target
stringlengths 5
300
| feat_repo_name
stringlengths 6
76
| text
stringlengths 26
1.05M
|
|---|---|---|
src/parser/rogue/shared/resources/ComboPointDetails.js
|
ronaldpereira/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Panel from 'interface/others/Panel';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import Icon from 'common/Icon';
import { formatPercentage } from 'common/format';
import ResourceBreakdown from 'parser/shared/modules/resourcetracker/ResourceBreakdown';
import ComboPointTracker from './ComboPointTracker';
const MINOR_THRESHOLD = 0.05;
const AVERAGE_THRESHOLD = 0.1;
const MAJOR_THRESHOLD = 0.2;
class ComboPointDetails extends Analyzer {
static dependencies = {
comboPointTracker: ComboPointTracker,
};
get wasted() {
return this.comboPointTracker.wasted || 0;
}
get total() {
return this.comboPointTracker.wasted + this.comboPointTracker.generated || 0;
}
get wastedPercent() {
return this.wasted / this.total || 0;
}
get suggestionThresholds() {
return {
actual: 1 - this.wastedPercent,
isLessThan: {
minor: 1 - MINOR_THRESHOLD,
average: 1 - AVERAGE_THRESHOLD,
major: 1 - MAJOR_THRESHOLD,
},
style: 'percentage',
};
}
statistic() {
return (
<StatisticBox
position={STATISTIC_ORDER.CORE(3)}
icon={<Icon icon="ability_rogue_masterofsubtlety" alt="Wasted Combo Points" />}
value={`${formatPercentage(this.wastedPercent)} %`}
label="Wasted Combo Points"
tooltip={`You wasted ${this.wasted} out of ${this.total} Combo Points. Some waste is expected due to the random nature of some generation abilities.`}
/>
);
}
tab() {
return {
title: 'Combo Point usage',
url: 'combo-points',
render: () => (
<Panel>
<ResourceBreakdown
tracker={this.comboPointTracker}
showSpenders
/>
</Panel>
),
};
}
}
export default ComboPointDetails;
|
Phishing/twitter/facebook/Welcome to Facebook - Log In, Sign Up or Learn More_files/tBB9JeD6K85.js
|
JohnTroony/Scriptology
|
/*!CK:2597761903!*//*1415130032,*/
if (self.CavalryLogger) { CavalryLogger.start_js(["u71Ms"]); }
__d("StickerConstants",[],function(a,b,c,d,e,f){e.exports={MOBILE_LIKE_STICKER_PACK_ID:"227877430692340",GRAVEYARD_PACK_ID:"604597256247273",LIKE_STICKER_ID:"227878347358915",HOT_LIKE_SMALL_STICKER_ID:"369239263222822",HOT_LIKE_MEDIUM_STICKER_ID:"369239343222814",HOT_LIKE_LARGE_STICKER_ID:"369239383222810",MRU_STICKER_PACK:"599061016853145",SEARCH_PACK_ID:"680229632032514",SPRITE_PADDING:"24",PayloadSource:{VIEW_ACTION:"view-action"},ActionTypes:{ADD_PACK:"ADD_PACK",REMOVE_PACK:"REMOVE_PACK",SELECT_PACK:"SELECT_PACK",RESET_NUM_NEW_PACKS:"RESET_NUM_NEW_PACKS"},EMOTICON_PACK_ID:"1471127876485636"};},null);
__d("TrackingNodeTypes",[],function(a,b,c,d,e,f){e.exports={HEADLINE:1,USER_NAME:2,ACTOR_PHOTO:3,ACTION_LINKS:4,LIKE_LINK:5,UNLIKE_LINK:6,PARTICIPANT:7,PRONOUN:8,ROBOTEXT:9,TITLE:10,MEDIA_GENERIC:11,PHOTO:12,VIDEO:13,MUSIC:14,ATTACHMENT:15,NAME_LIST:16,SHARE_LINK:17,USER_MESSAGE:18,SUBTITLE:19,DESCRIPTION:20,SOURCE:21,BLINGBOX:22,OTHER:23,VIEW_ALL_COMMENTS:24,COMMENT:25,COMMENT_LINK:26,SMALL_ACTOR_PHOTO:27,SUBSTORY:28,XBUTTON:29,HIDE_LINK:30,REPORT_SPAM_LINK:31,HIDE_ALL_LINK:32,BAD_AGGREGATION_LINK:33,ADD_COMMENT_BOX:34,APP_CALL_TO_ACTION:35,UFI:36,OG_LEFT_SLIDE_PAGER:37,OG_RIGHT_SLIDE_PAGER:38,EXP_CALL_TO_ACTION:39,LARGE_MEDIA_ATTACHMENT:40,FAN_PAGE:42,UNFAN_PAGE:43,SEE_MORE:44,COLLECTION_ROBOTEXT_LINK:45,COLLECTION_ACTION_LINK:46,COLLECTION_TICKER_LINK:47,SPONSORED_LINK:49,PAGE_LINK:50,SOCIAL_CONTEXT:51,SOCIAL_ACTOR_PHOTO:52,OFFERS_CLAIM:53,OFFERS_CLICK:54,DROPDOWN_BUTTON:55,EVENT_VIEW:56,EVENT_RSVP:57,ADS_SHIMMED_LINK:58,COLLECTION_ADD_BUTTON:59,EVENT_INVITE_FRIENDS:60,RHC_AD:61,AD_CREATIVE_TITLE:62,AD_CREATIVE_BODY:63,AD_CREATIVE_IMAGE:64,AD_SOCIAL_SENTENCE:65,APP_NAME:66,GROUP_JOIN:67,PAGE_COVER_PHOTO:68,PAGE_PROFILE_PIC:69,AD_IDENTITY:70,UNHIDE_LINK:71,TRENDING_TOPIC_LINK:72,RELATED_SHARE_ARTICLE:73,OFFERS_USE_NOW:74,RELATED_SHARE_VIDEO:75,RHC_CARD:76,RHC_CARD_HIDE:77,RHC_SIMPLIFICATION:78,RHC_SIMPLIFICATION_HIDE:79,TOPIC_PIVOT_HEADER:80,ADD_FRIEND_BUTTON:81,SNOWLIFT:82,SNOWLIFT_MESSAGE:83,OFFERS_RESEND:84,RHC_LINK_OPEN:85,GENERIC_CALL_TO_ACTION_BUTTON:86,AD_LOGOUT:87,RHC_PHOTO_SLIDER:88,RHC_COMMENT_BUTTON:89,HASHTAG:90,NOTE:91,RELATED_SHARE_ARTICLE_HIDE:92,RELATED_SHARE_VIDEO_HIDE:93,NEKO_PREVIEW:94,OG_COMPOSER_OBJECT:95,INSTALL_ACTION:96,SPONSORED_CONTEXT:97,DIGITAL_GOOD:98,STORY_FOOTER:99,STORY_LOCATION:100,ADD_PHOTO_ACTION:101,ACTION_ICON:102,EGO_FEED_UNIT:103,PLACE_STAR_SURVEY:104,REVIEW_MENU:105,SAVE_ACTION:106,PHOTO_GALLERY:107,SUB_ATTACHMENT:108,FEEDBACK_SECTION:109,ALBUM:110,ALBUM_COLLAGE:111,AVATAR_LIST:112,STORY_LIST:113,MEDIA_CONTROLS:114,ZERO_UPSELL_BUY:115,ZERO_UPSELL_FEED_UNIT:116,RATING:117,PERMALINK_COMMENT:118,LIKE_COUNT:119,RETRY_BUTTON:120,TIMELINE_GIFTS:121,NEARBY_FRIENDS_LIST:122,PRESENCE_UNIT:123,EVENT_INVITE_SENT:124,ATTACHMENT_TITLE:125,HSCROLL_PAGER:126,STORY_MESSAGE:127,STATUS_LINK:128,ADD_MEDIA_LINK:129,ADD_QUESTION_LINK:130,START_Q_AND_A_LINK:131,UPLOAD_FILE_LINK:132,START_CONVERSATION_LINK:133,ATTACH_LIFE_EVENT_LINK:134,ATTACH_PLACE_LINK:135,COVER_PHOTO_EDIT_LINK:136,SHOW_LIKES:137,ROTATE_LEFT_BUTTON:138,ROTATE_RIGHT_BUTTON:139,TAG_LINK:140,CLOSE_BUTTON:141,PAGER_NEXT:142,PAGER_PREVIOUS:143,FULLSCREEN_BUTTON:144,ACTIONS:145,CURATION_MENU:146,PROFILE_PIC_EDIT_LINK:147,VIEW_ALL_SHARES:148,THUMBNAIL_LINK:149,EDIT_HISTORY:150,ADD_TO_THREAD:151,SIDEBAR:152,HOME_SIDENAV:153,BUDDYLIST_NUB:154,TITLEBAR:155,SEND_BUTTON:156,CONVERSATION:157,CHAT_FLYOUT:158,INPUT:159,EMOTICONS:160,VIDEOCHAT:161,TYPEAHEAD:162,OPTIONS_MENU:163,BOOST_POST_BUTTON:164,TOGGLE_BUTTON:165,CHAT_SIDEBAR_FOOTER:166,GRIPPER:167,BOOKMARK_ITEM:168,BOOKMARKS_SECTION:169,BOOKMARKS_NAV:170,RHC:171,RHC_HEADER:172,SIDE_ADS:173,BUDDY_LIST:174,CONTENT_ROLL:175,SHOW_ADS_FEED:184,VIDEO_IN_PLAY_CALL_TO_ACTION_BUTTON:185,VIDEO_ENDSCREEN_CALL_TO_ACTION_BUTTON:186,INLINE_PHOTO_PIVOTS_HIDE:187,VIDEO_CALL_TO_ACTION_ENDSCREEN_REPLAY:188,APP_ATTACHMENT:189,ACTIVITY_LINK:190,SAVE_BUTTON:191,SEE_MORE_PHOTO_PAGE_POST_BUTTON:192,BUY_VIRTUAL_GOOD:193,SAVE_SECONDARY_MENU:194,MPP_INSIGHTS:195,WAP_FOOTER:196,GROUP_CANCEL:197,GROUP_LEAVE:198,MESSAGE_LINK:199,VIDEO_SPONSORSHIP_LABEL:200,MULTI_ATTACHMENT_PAGER_NEXT:201,MULTI_ATTACHMENT_PAGER_PREV:202,UNUSED:-1};},null);
__d("Keys",[],function(a,b,c,d,e,f){e.exports={BACKSPACE:8,TAB:9,RETURN:13,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,COMMA:188,PERIOD:190,A:65,Z:90};},null);
__d("AjaxRequest",["ErrorUtils","Keys","URI","UserAgent_DEPRECATED","getSameOriginTransport","setTimeoutAcrossTransitions","PHPQuerySerializer","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){function o(s,t,u){this.xhr=k();if(!(t instanceof i))t=new i(t);if(u&&s=='GET'){t.setQueryData(u);}else this._params=u;this.method=s;this.uri=t;this.xhr.open(s,t);}var p=window.XMLHttpRequest&&('withCredentials' in new XMLHttpRequest());o.supportsCORS=function(){return p;};o.ERROR='ar:error';o.TIMEOUT='ar:timeout';o.PROXY_ERROR='ar:proxy error';o.TRANSPORT_ERROR='ar:transport error';o.SERVER_ERROR='ar:http error';o.PARSE_ERROR='ar:parse error';o._inflight=[];function q(){var s=o._inflight;o._inflight=[];s.forEach(function(t){t.abort();});}function r(s){s.onJSON=s.onError=s.onSuccess=null;clearTimeout(s._timer);if(s.xhr&&s.xhr.readyState<4){s.xhr.abort();s.xhr=null;}o._inflight=o._inflight.filter(function(t){return t&&t!=s&&t.xhr&&t.xhr.readyState<4;});}n(o.prototype,{timeout:60000,streamMode:true,prelude:/^for \(;;\);/,status:null,_eol:-1,_call:function(s){if(this[s])this[s](this);},_parseStatus:function(){var s;try{this.status=this.xhr.status;s=this.xhr.statusText;}catch(t){if(this.xhr.readyState>=4){this.errorType=o.TRANSPORT_ERROR;this.errorText=t.message;}return;}if(this.status===0&&!(/^(file|ftp)/.test(this.uri))){this.errorType=o.TRANSPORT_ERROR;}else if(this.status>=100&&this.status<200){this.errorType=o.PROXY_ERROR;}else if(this.status>=200&&this.status<300){return;}else if(this.status>=300&&this.status<400){this.errorType=o.PROXY_ERROR;}else if(this.status>=400&&this.status<500){this.errorType=o.SERVER_ERROR;}else if(this.status>=500&&this.status<600){this.errorType=o.PROXY_ERROR;}else if(this.status==1223){return;}else if(this.status>=12001&&this.status<=12156){this.errorType=o.TRANSPORT_ERROR;}else{s='unrecognized status code: '+this.status;this.errorType=o.ERROR;}if(!this.errorText)this.errorText=s;},_parseResponse:function(){var s,t=this.xhr.readyState;try{s=this.xhr.responseText||'';}catch(u){if(t>=4){this.errorType=o.ERROR;this.errorText='responseText not available - '+u.message;}return;}while(this.xhr){var v=this._eol+1,w=this.streamMode?s.indexOf('\n',v):s.length;if(w<0&&t==4)w=s.length;if(w<=this._eol)break;var x=s;if(this.streamMode)x=s.substr(v,w-v).replace(/^\s*|\s*$/g,'');if(v===0&&this.prelude)if(this.prelude.test(x))x=x.replace(this.prelude,'');this._eol=w;if(x){try{this.json=JSON.parse(x);}catch(u){var y=(/(<body[\S\s]+?<\/body>)/i).test(s)&&RegExp.$1,z={message:u.message,'char':v,excerpt:((v===0&&y)||x).substr(512)};this.errorType=o.PARSE_ERROR;this.errorText='parse error - '+JSON.stringify(z);return;}g.applyWithGuard(this._call,this,['onJSON']);}}},_onReadyState:function(){var s=this.xhr&&this.xhr.readyState||0;if(this.status==null&&s>=2)this._parseStatus();if(!this.errorType&&this.status!=null)if((s==3&&this.streamMode)||s==4)this._parseResponse();if(this.errorType||s==4){this._time=Date.now()-this._sentAt;this._call(!this.errorType?'onSuccess':'onError');r(this);}},send:function(s){this.xhr.onreadystatechange=function(){g.applyWithGuard(this._onReadyState,this,arguments);}.bind(this);var t=this.timeout;if(t)this._timer=l((function(){this.errorType=o.TIMEOUT;this.errorText='timeout';this._time=Date.now()-this._sentAt;this._call('onError');r(this);}).bind(this),t);o._inflight.push(this);if(this.method=='POST')this.xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');this._sentAt=Date.now();this.xhr.send(s?m.serialize(s):'');},abort:function(){r(this);},toString:function(){var s='[AjaxRequest readyState='+this.xhr.readyState;if(this.errorType)s+=' errorType='+this.errorType+' ('+this.errorText+')';return s+']';},toJSON:function(){var s={json:this.json,status:this.status,errorType:this.errorType,errorText:this.errorText,time:this._time};if(this.errorType)s.uri=this.uri;for(var t in s)if(s[t]==null)delete s[t];return s;}});if(window.addEventListener&&j.firefox())window.addEventListener('keydown',function(event){if(event.keyCode===h.ESC)event.prevent();},false);if(window.attachEvent)window.attachEvent('onunload',q);e.exports=o;},null);
__d("FBAjaxRequest",["AjaxRequest","copyProperties","getAsyncParams"],function(a,b,c,d,e,f,g,h,i){function j(k,l,m){m=h(i(k),m);var n=new g(k,l,m);n.streamMode=false;var o=n._call;n._call=function(p){if(p=='onJSON'&&this.json){if(this.json.error){this.errorType=g.SERVER_ERROR;this.errorText='AsyncResponse error: '+this.json.error;}this.json=this.json.payload;}o.apply(this,arguments);};n.ajaxReqSend=n.send;n.send=function(p){this.ajaxReqSend(h(p,m));};return n;}e.exports=j;},null);
__d("CallbackManagerController",["ErrorUtils","copyProperties"],function(a,b,c,d,e,f,g,h){var i=function(j){this._pendingIDs=[];this._allRequests=[undefined];this._callbackArgHandler=j;};h(i.prototype,{executeOrEnqueue:function(j,k,l){l=l||{};var m=this._attemptCallback(k,j,l);if(m)return 0;this._allRequests.push({fn:k,request:j,options:l});var n=this._allRequests.length-1;this._pendingIDs.push(n);return n;},unsubscribe:function(j){delete this._allRequests[j];},reset:function(){this._allRequests=[];},getRequest:function(j){return this._allRequests[j];},runPossibleCallbacks:function(){var j=this._pendingIDs;this._pendingIDs=[];var k=[];j.forEach(function(l){var m=this._allRequests[l];if(!m)return;if(this._callbackArgHandler(m.request,m.options)){k.push(l);}else this._pendingIDs.push(l);}.bind(this));k.forEach(function(l){var m=this._allRequests[l];delete this._allRequests[l];this._attemptCallback(m.fn,m.request,m.options);}.bind(this));},_attemptCallback:function(j,k,l){var m=this._callbackArgHandler(k,l);if(m){var n={ids:k};g.applyWithGuard(j,n,m);}return !!m;}});e.exports=i;},null);
__d("Deferred",[],function(a,b,c,d,e,f){var g=0,h=1,i=2,j=4,k='callbacks',l='errbacks',m='cancelbacks',n='completeCallbacks',o=[],p=o.slice,q=o.unshift;function r(u,v){return u?p.call(u,v):o;}function s(u,v){return v<u.length?r(u,v):o;}function t(){"use strict";this.$Deferred0=g;}t.prototype.addCallback=function(u,v){"use strict";return this.$Deferred1(h,this.$Deferred2(k),u,v,s(arguments,2));};t.prototype.removeCallback=function(u,v){"use strict";return this.$Deferred3(this.$Deferred2(k),u,v);};t.prototype.addCompleteCallback=function(u,v){"use strict";return this.$Deferred1(null,this.$Deferred2(n),u,v,s(arguments,2));};t.prototype.removeCompleteCallback=function(u,v){"use strict";return this.$Deferred3(this.$Deferred2(n),u,v);};t.prototype.addErrback=function(u,v){"use strict";return this.$Deferred1(i,this.$Deferred2(l),u,v,s(arguments,2));};t.prototype.removeErrback=function(u,v){"use strict";return this.$Deferred3(this.$Deferred2(l),u,v);};t.prototype.addCancelback=function(u,v){"use strict";return this.$Deferred1(j,this.$Deferred2(m),u,v,s(arguments,2));};t.prototype.removeCancelback=function(u,v){"use strict";return this.$Deferred3(this.$Deferred2(m),u,v);};t.prototype.getStatus=function(){"use strict";return this.$Deferred0;};t.prototype.setStatus=function(u){"use strict";var v;this.$Deferred0=u;this.callbackArgs=r(arguments,1);if(u===i){v=l;}else if(u===h){v=k;}else if(u===j)v=m;if(v)this.$Deferred4(this[v],this.callbackArgs);this.$Deferred4(this[n],this.callbackArgs);return this;};t.prototype.setTimeout=function(u){"use strict";if(this.timeout)this.clearTimeout();this.$Deferred5=this.$Deferred5||this.fail.bind(this);this.timeout=window.setTimeout(this.$Deferred5,u);};t.prototype.clearTimeout=function(){"use strict";window.clearTimeout(this.timeout);delete this.timeout;};t.prototype.succeed=function(){"use strict";return this.$Deferred6(h,arguments);};t.prototype.fail=function(){"use strict";return this.$Deferred6(i,arguments);};t.prototype.cancel=function(){"use strict";delete this[k];delete this[l];return this.$Deferred6(j,arguments);};t.prototype.$Deferred6=function(u,v){"use strict";q.call(v,u);return this.setStatus.apply(this,v);};t.prototype.$Deferred2=function(u){"use strict";return this[u]||(this[u]=[]);};t.prototype.then=function(u,v,w,x){"use strict";var y=new t(),u,z,aa,ba=r(arguments,0);if(typeof ba[0]==='function')u=ba.shift();if(typeof ba[0]==='function')z=ba.shift();if(typeof ba[0]==='function')aa=ba.shift();var ca=ba.shift();if(u){var da=[this.$Deferred7,this,y,'succeed',u,ca].concat(ba);this.addCallback.apply(this,da);}else this.addCallback(y.succeed,y);if(z){var ea=[this.$Deferred7,this,y,'fail',z,ca].concat(ba);this.addErrback.apply(this,ea);}else this.addErrback(y.fail,y);if(aa){var fa=[this.$Deferred7,this,y,'cancel',aa,ca].concat(ba);this.addCancelback.apply(this,fa);}else this.addCancelback(y.cancel,y);return y;};t.prototype.$Deferred1=function(u,v,w,x,y){"use strict";var z=this.getStatus();if((!u&&z!==g)||z===u){w.apply(x||this,y.concat(this.callbackArgs));}else v.push(w,x,y);return this;};t.prototype.$Deferred3=function(u,v,w){"use strict";for(var x=0;x<u.length;x+=3)if(u[x]===v&&(!w||u[x+1]===w)){u.splice(x,3);if(w)break;x-=3;}return this;};t.prototype.pipe=function(u){"use strict";this.addCallback(u.succeed,u).addErrback(u.fail,u).addCancelback(u.cancel,u);};t.prototype.$Deferred4=function(u,v){"use strict";for(var w=0;w<(u||o).length;w+=3)u[w].apply(u[w+1]||this,(u[w+2]||o).concat(v));};t.prototype.$Deferred7=function(u,v,w,x){"use strict";var y=r(arguments,4),z=w.apply(x,y);if(z instanceof t){z.pipe(u);}else u[v](z);};t.STATUS_UNKNOWN=g;t.STATUS_SUCCEEDED=h;t.STATUS_CANCELED=j;t.STATUS_FAILED=i;e.exports=t;},null);
__d("KeyedCallbackManager",["CallbackManagerController","Deferred","ErrorUtils","copyProperties"],function(a,b,c,d,e,f,g,h,i,j){var k=function(){this._resources={};this._controller=new g(this._constructCallbackArg.bind(this));};j(k.prototype,{executeOrEnqueue:function(l,m){if(!(l instanceof Array)){var n=l,o=m;l=[l];m=function(p){o(p[n]);};}l=l.filter(function(p){var q=(p!==null&&p!==undefined);if(!q)i.applyWithGuard(function(){throw new Error('KeyedCallbackManager.executeOrEnqueue: key '+JSON.stringify(p)+' is invalid');});return q;});return this._controller.executeOrEnqueue(l,m);},deferredExecuteOrEnqueue:function(l){var m=new h();this.executeOrEnqueue(l,m.succeed.bind(m));return m;},unsubscribe:function(l){this._controller.unsubscribe(l);},reset:function(){this._controller.reset();this._resources={};},getUnavailableResources:function(l){var m=this._controller.getRequest(l),n=[];if(m)n=m.request.filter(function(o){return !this._resources[o];}.bind(this));return n;},getUnavailableResourcesFromRequest:function(l){var m=Array.isArray(l)?l:[l];return m.filter(function(n){if(n!==null&&n!==undefined)return !this._resources[n];},this);},addResourcesAndExecute:function(l){j(this._resources,l);this._controller.runPossibleCallbacks();},setResource:function(l,m){this._resources[l]=m;this._controller.runPossibleCallbacks();},getResource:function(l){return this._resources[l];},getAllResources:function(){return this._resources;},dumpResources:function(){var l={};for(var m in this._resources){var n=this._resources[m];if(typeof n==='object')n=j({},n);l[m]=n;}return l;},_constructCallbackArg:function(l){var m={};for(var n=0;n<l.length;n++){var o=l[n],p=this._resources[o];if(typeof p=='undefined')return false;m[o]=p;}return [m];}});e.exports=k;},null);
__d("BaseAsyncLoader",["KeyedCallbackManager","copyProperties"],function(a,b,c,d,e,f,g,h){var i={};function j(l,m,n){var o=new g(),p=false,q=[];function r(){if(!q.length||p)return;p=true;setTimeout(t,0);}function s(w){p=false;w.forEach(o.unsubscribe.bind(o));r();}function t(){var w={},x=[];q=q.filter(function(z){var aa=o.getUnavailableResources(z);if(aa.length){aa.forEach(function(ba){w[ba]=true;});x.push(z);return true;}return false;});var y=Object.keys(w);if(y.length){n(l,y,x,u.bind(null,x),v.bind(null,x));}else p=false;}function u(w,x){var y=x.payload[m]||x.payload;o.addResourcesAndExecute(y);s(w);}function v(w){s(w);}return {get:function(w,x){var y=o.executeOrEnqueue(w,x),z=o.getUnavailableResources(y);if(z.length){q.push(y);r();}},getCachedKeys:function(){return Object.keys(o.getAllResources());},getNow:function(w){return o.getResource(w)||null;},set:function(w){o.addResourcesAndExecute(w);}};}function k(l,m){throw ('BaseAsyncLoader can\'t be instantiated');}h(k.prototype,{_getLoader:function(){if(!i[this._endpoint])i[this._endpoint]=j(this._endpoint,this._type,this.send);return i[this._endpoint];},get:function(l,m){return this._getLoader().get(l,m);},getCachedKeys:function(){return this._getLoader().getCachedKeys();},getNow:function(l){return this._getLoader().getNow(l);},reset:function(){i[this._endpoint]=null;},set:function(l){this._getLoader().set(l);}});e.exports=k;},null);
__d("AjaxLoader",["copyProperties","FBAjaxRequest","BaseAsyncLoader"],function(a,b,c,d,e,f,g,h,i){function j(k,l){this._endpoint=k;this._type=l;}g(j.prototype,i.prototype);j.prototype.send=function(k,l,m,n,o){var p=new h('GET',k,{ids:l});p.onJSON=function(q){n({payload:q.json});};p.onError=o;p.send();};e.exports=j;},null);
__d("JSLogger",[],function(a,b,c,d,e,f){var g={MAX_HISTORY:500,counts:{},categories:{},seq:0,pageId:(Math.random()*2147483648|0).toString(36),forwarding:false};function h(m){if(m=='/'||m.indexOf('/',1)<0)return false;var n=/^\/(v\d+\.\d\d?|head)\//.test(m);if(n)return (/^\/(dialog|plugins)\//).test(m.substring(m.indexOf('/',1)));return (/^\/(dialog|plugins)\//).test(m);}function i(m){if(m instanceof Error&&a.ErrorUtils)m=a.ErrorUtils.normalizeError(m);try{return JSON.stringify(m);}catch(n){return '{}';}}function j(m,event,n){if(!g.counts[m])g.counts[m]={};if(!g.counts[m][event])g.counts[m][event]=0;n=n==null?1:Number(n);g.counts[m][event]+=isFinite(n)?n:0;}g.logAction=function(event,m,n){if(this.type=='bump'){j(this.cat,event,m);}else if(this.type=='rate'){(m&&j(this.cat,event+'_n',n));j(this.cat,event+'_d',n);}else{var o={cat:this.cat,type:this.type,event:event,data:m!=null?i(m):null,date:Date.now(),seq:g.seq++};g.head=g.head?(g.head.next=o):(g.tail=o);while(g.head.seq-g.tail.seq>g.MAX_HISTORY)g.tail=g.tail.next;return o;}};function k(m){if(!g.categories[m]){g.categories[m]={};var n=function(o){var p={cat:m,type:o};g.categories[m][o]=function(){g.forwarding=false;var q=null;if(document.domain!='facebook.com')return;q=g.logAction;if(h(location.pathname)){g.forwarding=false;}else try{q=a.top.require('JSLogger')._.logAction;g.forwarding=q!==g.logAction;}catch(r){}(q&&q.apply(p,arguments));};};n('debug');n('log');n('warn');n('error');n('bump');n('rate');}return g.categories[m];}function l(m,n){var o=[];for(var p=n||g.tail;p;p=p.next)if(!m||m(p)){var q={type:p.type,cat:p.cat,date:p.date,event:p.event,seq:p.seq};if(p.data)q.data=JSON.parse(p.data);o.push(q);}return o;}e.exports={_:g,DUMP_EVENT:'jslogger/dump',create:k,getEntries:l};},null);
__d("ES6Promise",["setImmediate"],function(a,b,c,d,e,f){e.exports=(function(g,h){'use strict';var i=b('setImmediate'),j='pending',k='fulfilled',l='rejected',m='__slots$'+Math.random().toString(36).slice(2);function n(v){var w=v[m];if(!w){v[m]=w={};if(Object.defineProperty)try{Object.defineProperty(v,m,{value:w});}catch(x){}}return w;}function o(v){return v;}function p(v){throw v;}function q(v){var w=n(this);w.state=j;w.fulfillReactions=[];w.rejectReactions=[];var x=r(this),y=x.reject;try{v(x.resolve,y);}catch(z){y(z);}}function r(v){var w=false;return {resolve:function(x){if(!w){w=true;if(x===v)return s(v,l,new TypeError('Cannot resolve promise with itself'));if(!x||typeof x!=="object"||typeof x.then!=="function")return s(v,k,x);var y=r(v),z=y.reject;try{x.then(y.resolve,z);}catch(aa){z(aa);}}},reject:function(x){if(!w){w=true;s(v,l,x);}}};}function s(v,w,x){var y=n(v);if(y.state!==j)throw new Error('Settling a '+y.state+' promise');var z;if(w===k){z=y.fulfillReactions;}else if(w===l)z=y.rejectReactions;y.result=x;y.fulfillReactions=h;y.rejectReactions=h;y.state=w;var aa=z.length;aa&&i(function(){for(var ba=0;ba<aa;++ba)z[ba](y.result);});}q.all=function(v){var w=this;return new w(function(x,y){var z=[],aa=0;v.forEach(function(ba,ca){++aa;w.resolve(ba).then(function(da){if(!z.hasOwnProperty(ca)){z[ca]=da;--aa||x(z);}},y);});aa||x(z);});};q.race=function(v){var w=this;return new w(function(x,y){v.forEach(function(z){w.resolve(z).then(x,y);});});};q.resolve=function(v){return v instanceof q&&v.constructor===this?v:new this(function(w){w(v);});};q.reject=function(v){return new this(function(w,x){x(v);});};var t=q.prototype;t.then=function(v,w){var x,y,z=new this.constructor(function(ca,da){x=ca;y=da;});if(typeof x!=="function")throw new TypeError('Uncallable Promise resolve function');if(typeof y!=="function")throw new TypeError('Uncallable Promise reject function');if(v===h||v===null)v=o;if(w===h||w===null)w=p;var aa=n(this),ba=aa.state;if(ba===j){aa.fulfillReactions.push(u(x,y,v));aa.rejectReactions.push(u(x,y,w));}else if(ba===k||ba===l)i(u(x,y,ba===k?v:w,aa.result));return z;};function u(v,w,x,y){var z=arguments.length>3;return function(aa){try{aa=x(z?y:aa);}catch(ba){w(ba);return;}v(aa);};}t["catch"]=function(v){return this.then(h,v);};t.toString=function(){return '[object Promise]';};return q;}(Function('return this')()));},null);
__d("throwImmediate",["setImmediate"],function(a,b,c,d,e,f,g){'use strict';function h(j){throw j;}function i(j){g(h,j);}e.exports=i;},null);
__d("Promise",["ES6Promise","invariant","throwImmediate"],function(a,b,c,d,e,f,g,h,i){var j=g.prototype;j["finally"]=function(k){return this.then(k,k);};j.done=function(k,l){this.then(k,l).then(null,i);};g.allObject=function(k){h(!Array.isArray(k));var l=Object.keys(k);return g.all(l.map(function(m){return k[m];})).then(function(m){var n={};m.forEach(function(o,p){n[l[p]]=o;});return n;});};e.exports=g;},null);
__d("XControllerURIBuilder",["URI","invariant"],function(a,b,c,d,e,f,g,h){function i(j,k){"use strict";this.$XControllerURIBuilder0=j;this.$XControllerURIBuilder1=k;this.$XControllerURIBuilder2={};}i.prototype.setInt=function(j,k){"use strict";return this.__setParam(j,'Int',k);};i.prototype.setFloat=function(j,k){"use strict";return this.__setParam(j,'Float',k);};i.prototype.setString=function(j,k){"use strict";return this.__setParam(j,'String',k);};i.prototype.setExists=function(j,k){"use strict";if(k===false)k=undefined;return this.__setParam(j,'Exists',k);};i.prototype.setBool=function(j,k){"use strict";return this.__setParam(j,'Bool',k);};i.prototype.setEnum=function(j,k){"use strict";return this.__setParam(j,'Enum',k);};i.prototype.setIntVector=function(j,k){"use strict";return this.__setParam(j,'IntVector',k);};i.prototype.setFloatVector=function(j,k){"use strict";return this.__setParam(j,'FloatVector',k);};i.prototype.setStringVector=function(j,k){"use strict";return this.__setParam(j,'StringVector',k);};i.prototype.setEnumVector=function(j,k){"use strict";return this.__setParam(j,'EnumVector',k);};i.prototype.setIntToIntMap=function(j,k){"use strict";return this.__setParam(j,'IntToIntMap',k);};i.prototype.setIntToFloatMap=function(j,k){"use strict";return this.__setParam(j,'IntToFloatMap',k);};i.prototype.setIntToStringMap=function(j,k){"use strict";return this.__setParam(j,'IntToStringMap',k);};i.prototype.setIntToBoolMap=function(j,k){"use strict";return this.__setParam(j,'IntToBoolMap',k);};i.prototype.setStringToIntMap=function(j,k){"use strict";return this.__setParam(j,'StringToIntMap',k);};i.prototype.setStringToFloatMap=function(j,k){"use strict";return this.__setParam(j,'StringToFloatMap',k);};i.prototype.setStringToStringMap=function(j,k){"use strict";return this.__setParam(j,'StringToStringMap',k);};i.prototype.setStringToBoolMap=function(j,k){"use strict";return this.__setParam(j,'StringToBoolMap',k);};i.prototype.setHackType=function(j,k){"use strict";return this.__setParam(j,'HackType',k);};i.prototype.__validateRequiredParamsExistence=function(){"use strict";for(var j in this.$XControllerURIBuilder1)h(!this.$XControllerURIBuilder1[j].required||this.$XControllerURIBuilder2.hasOwnProperty(j));};i.prototype.__setParam=function(j,k,l){"use strict";h(j in this.$XControllerURIBuilder1);var m=this.$XControllerURIBuilder1[j].type;h(m===k);this.__setParamInt(j,l);return this;};i.prototype.__setParamInt=function(j,k){"use strict";this.$XControllerURIBuilder2[j]=k;};i.prototype.getURI=function(){"use strict";this.__validateRequiredParamsExistence();var j={},k='',l=new RegExp(/^\{(\?)?(\*)?(.+?)\}$/),m=this.$XControllerURIBuilder0.split('/'),n=false;for(var o=0;o<m.length;o++){var p=m[o];if(p==='')continue;var q=l.exec(p);if(!q){k+='/'+p;}else{var r=q[1]==='?',s=q[2]==='*',t=q[3],u=this.$XControllerURIBuilder1[t];h(u);if(r&&n)continue;var v=this.$XControllerURIBuilder2[t];if(v==null&&r){n=true;continue;}h(v!=null);k+='/'+v;j[t]=true;}}if(this.$XControllerURIBuilder0.slice(-1)==='/')k+='/';var w=new g(k);for(u in this.$XControllerURIBuilder2){v=this.$XControllerURIBuilder2[u];if(!j[u]&&v!=null){var x=this.$XControllerURIBuilder1[u];w.addQueryData(u,x&&x.type==='Exists'?null:v);}}return w;};i.create=function(j,k){return i.bind(null,j,k);};e.exports=i;},null);
__d("XChatUserInfoAllAsyncControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/chat\/user_info_all\/",{viewer:{type:"Int",required:true}});},null);
__d("ShortProfilesBootstrapper",["AsyncRequest","BanzaiODS","CurrentUser","JSLogger","Promise","XChatUserInfoAllAsyncControllerURIBuilder"],function(a,b,c,d,e,f,g,h,i,j,k,l){'use strict';var m=5,n=10000,o=new l().setInt('viewer',i.getID()).getURI(),p=j.create('short_profiles');function q(r){this.$ShortProfilesBootstrapper0=r;this.$ShortProfilesBootstrapper1=new k(function(s,t){this.$ShortProfilesBootstrapper2=s;this.$ShortProfilesBootstrapper3=t;}.bind(this));this.$ShortProfilesBootstrapper4=false;this.$ShortProfilesBootstrapper5=null;this.$ShortProfilesBootstrapper6=0;this.$ShortProfilesBootstrapper7=0;this.$ShortProfilesBootstrapper8=0;this.$ShortProfilesBootstrapper9=false;this.$ShortProfilesBootstrappera=false;}q.prototype.fetchAll=function(){this.$ShortProfilesBootstrapperb();if(this.$ShortProfilesBootstrapper4||this.$ShortProfilesBootstrapper5)return this.$ShortProfilesBootstrapper1;if(this.$ShortProfilesBootstrapper6>=m){this.$ShortProfilesBootstrapperc();return this.$ShortProfilesBootstrapper1;}this.$ShortProfilesBootstrapper6++;this.$ShortProfilesBootstrapperd();this.$ShortProfilesBootstrapper5=new g(o).setHandler(function(r){this.$ShortProfilesBootstrapper5=null;this.$ShortProfilesBootstrapper4=true;this.$ShortProfilesBootstrappere();this.$ShortProfilesBootstrapper0(r.payload);this.$ShortProfilesBootstrapper2();}.bind(this)).setErrorHandler(function(){this.$ShortProfilesBootstrapper5=null;this.$ShortProfilesBootstrapper7++;this.$ShortProfilesBootstrapperf();}.bind(this)).setTimeoutHandler(n,function(){this.$ShortProfilesBootstrapper5=null;this.$ShortProfilesBootstrapper8++;this.$ShortProfilesBootstrapperg();}.bind(this));this.$ShortProfilesBootstrapper5.send();return this.$ShortProfilesBootstrapper1;};q.prototype.isBootstrapped=function(){return this.$ShortProfilesBootstrapper4;};q.prototype.isBootstrapping=function(){return !!this.$ShortProfilesBootstrapper5;};q.prototype.getAttemptCount=function(){return this.$ShortProfilesBootstrapper6;};q.prototype.getErrorCount=function(){return this.$ShortProfilesBootstrapper7;};q.prototype.getTimeoutCount=function(){return this.$ShortProfilesBootstrapper8;};q.prototype.$ShortProfilesBootstrapperb=function(){if(!this.$ShortProfilesBootstrapper9){p.log('bootstrap_start');h.bumpEntityKey('chat.web','typeahead.bootstrap.starts');this.$ShortProfilesBootstrapper9=true;}};q.prototype.$ShortProfilesBootstrapperd=function(){p.log('bootstrap_attempt');h.bumpEntityKey('chat.web','typeahead.bootstrap.attempts');};q.prototype.$ShortProfilesBootstrappere=function(){p.log('bootstrap_success');h.bumpEntityKey('chat.web','typeahead.bootstrap.successes');if(this.$ShortProfilesBootstrapper6>1)h.bumpEntityKey('chat.web','typeahead.bootstrap.successes_after_retries');};q.prototype.$ShortProfilesBootstrapperf=function(){p.log('bootstrap_error');h.bumpEntityKey('chat.web','typeahead.bootstrap.errors');};q.prototype.$ShortProfilesBootstrapperg=function(){p.log('bootstrap_timeout');h.bumpEntityKey('chat.web','typeahead.bootstrap.timeouts');};q.prototype.$ShortProfilesBootstrapperc=function(){if(!this.$ShortProfilesBootstrappera){p.log('bootstrap_giveup');h.bumpEntityKey('chat.web','typeahead.bootstrap.giveups');this.$ShortProfilesBootstrappera=true;this.$ShortProfilesBootstrapper3();}};e.exports=q;},null);
__d("XChatUserInfoAsyncControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/chat\/user_info\/",{ids:{type:"IntVector"}});},null);
__d("ShortProfiles",["AjaxLoader","Arbiter","JSLogger","ShortProfilesBootstrapper","XChatUserInfoAsyncControllerURIBuilder"],function(a,b,c,d,e,f,g,h,i,j,k){var l=null,m=new g(new k().getURI().toString(),'profiles'),n={get:function(p,q){this.getMulti([p],function(r){q(r[p],p);});},getMulti:function(p,q){function r(s){q(o(s));}m.get(p,r);},getNow:function(p){return o(m.getNow(p)||null);},getNowUnsafe:function(p){return m.getNow(p)||null;},getCachedProfileIDs:function(){return m.getCachedKeys();},hasAll:function(){return !!l&&l.isBootstrapped();},fetchAll:function(){if(!l)l=new j(function(p){m.set(p);});return l.fetchAll();},set:function(p,q){var r={};r[p]=q;this.setMulti(r);},setMulti:function(p){m.set(o(p));}};function o(p){return JSON.parse(JSON.stringify(p));}h.subscribe(i.DUMP_EVENT,function(p,q){var r=n.getCachedProfileIDs(),s=i.getEntries(function(t){return (t.cat=='short_profiles'||t.cat=='chat_typeahead');});q.chat_typeahead={bootstrapped:l&&l.isBootstrapped(),bootstrapping:l&&l.isBootstrapping(),bootstrap_attempts:l&&l.getAttemptCount(),bootstrap_errors:l&&l.getErrorCount(),bootstrap_timeouts:l&&l.getTimeoutCount(),entries:r,entry_count:r.length,history:s};});e.exports=n;},null);
__d("LiveTimer",["CSS","DOM","ServerTime","fbt","tx"],function(a,b,c,d,e,f,g,h,i,j,k){var l=1000,m=60,n=3600,o=43200,p=86400,q=60,r=20000,s={restart:function(t){i.update(t*1000);this.updateTimeStamps();},getApproximateServerTime:function(){return i.get();},getServerTimeOffset:function(){return -1*i.getSkew();},updateTimeStamps:function(){this.timestamps=h.scry(document.body,'abbr.livetimestamp');this.startLoop(r);},addTimeStamps:function(t){if(!t)return;this.timestamps=this.timestamps||[];if(h.isNodeOfType(t,'abbr')&&g.hasClass(t,'livetimestamp')){this.timestamps.push(t);}else{var u=h.scry(t,'abbr.livetimestamp');for(var v=0;v<u.length;++v)this.timestamps.push(u[v]);}this.startLoop(0);},startLoop:function(t){this.stop();this.timeout=setTimeout(function(){this.loop();}.bind(this),t);},stop:function(){clearTimeout(this.timeout);},loop:function(t){if(t)this.updateTimeStamps();var u=Math.floor(i.get()/l),v=-1;this.timestamps&&this.timestamps.forEach(function(x){var y=x.getAttribute('data-utime'),z=x.getAttribute('data-shorten'),aa=this.renderRelativeTime(u,y,z);if(aa.text)h.setContent(x,aa.text);if(aa.next!=-1&&(aa.next<v||v==-1))v=aa.next;}.bind(this));if(v!=-1){var w=Math.max(r,v*l);this.timeout=setTimeout(function(){this.loop();}.bind(this),w);}},renderRelativeTime:function(t,u,v){var w={text:"",next:-1};if(t-u>(p))return w;var x=t-u,y=Math.floor(x/m),z=Math.floor(y/q);if(y<1){if(v){w.text="Just now";w.next=20-x%20;}else{w.text="a few seconds ago";w.next=m-x%m;}return w;}if(z<1){if(v&&y==1){w.text="1 min";}else if(v){w.text=j._("{number} mins",[j.param("number",y)]);}else w.text=y==1?"about a minute ago":k._("{number} minutes ago",{number:y});w.next=m-x%m;return w;}if(z<11)w.next=n-x%n;if(v&&z==1){w.text="1 hr";}else if(v){w.text=j._("{number} hrs",[j.param("number",z)]);}else w.text=z==1?"about an hour ago":k._("{number} hours ago",{number:z});return w;},renderRelativeTimeToServer:function(t,u){return this.renderRelativeTime(Math.floor(i.get()/l),t,u);}};e.exports=s;e.exports.CONSTS={MS_IN_SEC:l,SEC_IN_MIN:m,SEC_IN_HOUR:n,SEC_IN_12_HOUR:o,SEC_IN_24_HOUR:p,MIN_IN_HOUR:q,HEARTBEAT:r};},null);
__d("UFICentralUpdates",["Arbiter","ChannelConstants","LiveTimer","ShortProfiles","UFIConstants","copyProperties","tx"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n=0,o={},p={},q={},r={},s=[];g.subscribe(h.getArbiterType('live-data'),function(x,y){if(y&&y.obj){var z=y.obj,aa=z.comments||[];aa.forEach(function(ba){ba.timestamp.text="a few seconds ago";});w.handleUpdate(k.UFIPayloadSourceType.LIVE_SEND,z);}});function t(){if(!n){var x=q,y=o,z=p,aa=r;q={};o={};p={};r={};if(Object.keys(x).length)v('feedback-id-changed',x);if(Object.keys(y).length)v('feedback-updated',y);if(Object.keys(z).length)v('comments-updated',z);if(Object.keys(aa).length)v('instance-updated',aa);s.pop();}}function u(){if(s.length){return s[s.length-1];}else return k.UFIPayloadSourceType.UNKNOWN;}function v(event,x){w.inform(event,{updates:x,payloadSource:u()});}var w=l(new g(),{handleUpdate:function(x,y){if(Object.keys(y).length)this.synchronizeInforms(function(){s.push(x);var z=l({payloadsource:u()},y);this.inform('update-feedback',z);this.inform('update-comment-lists',z);this.inform('update-comments',z);this.inform('update-actions',z);(y.profiles||[]).forEach(function(aa){j.set(aa.id,aa);});if(y.servertime)i.restart(y.servertime);}.bind(this));},didUpdateFeedback:function(x){o[x]=true;t();},didUpdateComment:function(x){p[x]=true;t();},didUpdateFeedbackID:function(x,y){q[x]=y;t();},didUpdateInstanceState:function(x,y){if(!r[x])r[x]={};r[x][y]=true;t();},synchronizeInforms:function(x){n++;try{x();}catch(y){throw y;}finally{n--;t();}}});e.exports=w;},null);
__d("randomInt",["invariant"],function(a,b,c,d,e,f,g){function h(i,j){var k=arguments.length;g(k>0&&k<=2);if(k===1){j=i;i=0;}g(j>i);var l=this.random||Math.random;return Math.floor(i+l()*(j-i));}e.exports=h;},null);
__d("ClientIDs",["randomInt"],function(a,b,c,d,e,f,g){var h={},i={getNewClientID:function(){var j=Date.now(),k=j+':'+(g(0,4294967295)+1);h[k]=true;return k;},isExistingClientID:function(j){return !!h[j];}};e.exports=i;},null);
__d("UFIFeedbackTargets",["ClientIDs","KeyedCallbackManager","UFICentralUpdates","UFIConstants","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k){var l=new h();function m(v){var w={};v.forEach(function(x){var y=k({},x);delete y.commentlist;delete y.commentcount;w[x.entidentifier]=y;i.didUpdateFeedback(x.entidentifier);});l.addResourcesAndExecute(w);}function n(v){for(var w=0;w<v.length;w++){var x=v[w];switch(x.actiontype){case j.UFIActionType.LIKE_ACTION:p(x);break;case j.UFIActionType.SUBSCRIBE_ACTION:q(x);break;case j.UFIActionType.DISABLE_COMMENTS:r(x);break;}}}function o(v){for(var w=0;w<v.length;w++){var x=v[w];if(x.orig_ftentidentifier)t(x.orig_ftentidentifier,x.ftentidentifier);}}function p(v){var w=s(v);if(w){v.hasviewerliked=!!v.hasviewerliked;if(v.clientid&&g.isExistingClientID(v.clientid)&&v.hasviewerliked!=w.hasviewerliked)return;w.likecount=v.likecount||0;w.likesentences=v.likesentences;if(v.actorid==w.actorforpost){w.hasviewerliked=v.hasviewerliked;}else if(v.hasviewerliked!=w.hasviewerliked){w.likesentences={current:v.likesentences.alternate,alternate:v.likesentences.current};if(w.hasviewerliked){w.likecount++;}else w.likecount--;}if(v.actorid!=w.actorforpost)w.likesentences.isunseen=true;m([w]);}}function q(v){var w=s(v);if(w){v.hasviewersubscribed=!!v.hasviewersubscribed;if(v.clientid&&g.isExistingClientID(v.clientid)&&v.hasviewersubscribed!=w.hasviewersubscribed)return;if(v.actorid==w.actorforpost)w.hasviewersubscribed=v.hasviewersubscribed;m([w]);}}function r(v){var w=s(v);if(w){w.cancomment=!!v.cancomment;m([w]);}}function s(v){if(v.orig_entidentifier)t(v.orig_entidentifier,v.entidentifier);return l.getResource(v.entidentifier);}function t(v,w){var x=l.getResource(v);if(x){l.setResource(v,null);x.entidentifier=w;l.setResource(w,x);i.didUpdateFeedbackID(v,w);}}var u={getFeedbackTarget:function(v,w){var x=l.executeOrEnqueue(v,w),y=l.getUnavailableResources(x);y.length;return x;},getActorIDForFeedbackTargetIfExists:function(v){var w=l.getResource(v);return w?w.actorforpost:null;},handleNFB:function(v,w){var x=l.getResource(v);if(x){x.nfbcount=w||0;m([x]);}},unsubscribe:function(v){l.unsubscribe(v);}};i.subscribe('update-feedback',function(v,w){var x=w.feedbacktargets;if(x&&x.length)m(x);});i.subscribe('update-actions',function(v,w){if(w.actions&&w.actions.length)n(w.actions);});i.subscribe('update-comments',function(v,w){if(w.comments&&w.comments.length)o(w.comments);});e.exports=u;},null);
__d("HovercardLink",["Bootloader","URI"],function(a,b,c,d,e,f,g,h){var i={getBaseURI:function(){return h('/ajax/hovercard/hovercard.php');},constructEndpoint:function(j,k){return i.constructEndpointWithGroupAndLocation(j,k,null);},constructEndpointWithLocation:function(j,k){return i.constructEndpointWithGroupAndLocation(j,null,k);},constructEndpointWithGroupAndLocation:function(j,k,l,m){g.loadModules(["Hovercard"],function(){});var n=new h(i.getBaseURI()).setQueryData({id:j.id}),o={};if((j.weakreference||m)&&k)o.group_id=k;if(l)o.hc_location=l;n.addQueryData({extragetparams:JSON.stringify(o)});return n;}};e.exports=i;},null);
__d("loadImage",[],function(a,b,c,d,e,f){"use strict";function g(h,i){var j=new Image();j.onload=function(){i(j.width,j.height,j);};j.src=h;}e.exports=g;},null);
__d("joinClasses",[],function(a,b,c,d,e,f){"use strict";function g(h){if(!h)h='';var i,j=arguments.length;if(j>1)for(var k=1;k<j;k++){i=arguments[k];if(i)h=(h?h+' ':'')+i;}return h;}e.exports=g;},null);
__d("DOMProperty",["invariant"],function(a,b,c,d,e,f,g){"use strict";function h(l,m){return (l&m)===m;}var i={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_SIDE_EFFECTS:4,HAS_BOOLEAN_VALUE:8,HAS_NUMERIC_VALUE:16,HAS_POSITIVE_NUMERIC_VALUE:32|16,HAS_OVERLOADED_BOOLEAN_VALUE:64,injectDOMPropertyConfig:function(l){var m=l.Properties||{},n=l.DOMAttributeNames||{},o=l.DOMPropertyNames||{},p=l.DOMMutationMethods||{};if(l.isCustomAttribute)k._isCustomAttributeFunctions.push(l.isCustomAttribute);for(var q in m){g(!k.isStandardName.hasOwnProperty(q));k.isStandardName[q]=true;var r=q.toLowerCase();k.getPossibleStandardName[r]=q;if(n.hasOwnProperty(q)){var s=n[q];k.getPossibleStandardName[s]=q;k.getAttributeName[q]=s;}else k.getAttributeName[q]=r;k.getPropertyName[q]=o.hasOwnProperty(q)?o[q]:q;if(p.hasOwnProperty(q)){k.getMutationMethod[q]=p[q];}else k.getMutationMethod[q]=null;var t=m[q];k.mustUseAttribute[q]=h(t,i.MUST_USE_ATTRIBUTE);k.mustUseProperty[q]=h(t,i.MUST_USE_PROPERTY);k.hasSideEffects[q]=h(t,i.HAS_SIDE_EFFECTS);k.hasBooleanValue[q]=h(t,i.HAS_BOOLEAN_VALUE);k.hasNumericValue[q]=h(t,i.HAS_NUMERIC_VALUE);k.hasPositiveNumericValue[q]=h(t,i.HAS_POSITIVE_NUMERIC_VALUE);k.hasOverloadedBooleanValue[q]=h(t,i.HAS_OVERLOADED_BOOLEAN_VALUE);g(!k.mustUseAttribute[q]||!k.mustUseProperty[q]);g(k.mustUseProperty[q]||!k.hasSideEffects[q]);g(!!k.hasBooleanValue[q]+!!k.hasNumericValue[q]+!!k.hasOverloadedBooleanValue[q]<=1);}}},j={},k={ID_ATTRIBUTE_NAME:'data-reactid',isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(l){for(var m=0;m<k._isCustomAttributeFunctions.length;m++){var n=k._isCustomAttributeFunctions[m];if(n(l))return true;}return false;},getDefaultValueForProperty:function(l,m){var n=j[l],o;if(!n)j[l]=n={};if(!(m in n)){o=document.createElement(l);n[m]=o[m];}return n[m];},injection:i};e.exports=k;},null);
__d("escapeTextForBrowser",[],function(a,b,c,d,e,f){"use strict";var g={"&":"&",">":">","<":"<","\"":""","'":"'"},h=/[&><"']/g;function i(k){return g[k];}function j(k){return (''+k).replace(h,i);}e.exports=j;},null);
__d("ReactCurrentOwner",[],function(a,b,c,d,e,f){"use strict";var g={current:null};e.exports=g;},null);
__d("monitorCodeUse",["BanzaiScuba","ReactCurrentOwner","invariant","forEachObject"],function(a,b,c,d,e,f,g,h,i,j){function k(m){var n=[];while(m){n.push(m.constructor.displayName);m=m._owner;}return n;}function l(m,n){i(m&&!/[^a-z0-9_]/.test(m));var o=new g('core_monitor');o.addNormal('event',m);o.addDenorm('stack',new Error().stack);o.addNormVector('owners',k(h.current));j(n,function(p,q,r){o.addNormal(q,p);});o.post();}e.exports=l;},null);
__d("warning",["Bootloader","monitorCodeUse"],function(a,b,c,d,e,f,g,h){function i(j,k){for(var l=[],m=2,n=arguments.length;m<n;m++)l.push(arguments[m]);if(k===undefined)throw new Error('`warning(condition, format, ...args)` requires a warning '+'message argument');if(!j){var o=0,p=k.replace(/%s/g,function(){return l[o++];});h('warning',{message:p});}}e.exports=i;},null);
__d("DOMPropertyOperations",["DOMProperty","escapeTextForBrowser","memoizeStringOnly","warning"],function(a,b,c,d,e,f,g,h,i,j){"use strict";function k(n,o){return o==null||(g.hasBooleanValue[n]&&!o)||(g.hasNumericValue[n]&&isNaN(o))||(g.hasPositiveNumericValue[n]&&(o<1))||(g.hasOverloadedBooleanValue[n]&&o===false);}var l=i(function(n){return h(n)+'="';}),m={createMarkupForID:function(n){return l(g.ID_ATTRIBUTE_NAME)+h(n)+'"';},createMarkupForProperty:function(n,o){if(g.isStandardName.hasOwnProperty(n)&&g.isStandardName[n]){if(k(n,o))return '';var p=g.getAttributeName[n];if(g.hasBooleanValue[n]||(g.hasOverloadedBooleanValue[n]&&o===true))return h(p);return l(p)+h(o)+'"';}else if(g.isCustomAttribute(n)){if(o==null)return '';return l(n)+h(o)+'"';}return null;},setValueForProperty:function(n,o,p){if(g.isStandardName.hasOwnProperty(o)&&g.isStandardName[o]){var q=g.getMutationMethod[o];if(q){q(n,p);}else if(k(o,p)){this.deleteValueForProperty(n,o);}else if(g.mustUseAttribute[o]){n.setAttribute(g.getAttributeName[o],''+p);}else{var r=g.getPropertyName[o];if(!g.hasSideEffects[o]||(''+n[r])!==(''+p))n[r]=p;}}else if(g.isCustomAttribute(o))if(p==null){n.removeAttribute(o);}else n.setAttribute(o,''+p);},deleteValueForProperty:function(n,o){if(g.isStandardName.hasOwnProperty(o)&&g.isStandardName[o]){var p=g.getMutationMethod[o];if(p){p(n,undefined);}else if(g.mustUseAttribute[o]){n.removeAttribute(g.getAttributeName[o]);}else{var q=g.getPropertyName[o],r=g.getDefaultValueForProperty(n.nodeName,q);if(!g.hasSideEffects[o]||(''+n[q])!==r)n[q]=r;}}else if(g.isCustomAttribute(o))n.removeAttribute(o);}};e.exports=m;},null);
__d("EventConstants",["keyMirror"],function(a,b,c,d,e,f,g){"use strict";var h=g({bubbled:null,captured:null}),i=g({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}),j={topLevelTypes:i,PropagationPhases:h};e.exports=j;},null);
__d("EventPluginUtils",["EventConstants","invariant"],function(a,b,c,d,e,f,g,h){"use strict";var i={Mount:null,injectMount:function(w){i.Mount=w;}},j=g.topLevelTypes;function k(w){return w===j.topMouseUp||w===j.topTouchEnd||w===j.topTouchCancel;}function l(w){return w===j.topMouseMove||w===j.topTouchMove;}function m(w){return w===j.topMouseDown||w===j.topTouchStart;}var n;function o(event,w){var x=event._dispatchListeners,y=event._dispatchIDs;if(Array.isArray(x)){for(var z=0;z<x.length;z++){if(event.isPropagationStopped())break;w(event,x[z],y[z]);}}else if(x)w(event,x,y);}function p(event,w,x){event.currentTarget=i.Mount.getNode(x);var y=w(event,x);event.currentTarget=null;return y;}function q(event,w){o(event,w);event._dispatchListeners=null;event._dispatchIDs=null;}function r(event){var w=event._dispatchListeners,x=event._dispatchIDs;if(Array.isArray(w)){for(var y=0;y<w.length;y++){if(event.isPropagationStopped())break;if(w[y](event,x[y]))return x[y];}}else if(w)if(w(event,x))return x;return null;}function s(event){var w=r(event);event._dispatchIDs=null;event._dispatchListeners=null;return w;}function t(event){var w=event._dispatchListeners,x=event._dispatchIDs;h(!Array.isArray(w));var y=w?w(event,x):null;event._dispatchListeners=null;event._dispatchIDs=null;return y;}function u(event){return !!event._dispatchListeners;}var v={isEndish:k,isMoveish:l,isStartish:m,executeDirectDispatch:t,executeDispatch:p,executeDispatchesInOrder:q,executeDispatchesInOrderStopAtTrue:s,hasDispatches:u,injection:i,useTouchEvents:false};e.exports=v;},null);
__d("PooledClass",["invariant"],function(a,b,c,d,e,f,g){"use strict";var h=function(q){var r=this;if(r.instancePool.length){var s=r.instancePool.pop();r.call(s,q);return s;}else return new r(q);},i=function(q,r){var s=this;if(s.instancePool.length){var t=s.instancePool.pop();s.call(t,q,r);return t;}else return new s(q,r);},j=function(q,r,s){var t=this;if(t.instancePool.length){var u=t.instancePool.pop();t.call(u,q,r,s);return u;}else return new t(q,r,s);},k=function(q,r,s,t,u){var v=this;if(v.instancePool.length){var w=v.instancePool.pop();v.call(w,q,r,s,t,u);return w;}else return new v(q,r,s,t,u);},l=function(q){var r=this;g(q instanceof r);if(q.destructor)q.destructor();if(r.instancePool.length<r.poolSize)r.instancePool.push(q);},m=10,n=h,o=function(q,r){var s=q;s.instancePool=[];s.getPooled=r||n;if(!s.poolSize)s.poolSize=m;s.release=l;return s;},p={addPoolingTo:o,oneArgumentPooler:h,twoArgumentPooler:i,threeArgumentPooler:j,fiveArgumentPooler:k};e.exports=p;},null);
__d("Object.assign",[],function(a,b,c,d,e,f){e.exports=Object.assign;},null);
__d("ReactContext",["Object.assign"],function(a,b,c,d,e,f,g){"use strict";var h={current:{},withContext:function(i,j){var k,l=h.current;h.current=g({},l,i);try{k=j();}finally{h.current=l;}return k;}};e.exports=h;},null);
__d("ReactElement",["ReactContext","ReactCurrentOwner","warning"],function(a,b,c,d,e,f,g,h,i){"use strict";var j={key:true,ref:true};function k(o,p){Object.defineProperty(o,p,{configurable:false,enumerable:true,get:function(){if(!this._store)return null;return this._store[p];},set:function(q){i(false,'Don\'t set the '+p+' property of the component. '+'Mutate the existing props object instead.');this._store[p]=q;}});}var l=false;function m(o){try{var q={props:true};for(var r in q)k(o,r);l=true;}catch(p){}}var n=function(o,p,q,r,s,t){this.type=o;this.key=p;this.ref=q;this._owner=r;this._context=s;this.props=t;};n.prototype={_isReactElement:true};n.createElement=function(o,p,q){var r,s={},t=null,u=null;if(p!=null){u=p.ref===undefined?null:p.ref;t=p.key==null?null:''+p.key;for(r in p)if(p.hasOwnProperty(r)&&!j.hasOwnProperty(r))s[r]=p[r];}var v=arguments.length-2;if(v===1){s.children=q;}else if(v>1){var w=Array(v);for(var x=0;x<v;x++)w[x]=arguments[x+2];s.children=w;}if(o.defaultProps){var y=o.defaultProps;for(r in y)if(typeof s[r]==='undefined')s[r]=y[r];}return new n(o,t,u,h.current,g.current,s);};n.createFactory=function(o){var p=n.createElement.bind(null,o);p.type=o;return p;};n.cloneAndReplaceProps=function(o,p){var q=new n(o.type,o.key,o.ref,o._owner,o._context,p);return q;};n.isValidElement=function(o){var p=!!(o&&o._isReactElement);return p;};e.exports=n;},null);
__d("ReactRootIndex",[],function(a,b,c,d,e,f){"use strict";var g={injectCreateReactRootIndex:function(i){h.createReactRootIndex=i;}},h={createReactRootIndex:null,injection:g};e.exports=h;},null);
__d("ReactInstanceHandles",["ReactRootIndex","invariant"],function(a,b,c,d,e,f,g,h){"use strict";var i='.',j=i.length,k=100;function l(u){return i+u.toString(36);}function m(u,v){return u.charAt(v)===i||v===u.length;}function n(u){return u===''||(u.charAt(0)===i&&u.charAt(u.length-1)!==i);}function o(u,v){return (v.indexOf(u)===0&&m(v,u.length));}function p(u){return u?u.substr(0,u.lastIndexOf(i)):'';}function q(u,v){h(n(u)&&n(v));h(o(u,v));if(u===v)return u;var w=u.length+j;for(var x=w;x<v.length;x++)if(m(v,x))break;return v.substr(0,x);}function r(u,v){var w=Math.min(u.length,v.length);if(w===0)return '';var x=0;for(var y=0;y<=w;y++)if(m(u,y)&&m(v,y)){x=y;}else if(u.charAt(y)!==v.charAt(y))break;var z=u.substr(0,x);h(n(z));return z;}function s(u,v,w,x,y,z){u=u||'';v=v||'';h(u!==v);var aa=o(v,u);h(aa||o(u,v));var ba=0,ca=aa?p:q;for(var da=u;;da=ca(da,v)){var ea;if((!y||da!==u)&&(!z||da!==v))ea=w(da,aa,x);if(ea===false||da===v)break;h(ba++<k);}}var t={createReactRootID:function(){return l(g.createReactRootIndex());},createReactID:function(u,v){return u+v;},getReactRootIDFromNodeID:function(u){if(u&&u.charAt(0)===i&&u.length>1){var v=u.indexOf(i,1);return v>-1?u.substr(0,v):u;}return null;},traverseEnterLeave:function(u,v,w,x,y){var z=r(u,v);if(z!==u)s(u,z,w,x,false,true);if(z!==v)s(z,v,w,y,true,false);},traverseTwoPhase:function(u,v,w){if(u){s('',u,v,w,true,false);s(u,'',v,w,false,true);}},traverseAncestors:function(u,v,w){s('',u,v,w,true,false);},_getFirstCommonAncestorID:r,_getNextDescendantID:q,isAncestorIDOf:o,SEPARATOR:i};e.exports=t;},null);
__d("getIteratorFn",[],function(a,b,c,d,e,f){"use strict";var g=typeof Symbol==='function'&&Symbol.iterator,h='@@iterator';function i(j){var k=j&&((g&&j[g])||j[h]);if(typeof k==='function')return k;}e.exports=i;},null);
__d("traverseAllChildren",["ReactElement","ReactInstanceHandles","getIteratorFn","invariant"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k=h.SEPARATOR,l=':',m={'=':'=0','.':'=1',':':'=2'},n=/[=.:]/g;function o(u){return m[u];}function p(u,v){if(u&&u.key!=null)return r(u.key);return v.toString(36);}function q(u){return (''+u).replace(n,o);}function r(u){return '$'+q(u);}function s(u,v,w,x,y){var z=typeof u;if(z==='undefined'||z==='boolean')u=null;if(u===null||z==='string'||z==='number'||g.isValidElement(u)){x(y,u,v===''?k+p(u,0):v,w);return 1;}var aa,ba,ca,da=0;if(Array.isArray(u)){for(var ea=0;ea<u.length;ea++){aa=u[ea];ba=((v!==''?v+l:k)+p(aa,ea));ca=w+da;da+=s(aa,ba,ca,x,y);}}else{var fa=i(u);if(fa){var ga=fa.call(u),ha;if(fa!==u.entries){var ia=0;while(!(ha=ga.next()).done){aa=ha.value;ba=((v!==''?v+l:k)+p(aa,ia++));ca=w+da;da+=s(aa,ba,ca,x,y);}}else while(!(ha=ga.next()).done){var ja=ha.value;if(ja){aa=ja[1];ba=((v!==''?v+l:k)+r(ja[0])+l+p(aa,0));ca=w+da;da+=s(aa,ba,ca,x,y);}}}else if(z==='object'){j(u.nodeType!==1);for(var ka in u)if(u.hasOwnProperty(ka)){aa=u[ka];ba=((v!==''?v+l:k)+r(ka)+l+p(aa,0));ca=w+da;da+=s(aa,ba,ca,x,y);}}}return da;}function t(u,v,w){if(u==null)return 0;return s(u,'',0,v,w);}e.exports=t;},null);
__d("ReactChildren",["PooledClass","traverseAllChildren","warning"],function(a,b,c,d,e,f,g,h,i){"use strict";var j=g.twoArgumentPooler,k=g.threeArgumentPooler;function l(u,v){this.forEachFunction=u;this.forEachContext=v;}g.addPoolingTo(l,j);function m(u,v,w,x){var y=u;y.forEachFunction.call(y.forEachContext,v,x);}function n(u,v,w){if(u==null)return u;var x=l.getPooled(v,w);h(u,m,x);l.release(x);}function o(u,v,w){this.mapResult=u;this.mapFunction=v;this.mapContext=w;}g.addPoolingTo(o,k);function p(u,v,w,x){var y=u,z=y.mapResult,aa=!z.hasOwnProperty(w);i(aa,'ReactChildren.map(...): Encountered two children with the same key, '+'`%s`. Child keys must be unique; when two children share a key, only '+'the first child will be used.',w);if(aa){var ba=y.mapFunction.call(y.mapContext,v,x);z[w]=ba;}}function q(u,v,w){if(u==null)return u;var x={},y=o.getPooled(x,v,w);h(u,p,y);o.release(y);return x;}function r(u,v,w,x){return null;}function s(u,v){return h(u,r,null);}var t={forEach:n,map:q,count:s};e.exports=t;},null);
__d("emptyObject",[],function(a,b,c,d,e,f){"use strict";var g={};e.exports=g;},null);
__d("ReactOwner",["emptyObject","invariant"],function(a,b,c,d,e,f,g,h){"use strict";var i={isValidOwner:function(j){return !!(j&&typeof j.attachRef==='function'&&typeof j.detachRef==='function');},addComponentAsRefTo:function(j,k,l){h(i.isValidOwner(l));l.attachRef(k,j);},removeComponentAsRefFrom:function(j,k,l){h(i.isValidOwner(l));if(l.refs[k]===j)l.detachRef(k);},Mixin:{construct:function(){this.refs=g;},attachRef:function(j,k){h(k.isOwnedBy(this));var l=this.refs===g?(this.refs={}):this.refs;l[j]=k;},detachRef:function(j){delete this.refs[j];}}};e.exports=i;},null);
__d("ReactPerf",[],function(a,b,c,d,e,f){"use strict";var g={enableMeasure:false,storedMeasure:h,measure:function(i,j,k){return k;},injection:{injectMeasure:function(i){g.storedMeasure=i;}}};function h(i,j,k){return k;}e.exports=g;},null);
__d("Transaction",["invariant"],function(a,b,c,d,e,f,g){"use strict";var h={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers();if(!this.wrapperInitData){this.wrapperInitData=[];}else this.wrapperInitData.length=0;this._isInTransaction=false;},_isInTransaction:false,getTransactionWrappers:null,isInTransaction:function(){return !!this._isInTransaction;},perform:function(j,k,l,m,n,o,p,q){g(!this.isInTransaction());var r,s;try{this._isInTransaction=true;r=true;this.initializeAll(0);s=j.call(k,l,m,n,o,p,q);r=false;}finally{try{if(r){try{this.closeAll(0);}catch(t){}}else this.closeAll(0);}finally{this._isInTransaction=false;}}return s;},initializeAll:function(j){var k=this.transactionWrappers;for(var l=j;l<k.length;l++){var m=k[l];try{this.wrapperInitData[l]=i.OBSERVED_ERROR;this.wrapperInitData[l]=m.initialize?m.initialize.call(this):null;}finally{if(this.wrapperInitData[l]===i.OBSERVED_ERROR)try{this.initializeAll(l+1);}catch(n){}}}},closeAll:function(j){g(this.isInTransaction());var k=this.transactionWrappers;for(var l=j;l<k.length;l++){var m=k[l],n=this.wrapperInitData[l],o;try{o=true;if(n!==i.OBSERVED_ERROR)m.close&&m.close.call(this,n);o=false;}finally{if(o)try{this.closeAll(l+1);}catch(p){}}}this.wrapperInitData.length=0;}},i={Mixin:h,OBSERVED_ERROR:{}};e.exports=i;},null);
__d("ReactUpdates",["CallbackQueue","PooledClass","ReactCurrentOwner","ReactPerf","Transaction","Object.assign","invariant","warning"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){"use strict";var o=[],p=g.getPooled(),q=false,r=null;function s(){m(ea.ReactReconcileTransaction&&r);}var t={initialize:function(){this.dirtyComponentsLength=o.length;},close:function(){if(this.dirtyComponentsLength!==o.length){o.splice(0,this.dirtyComponentsLength);aa();}else o.length=0;}},u={initialize:function(){this.callbackQueue.reset();},close:function(){this.callbackQueue.notifyAll();}},v=[t,u];function w(){this.reinitializeTransaction();this.dirtyComponentsLength=null;this.callbackQueue=g.getPooled();this.reconcileTransaction=ea.ReactReconcileTransaction.getPooled();}l(w.prototype,k.Mixin,{getTransactionWrappers:function(){return v;},destructor:function(){this.dirtyComponentsLength=null;g.release(this.callbackQueue);this.callbackQueue=null;ea.ReactReconcileTransaction.release(this.reconcileTransaction);this.reconcileTransaction=null;},perform:function(fa,ga,ha){return k.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,fa,ga,ha);}});h.addPoolingTo(w);function x(fa,ga,ha){s();r.batchedUpdates(fa,ga,ha);}function y(fa,ga){return fa._mountDepth-ga._mountDepth;}function z(fa){var ga=fa.dirtyComponentsLength;m(ga===o.length);o.sort(y);for(var ha=0;ha<ga;ha++){var ia=o[ha];if(ia.isMounted()){var ja=ia._pendingCallbacks;ia._pendingCallbacks=null;ia.performUpdateIfNecessary(fa.reconcileTransaction);if(ja)for(var ka=0;ka<ja.length;ka++)fa.callbackQueue.enqueue(ja[ka],ia);}}}var aa=j.measure('ReactUpdates','flushBatchedUpdates',function(){while(o.length||q){if(o.length){var fa=w.getPooled();fa.perform(z,null,fa);w.release(fa);}if(q){q=false;var ga=p;p=g.getPooled();ga.notifyAll();g.release(ga);}}});function ba(fa,ga){m(!ga||typeof ga==="function");s();n(i.current==null,'enqueueUpdate(): Render methods should be a pure function of props '+'and state; triggering nested component updates from render is not '+'allowed. If necessary, trigger nested updates in '+'componentDidUpdate.');if(!r.isBatchingUpdates){r.batchedUpdates(ba,fa,ga);return;}o.push(fa);if(ga)if(fa._pendingCallbacks){fa._pendingCallbacks.push(ga);}else fa._pendingCallbacks=[ga];}function ca(fa,ga){m(r.isBatchingUpdates);p.enqueue(fa,ga);q=true;}var da={injectReconcileTransaction:function(fa){m(fa);ea.ReactReconcileTransaction=fa;},injectBatchingStrategy:function(fa){m(fa);m(typeof fa.batchedUpdates==='function');m(typeof fa.isBatchingUpdates==='boolean');r=fa;}},ea={ReactReconcileTransaction:null,batchedUpdates:x,enqueueUpdate:ba,flushBatchedUpdates:aa,injection:da,asap:ca};e.exports=ea;},null);
__d("ReactComponent",["ReactElement","ReactOwner","ReactUpdates","Object.assign","invariant","keyMirror"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";var m=l({MOUNTED:null,UNMOUNTED:null}),n=false,o=null,p=null,q={injection:{injectEnvironment:function(r){k(!n);p=r.mountImageIntoNode;o=r.unmountIDFromEnvironment;q.BackendIDOperations=r.BackendIDOperations;n=true;}},LifeCycle:m,BackendIDOperations:null,Mixin:{isMounted:function(){return this._lifeCycleState===m.MOUNTED;},setProps:function(r,s){var t=this._pendingElement||this._currentElement;this.replaceProps(j({},t.props,r),s);},replaceProps:function(r,s){k(this.isMounted());k(this._mountDepth===0);this._pendingElement=g.cloneAndReplaceProps(this._pendingElement||this._currentElement,r);i.enqueueUpdate(this,s);},_setPropsInternal:function(r,s){var t=this._pendingElement||this._currentElement;this._pendingElement=g.cloneAndReplaceProps(t,j({},t.props,r));i.enqueueUpdate(this,s);},construct:function(r){this.props=r.props;this._owner=r._owner;this._lifeCycleState=m.UNMOUNTED;this._pendingCallbacks=null;this._currentElement=r;this._pendingElement=null;},mountComponent:function(r,s,t){k(!this.isMounted());var u=this._currentElement.ref;if(u!=null){var v=this._currentElement._owner;h.addComponentAsRefTo(this,u,v);}this._rootNodeID=r;this._lifeCycleState=m.MOUNTED;this._mountDepth=t;},unmountComponent:function(){k(this.isMounted());var r=this._currentElement.ref;if(r!=null)h.removeComponentAsRefFrom(this,r,this._owner);o(this._rootNodeID);this._rootNodeID=null;this._lifeCycleState=m.UNMOUNTED;},receiveComponent:function(r,s){k(this.isMounted());this._pendingElement=r;this.performUpdateIfNecessary(s);},performUpdateIfNecessary:function(r){if(this._pendingElement==null)return;var s=this._currentElement,t=this._pendingElement;this._currentElement=t;this.props=t.props;this._owner=t._owner;this._pendingElement=null;this.updateComponent(r,s,t);},updateComponent:function(r,s,t){if(t._owner!==s._owner||t.ref!==s.ref){if(s.ref!=null)h.removeComponentAsRefFrom(this,s.ref,s._owner);if(t.ref!=null)h.addComponentAsRefTo(this,t.ref,t._owner);}},mountComponentIntoNode:function(r,s,t){var u=i.ReactReconcileTransaction.getPooled();u.perform(this._mountComponentIntoNode,this,r,s,u,t);i.ReactReconcileTransaction.release(u);},_mountComponentIntoNode:function(r,s,t,u){var v=this.mountComponent(r,t,0);p(v,s,u);},isOwnedBy:function(r){return this._owner===r;},getSiblingByRef:function(r){var s=this._owner;if(!s||!s.refs)return null;return s.refs[r];}}};e.exports=q;},null);
__d("ReactEmptyComponent",["ReactElement","invariant"],function(a,b,c,d,e,f,g,h){"use strict";var i,j={},k={injectEmptyComponent:function(q){i=g.createFactory(q);}};function l(){h(i);return i();}function m(q){j[q]=true;}function n(q){delete j[q];}function o(q){return j[q];}var p={deregisterNullComponentID:n,getEmptyComponent:l,injection:k,isNullComponentID:o,registerNullComponentID:m};e.exports=p;},null);
__d("ReactPropTransferer",["Object.assign","emptyFunction","invariant","joinClasses","warning"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=false;function m(r){return function(s,t,u){if(!s.hasOwnProperty(t)){s[t]=u;}else s[t]=r(s[t],u);};}var n=m(function(r,s){return g({},s,r);}),o={children:h,className:m(j),style:n};function p(r,s){for(var t in s){if(!s.hasOwnProperty(t))continue;var u=o[t];if(u&&o.hasOwnProperty(t)){u(r,t,s[t]);}else if(!r.hasOwnProperty(t))r[t]=s[t];}return r;}var q={TransferStrategies:o,mergeProps:function(r,s){return p(g({},r),s);},Mixin:{transferPropsTo:function(r){i(r._owner===this);p(r.props,this.props);return r;}}};e.exports=q;},null);
__d("ReactPropTypeLocations",["keyMirror"],function(a,b,c,d,e,f,g){"use strict";var h=g({prop:null,context:null,childContext:null});e.exports=h;},null);
__d("ReactNativeComponent",["Object.assign","invariant"],function(a,b,c,d,e,f,g,h){"use strict";var i=null,j={},k={injectGenericComponentClass:function(n){i=n;},injectComponentClasses:function(n){g(j,n);}};function l(n,o,p){var q=j[n];if(q==null){h(i);return new i(n,o);}if(p===n){h(i);return new i(n,o);}return new q(o);}var m={createInstanceForTag:l,injection:k};e.exports=m;},null);
__d("instantiateReactComponent",["warning","ReactNativeComponent"],function(a,b,c,d,e,f,g,h){"use strict";var i={forceUpdate:true,replaceState:true,setProps:true,setState:true,getDOMNode:true};function j(l){var m=k._compositeBase;for(var n in m.prototype)if(!i.hasOwnProperty(n))l[n]=m.prototype[n];}function k(l,m){var n;if(typeof l.type==='string'){n=h.createInstanceForTag(l.type,l.props,m);}else n=new l.type(l.props);n.construct(l);return n;}e.exports=k;},null);
__d("shouldUpdateReactComponent",[],function(a,b,c,d,e,f){"use strict";function g(h,i){if(h&&i&&h.type===i.type&&h.key===i.key&&h._owner===i._owner)return true;return false;}e.exports=g;},null);
__d("ReactCompositeComponent",["ReactComponent","ReactContext","ReactCurrentOwner","ReactElement","ReactEmptyComponent","ReactErrorUtils","ReactOwner","ReactPerf","ReactPropTransferer","ReactPropTypeLocations","ReactUpdates","Object.assign","instantiateReactComponent","invariant","keyMirror","monitorCodeUse","shouldUpdateReactComponent","warning"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){"use strict";function y(ea){var fa=ea._owner||null;if(fa&&fa.constructor&&fa.constructor.displayName)return ' Check the render method of `'+fa.constructor.displayName+'`.';return '';}function z(ea){var fa=ea._compositeLifeCycleState;t(ea.isMounted()||fa===aa.MOUNTING);t(i.current==null);t(fa!==aa.UNMOUNTING);}var aa=u({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null}),ba={construct:function(ea){g.Mixin.construct.apply(this,arguments);m.Mixin.construct.apply(this,arguments);this.state=null;this._pendingState=null;this.context=null;this._compositeLifeCycleState=null;},isMounted:function(){return g.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==aa.MOUNTING;},mountComponent:n.measure('ReactCompositeComponent','mountComponent',function(ea,fa,ga){g.Mixin.mountComponent.call(this,ea,fa,ga);this._compositeLifeCycleState=aa.MOUNTING;if(this.__reactAutoBindMap)this._bindAutoBindMethods();this.context=this._processContext(this._currentElement._context);this.props=this._processProps(this.props);this.state=this.getInitialState?this.getInitialState():null;t(typeof this.state==='object'&&!Array.isArray(this.state));this._pendingState=null;this._pendingForceUpdate=false;if(this.componentWillMount){this.componentWillMount();if(this._pendingState){this.state=this._pendingState;this._pendingState=null;}}this._renderedComponent=s(this._renderValidatedComponent(),this._currentElement.type);this._compositeLifeCycleState=null;var ha=this._renderedComponent.mountComponent(ea,fa,ga+1);if(this.componentDidMount)fa.getReactMountReady().enqueue(this.componentDidMount,this);return ha;}),unmountComponent:function(){this._compositeLifeCycleState=aa.UNMOUNTING;if(this.componentWillUnmount)this.componentWillUnmount();this._compositeLifeCycleState=null;this._renderedComponent.unmountComponent();this._renderedComponent=null;g.Mixin.unmountComponent.call(this);},setState:function(ea,fa){t(typeof ea==='object'||ea==null);this.replaceState(r({},this._pendingState||this.state,ea),fa);},replaceState:function(ea,fa){z(this);this._pendingState=ea;if(this._compositeLifeCycleState!==aa.MOUNTING)q.enqueueUpdate(this,fa);},_processContext:function(ea){var fa=null,ga=this.constructor.contextTypes;if(ga){fa={};for(var ha in ga)fa[ha]=ea[ha];}return fa;},_processChildContext:function(ea){var fa=this.getChildContext&&this.getChildContext(),ga=this.constructor.displayName||'ReactCompositeComponent';if(fa){t(typeof this.constructor.childContextTypes==='object');for(var ha in fa)t(ha in this.constructor.childContextTypes);return r({},ea,fa);}return ea;},_processProps:function(ea){return ea;},_checkPropTypes:function(ea,fa,ga){var ha=this.constructor.displayName;for(var ia in ea)if(ea.hasOwnProperty(ia)){var ja=ea[ia](fa,ia,ha,ga);if(ja instanceof Error){var ka=y(this);x(false,ja.message+ka);}}},receiveComponent:function(ea,fa){if(ea===this._currentElement&&ea._owner!=null)return;g.Mixin.receiveComponent.call(this,ea,fa);},performUpdateIfNecessary:function(ea){var fa=this._compositeLifeCycleState;if(fa===aa.MOUNTING||fa===aa.RECEIVING_PROPS)return;if(this._pendingElement==null&&this._pendingState==null&&!this._pendingForceUpdate)return;var ga=this._currentElement,ha=ga;if(this._pendingElement!=null){ha=this._pendingElement;this._pendingElement=null;}this.updateComponent(ea,ga,ha);},updateComponent:n.measure('ReactCompositeComponent','updateComponent',function(ea,fa,ga){g.Mixin.updateComponent.call(this,ea,fa,ga);var ha=this.context,ia=this.props,ja=ha,ka=ia;if(fa!==ga){ja=this._processContext(ga._context);ka=this._processProps(ga.props);this._compositeLifeCycleState=aa.RECEIVING_PROPS;if(this.componentWillReceiveProps)this.componentWillReceiveProps(ka,ja);}this._compositeLifeCycleState=null;var la=this._pendingState||this.state;this._pendingState=null;var ma=this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(ka,la,ja);if(!ma){this._currentElement=ga;this.props=ka;this.state=la;this.context=ja;this._owner=ga._owner;return;}this._pendingForceUpdate=false;this._performComponentUpdate(ga,ka,la,ja,ea);}),_performComponentUpdate:function(ea,fa,ga,ha,ia){var ja=this.props,ka=this.state,la=this.context;if(this.componentWillUpdate)this.componentWillUpdate(fa,ga,ha);this._currentElement=ea;this.props=fa;this.state=ga;this.context=ha;this._owner=ea._owner;this._updateRenderedComponent(ia);if(this.componentDidUpdate)ia.getReactMountReady().enqueue(this.componentDidUpdate.bind(this,ja,ka,la),this);},_updateRenderedComponent:function(ea){var fa=this._renderedComponent,ga=fa._currentElement,ha=this._renderValidatedComponent();if(w(ga,ha)){fa.receiveComponent(ha,ea);}else{var ia=this._rootNodeID,ja=fa._rootNodeID;fa.unmountComponent();this._renderedComponent=s(ha,this._currentElement.type);var ka=this._renderedComponent.mountComponent(ia,ea,this._mountDepth+1);g.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(ja,ka);}},forceUpdate:function(ea){var fa=this._compositeLifeCycleState;t(this.isMounted()||fa===aa.MOUNTING);t(fa!==aa.UNMOUNTING&&i.current==null);this._pendingForceUpdate=true;q.enqueueUpdate(this,ea);},_renderValidatedComponent:n.measure('ReactCompositeComponent','_renderValidatedComponent',function(){var ea,fa=h.current;h.current=this._processChildContext(this._currentElement._context);i.current=this;try{ea=this.render();if(ea===null||ea===false){ea=k.getEmptyComponent();k.registerNullComponentID(this._rootNodeID);}else k.deregisterNullComponentID(this._rootNodeID);}finally{h.current=fa;i.current=null;}t(j.isValidElement(ea));return ea;}),_bindAutoBindMethods:function(){for(var ea in this.__reactAutoBindMap){if(!this.__reactAutoBindMap.hasOwnProperty(ea))continue;var fa=this.__reactAutoBindMap[ea];this[ea]=this._bindAutoBindMethod(l.guard(fa,this.constructor.displayName+'.'+ea));}},_bindAutoBindMethod:function(ea){var fa=this,ga=ea.bind(fa);return ga;}},ca=function(){};r(ca.prototype,g.Mixin,m.Mixin,o.Mixin,ba);var da={LifeCycle:aa,Base:ca};s._compositeBase=ca;e.exports=da;},null);
__d("ReactPropTypeLocationNames",[],function(a,b,c,d,e,f){"use strict";var g={};e.exports=g;},null);
__d("ReactClass",["ReactCompositeComponent","ReactElement","ReactPropTypeLocations","ReactPropTypeLocationNames","Object.assign","invariant","keyMirror","keyOf","monitorCodeUse","mapObject"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){"use strict";var q=n({mixins:null}),r=m({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),s=[],t={mixins:r.DEFINE_MANY,statics:r.DEFINE_MANY,propTypes:r.DEFINE_MANY,contextTypes:r.DEFINE_MANY,childContextTypes:r.DEFINE_MANY,getDefaultProps:r.DEFINE_MANY_MERGED,getInitialState:r.DEFINE_MANY_MERGED,getChildContext:r.DEFINE_MANY_MERGED,render:r.DEFINE_ONCE,componentWillMount:r.DEFINE_MANY,componentDidMount:r.DEFINE_MANY,componentWillReceiveProps:r.DEFINE_MANY,shouldComponentUpdate:r.DEFINE_ONCE,componentWillUpdate:r.DEFINE_MANY,componentDidUpdate:r.DEFINE_MANY,componentWillUnmount:r.DEFINE_MANY,updateComponent:r.OVERRIDE_BASE},u={displayName:function(da,ea){da.displayName=ea;},mixins:function(da,ea){if(ea)for(var fa=0;fa<ea.length;fa++)x(da,ea[fa]);},childContextTypes:function(da,ea){v(da,ea,i.childContext);da.childContextTypes=k({},da.childContextTypes,ea);},contextTypes:function(da,ea){v(da,ea,i.context);da.contextTypes=k({},da.contextTypes,ea);},getDefaultProps:function(da,ea){if(da.getDefaultProps){da.getDefaultProps=aa(da.getDefaultProps,ea);}else da.getDefaultProps=ea;},propTypes:function(da,ea){v(da,ea,i.prop);da.propTypes=k({},da.propTypes,ea);},statics:function(da,ea){y(da,ea);}};function v(da,ea,fa){for(var ga in ea)if(ea.hasOwnProperty(ga))l(typeof ea[ga]=='function');}function w(da,ea){var fa=t.hasOwnProperty(ea)?t[ea]:null;if(g.Base.prototype.hasOwnProperty(ea))l(fa===r.OVERRIDE_BASE);if(da.hasOwnProperty(ea))l(fa===r.DEFINE_MANY||fa===r.DEFINE_MANY_MERGED);}function x(da,ea){if(!ea)return;l(typeof ea!=='function');l(!h.isValidElement(ea));var fa=da.prototype;if(ea.hasOwnProperty(q))u.mixins(da,ea.mixins);for(var ga in ea){if(!ea.hasOwnProperty(ga))continue;if(ga===q)continue;var ha=ea[ga];w(fa,ga);if(u.hasOwnProperty(ga)){u[ga](da,ha);}else{var ia=t.hasOwnProperty(ga),ja=fa.hasOwnProperty(ga),ka=ha&&ha.__reactDontBind,la=typeof ha==='function',ma=la&&!ia&&!ja&&!ka;if(ma){if(!fa.__reactAutoBindMap)fa.__reactAutoBindMap={};fa.__reactAutoBindMap[ga]=ha;fa[ga]=ha;}else if(ja){var na=t[ga];l(ia&&(na===r.DEFINE_MANY_MERGED||na===r.DEFINE_MANY));if(na===r.DEFINE_MANY_MERGED){fa[ga]=aa(fa[ga],ha);}else if(na===r.DEFINE_MANY)fa[ga]=ba(fa[ga],ha);}else fa[ga]=ha;}}}function y(da,ea){if(!ea)return;for(var fa in ea){var ga=ea[fa];if(!ea.hasOwnProperty(fa))continue;var ha=fa in u;l(!ha);var ia=fa in da;l(!ia);da[fa]=ga;}}function z(da,ea){l(da&&ea&&typeof da==='object'&&typeof ea==='object');p(ea,function(fa,ga){l(da[ga]===undefined);da[ga]=fa;});return da;}function aa(da,ea){return function fa(){var ga=da.apply(this,arguments),ha=ea.apply(this,arguments);if(ga==null){return ha;}else if(ha==null)return ga;return z(ga,ha);};}function ba(da,ea){return function fa(){da.apply(this,arguments);ea.apply(this,arguments);};}var ca={createClass:function(da){var ea=function(ga){};ea.prototype=new g.Base();ea.prototype.constructor=ea;s.forEach(x.bind(null,ea));x(ea,da);if(ea.getDefaultProps)ea.defaultProps=ea.getDefaultProps();l(ea.prototype.render);for(var fa in t)if(!ea.prototype[fa])ea.prototype[fa]=null;ea.type=ea;return ea;},injection:{injectMixin:function(da){s.push(da);}}};e.exports=ca;},null);
__d("ReactElementValidator",["ReactElement","ReactPropTypeLocations","ReactCurrentOwner","getIteratorFn","monitorCodeUse"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l={react_key_warning:{},react_numeric_key_warning:{}},m={},n={},o=/^\d+$/;function p(){var x=i.current;return x&&x.constructor.displayName||undefined;}function q(x,y){if(x._store.validated||x.key!=null)return;x._store.validated=true;s('react_key_warning','Each child in an array or iterator should have a unique "key" prop.',x,y);}function r(x,y,z){if(!o.test(x))return;s('react_numeric_key_warning','Child objects should have non-numeric keys so ordering is preserved.',y,z);}function s(x,y,z,aa){var ba=p(),ca=aa.displayName,da=ba||ca,ea=l[x];if(ea.hasOwnProperty(da))return;ea[da]=true;y+=ba?(" Check the render method of "+ba+"."):(" Check the renderComponent call using <"+ca+">.");var fa=null;if(z&&z._owner&&z._owner!==i.current){fa=z._owner.constructor.displayName;y+=(" It was passed a child from "+fa+".");}y+=' See http://fb.me/react-warning-keys for more information.';k(x,{component:da,componentOwner:fa});}function t(){var x=p()||'';if(m.hasOwnProperty(x))return;m[x]=true;k('react_object_map_children');}function u(x,y){if(Array.isArray(x)){for(var z=0;z<x.length;z++){var aa=x[z];if(g.isValidElement(aa))q(aa,y);}}else if(g.isValidElement(x)){x._store.validated=true;}else if(x){var ba=j(x);if(ba&&ba!==x.entries){var ca=ba.call(x),da;while(!(da=ca.next()).done)if(g.isValidElement(da.value))q(da.value,y);}else if(typeof x==='object'){t();for(var ea in x)if(x.hasOwnProperty(ea))r(ea,x[ea],y);}}}function v(x,y,z,aa){for(var ba in y)if(y.hasOwnProperty(ba)){var ca;try{ca=y[ba](z,ba,x,aa);}catch(da){ca=da;}if(ca instanceof Error&&!(ca.message in n)){n[ca.message]=true;k('react_failed_descriptor_type_check',{message:ca.message});}}}var w={createElement:function(x,y,z){var aa=g.createElement.apply(this,arguments);if(aa==null)return aa;for(var ba=2;ba<arguments.length;ba++)u(arguments[ba],x);var ca=x.displayName;if(x.propTypes)v(ca,x.propTypes,aa.props,h.prop);if(x.contextTypes)v(ca,x.contextTypes,aa._context,h.context);return aa;},createFactory:function(x){var y=w.createElement.bind(null,x);y.type=x;return y;}};e.exports=w;},null);
__d("ReactDOM",["ReactElement","ReactElementValidator","mapObject"],function(a,b,c,d,e,f,g,h,i){"use strict";function j(l){return g.createFactory(l);}var k=i({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'},j);e.exports=k;},null);
__d("CSSProperty",[],function(a,b,c,d,e,f){"use strict";var g={columnCount:true,fillOpacity:true,flex:true,flexGrow:true,flexShrink:true,fontWeight:true,lineClamp:true,lineHeight:true,opacity:true,order:true,orphans:true,widows:true,zIndex:true,zoom:true};function h(l,m){return l+m.charAt(0).toUpperCase()+m.substring(1);}var i=['Webkit','ms','Moz','O'];Object.keys(g).forEach(function(l){i.forEach(function(m){g[h(m,l)]=g[l];});});var j={background:{backgroundImage:true,backgroundPosition:true,backgroundRepeat:true,backgroundColor:true},border:{borderWidth:true,borderStyle:true,borderColor:true},borderBottom:{borderBottomWidth:true,borderBottomStyle:true,borderBottomColor:true},borderLeft:{borderLeftWidth:true,borderLeftStyle:true,borderLeftColor:true},borderRight:{borderRightWidth:true,borderRightStyle:true,borderRightColor:true},borderTop:{borderTopWidth:true,borderTopStyle:true,borderTopColor:true},font:{fontStyle:true,fontVariant:true,fontWeight:true,fontSize:true,lineHeight:true,fontFamily:true}},k={isUnitlessNumber:g,shorthandPropertyExpansions:j};e.exports=k;},null);
__d("camelizeStyleName",["camelize"],function(a,b,c,d,e,f,g){"use strict";var h=/^-ms-/;function i(j){return g(j.replace(h,'ms-'));}e.exports=i;},null);
__d("dangerousStyleValue",["CSSProperty"],function(a,b,c,d,e,f,g){"use strict";var h=g.isUnitlessNumber;function i(j,k){var l=k==null||typeof k==='boolean'||k==='';if(l)return '';var m=isNaN(k);if(m||k===0||h.hasOwnProperty(j)&&h[j])return ''+k;if(typeof k==='string')k=k.trim();return k+'px';}e.exports=i;},null);
__d("hyphenateStyleName",["hyphenate"],function(a,b,c,d,e,f,g){"use strict";var h=/^ms-/;function i(j){return g(j).replace(h,'-ms-');}e.exports=i;},null);
__d("CSSPropertyOperations",["CSSProperty","ExecutionEnvironment","camelizeStyleName","dangerousStyleValue","hyphenateStyleName","memoizeStringOnly","warning"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n=l(function(q){return k(q);}),o='cssFloat';if(h.canUseDOM)if(document.documentElement.style.cssFloat===undefined)o='styleFloat';var p={createMarkupForStyles:function(q){var r='';for(var s in q){if(!q.hasOwnProperty(s))continue;var t=q[s];if(t!=null){r+=n(s)+':';r+=j(s,t)+';';}}return r||null;},setValueForStyles:function(q,r){var s=q.style;for(var t in r){if(!r.hasOwnProperty(t))continue;var u=j(t,r[t]);if(t==='float')t=o;if(u){s[t]=u;}else{var v=g.shorthandPropertyExpansions[t];if(v){for(var w in v)s[w]='';}else s[t]='';}}}};e.exports=p;},null);
__d("EventPluginRegistry",["invariant"],function(a,b,c,d,e,f,g){"use strict";var h=null,i={};function j(){if(!h)return;for(var n in i){var o=i[n],p=h.indexOf(n);g(p>-1);if(m.plugins[p])continue;g(o.extractEvents);m.plugins[p]=o;var q=o.eventTypes;for(var r in q)g(k(q[r],o,r));}}function k(n,o,p){g(!m.eventNameDispatchConfigs.hasOwnProperty(p));m.eventNameDispatchConfigs[p]=n;var q=n.phasedRegistrationNames;if(q){for(var r in q)if(q.hasOwnProperty(r)){var s=q[r];l(s,o,p);}return true;}else if(n.registrationName){l(n.registrationName,o,p);return true;}return false;}function l(n,o,p){g(!m.registrationNameModules[n]);m.registrationNameModules[n]=o;m.registrationNameDependencies[n]=o.eventTypes[p].dependencies;}var m={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(n){g(!h);h=Array.prototype.slice.call(n);j();},injectEventPluginsByName:function(n){var o=false;for(var p in n){if(!n.hasOwnProperty(p))continue;var q=n[p];if(!i.hasOwnProperty(p)||i[p]!==q){g(!i[p]);i[p]=q;o=true;}}if(o)j();},getPluginModuleForEvent:function(event){var n=event.dispatchConfig;if(n.registrationName)return m.registrationNameModules[n.registrationName]||null;for(var o in n.phasedRegistrationNames){if(!n.phasedRegistrationNames.hasOwnProperty(o))continue;var p=m.registrationNameModules[n.phasedRegistrationNames[o]];if(p)return p;}return null;},_resetEventPlugins:function(){h=null;for(var n in i)if(i.hasOwnProperty(n))delete i[n];m.plugins.length=0;var o=m.eventNameDispatchConfigs;for(var p in o)if(o.hasOwnProperty(p))delete o[p];var q=m.registrationNameModules;for(var r in q)if(q.hasOwnProperty(r))delete q[r];}};e.exports=m;},null);
__d("accumulateInto",["invariant"],function(a,b,c,d,e,f,g){"use strict";function h(i,j){g(j!=null);if(i==null)return j;var k=Array.isArray(i),l=Array.isArray(j);if(k&&l){i.push.apply(i,j);return i;}if(k){i.push(j);return i;}if(l)return [i].concat(j);return [i,j];}e.exports=h;},null);
__d("forEachAccumulated",[],function(a,b,c,d,e,f){"use strict";var g=function(h,i,j){if(Array.isArray(h)){h.forEach(i,j);}else if(h)i.call(j,h);};e.exports=g;},null);
__d("EventPluginHub",["EventPluginRegistry","EventPluginUtils","accumulateInto","forEachAccumulated","invariant"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l={},m=null,n=function(event){if(event){var r=h.executeDispatch,s=g.getPluginModuleForEvent(event);if(s&&s.executeDispatch)r=s.executeDispatch;h.executeDispatchesInOrder(event,r);if(!event.isPersistent())event.constructor.release(event);}},o=null;function p(){var r=!o||!o.traverseTwoPhase||!o.traverseEnterLeave;if(r)throw new Error('InstanceHandle not injected before use!');}var q={injection:{injectMount:h.injection.injectMount,injectInstanceHandle:function(r){o=r;},getInstanceHandle:function(){return o;},injectEventPluginOrder:g.injectEventPluginOrder,injectEventPluginsByName:g.injectEventPluginsByName},eventNameDispatchConfigs:g.eventNameDispatchConfigs,registrationNameModules:g.registrationNameModules,putListener:function(r,s,t){k(!t||typeof t==='function');var u=l[s]||(l[s]={});u[r]=t;},getListener:function(r,s){var t=l[s];return t&&t[r];},deleteListener:function(r,s){var t=l[s];if(t)delete t[r];},deleteAllListeners:function(r){for(var s in l)delete l[s][r];},extractEvents:function(r,s,t,u){var v,w=g.plugins;for(var x=0,y=w.length;x<y;x++){var z=w[x];if(z){var aa=z.extractEvents(r,s,t,u);if(aa)v=i(v,aa);}}return v;},enqueueEvents:function(r){if(r)m=i(m,r);},processEventQueue:function(){var r=m;m=null;j(r,n);k(!m);},__purge:function(){l={};},__getListenerBank:function(){return l;}};e.exports=q;},null);
__d("ReactEventEmitterMixin",["EventPluginHub"],function(a,b,c,d,e,f,g){"use strict";function h(j){g.enqueueEvents(j);g.processEventQueue();}var i={handleTopLevel:function(j,k,l,m){var n=g.extractEvents(j,k,l,m);h(n);}};e.exports=i;},null);
__d("ViewportMetrics",[],function(a,b,c,d,e,f){"use strict";var g={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(h){g.currentScrollLeft=h.x;g.currentScrollTop=h.y;}};e.exports=g;},null);
__d("isEventSupported",["ExecutionEnvironment"],function(a,b,c,d,e,f,g){"use strict";var h;if(g.canUseDOM)h=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature('','')!==true;function i(j,k){if(!g.canUseDOM||k&&!('addEventListener' in document))return false;var l='on'+j,m=l in document;if(!m){var n=document.createElement('div');n.setAttribute(l,'return;');m=typeof n[l]==='function';}if(!m&&h&&j==='wheel')m=document.implementation.hasFeature('Events.wheel','3.0');return m;}e.exports=i;},null);
__d("ReactBrowserEventEmitter",["EventConstants","EventPluginHub","EventPluginRegistry","ReactEventEmitterMixin","ViewportMetrics","Object.assign","isEventSupported"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n={},o=false,p=0,q={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'},r="_reactListenersID"+String(Math.random()).slice(2);function s(u){if(!Object.prototype.hasOwnProperty.call(u,r)){u[r]=p++;n[u[r]]={};}return n[u[r]];}var t=l({},j,{ReactEventListener:null,injection:{injectReactEventListener:function(u){u.setHandleTopLevel(t.handleTopLevel);t.ReactEventListener=u;}},setEnabled:function(u){if(t.ReactEventListener)t.ReactEventListener.setEnabled(u);},isEnabled:function(){return !!(t.ReactEventListener&&t.ReactEventListener.isEnabled());},listenTo:function(u,v){var w=v,x=s(w),y=i.registrationNameDependencies[u],z=g.topLevelTypes;for(var aa=0,ba=y.length;aa<ba;aa++){var ca=y[aa];if(!(x.hasOwnProperty(ca)&&x[ca])){if(ca===z.topWheel){if(m('wheel')){t.ReactEventListener.trapBubbledEvent(z.topWheel,'wheel',w);}else if(m('mousewheel')){t.ReactEventListener.trapBubbledEvent(z.topWheel,'mousewheel',w);}else t.ReactEventListener.trapBubbledEvent(z.topWheel,'DOMMouseScroll',w);}else if(ca===z.topScroll){if(m('scroll',true)){t.ReactEventListener.trapCapturedEvent(z.topScroll,'scroll',w);}else t.ReactEventListener.trapBubbledEvent(z.topScroll,'scroll',t.ReactEventListener.WINDOW_HANDLE);}else if(ca===z.topFocus||ca===z.topBlur){if(m('focus',true)){t.ReactEventListener.trapCapturedEvent(z.topFocus,'focus',w);t.ReactEventListener.trapCapturedEvent(z.topBlur,'blur',w);}else if(m('focusin')){t.ReactEventListener.trapBubbledEvent(z.topFocus,'focusin',w);t.ReactEventListener.trapBubbledEvent(z.topBlur,'focusout',w);}x[z.topBlur]=true;x[z.topFocus]=true;}else if(q.hasOwnProperty(ca))t.ReactEventListener.trapBubbledEvent(ca,q[ca],w);x[ca]=true;}}},trapBubbledEvent:function(u,v,w){return t.ReactEventListener.trapBubbledEvent(u,v,w);},trapCapturedEvent:function(u,v,w){return t.ReactEventListener.trapCapturedEvent(u,v,w);},ensureScrollValueMonitoring:function(){if(!o){var u=k.refreshScrollValues;t.ReactEventListener.monitorScrollValue(u);o=true;}},eventNameDispatchConfigs:h.eventNameDispatchConfigs,registrationNameModules:h.registrationNameModules,putListener:h.putListener,getListener:h.getListener,deleteListener:h.deleteListener,deleteAllListeners:h.deleteAllListeners});e.exports=t;},null);
__d("deprecated",["Object.assign","warning"],function(a,b,c,d,e,f,g,h){function i(j,k,l,m,n){var o=false;return n;}e.exports=i;},null);
__d("getReactRootElementInContainer",[],function(a,b,c,d,e,f){"use strict";var g=9;function h(i){if(!i)return null;if(i.nodeType===g){return i.documentElement;}else return i.firstChild;}e.exports=h;},null);
__d("ReactMount",["DOMProperty","ReactBrowserEventEmitter","ReactCurrentOwner","ReactElement","ReactInstanceHandles","ReactPerf","containsNode","deprecated","getReactRootElementInContainer","instantiateReactComponent","invariant","shouldUpdateReactComponent","warning"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s){"use strict";var t=k.SEPARATOR,u=g.ID_ATTRIBUTE_NAME,v={},w=1,x=9,y={},z={},aa=[];function ba(ma){var na=o(ma);return na&&la.getID(na);}function ca(ma){var na=da(ma);if(na)if(v.hasOwnProperty(na)){var oa=v[na];if(oa!==ma){q(!ga(oa,na));v[na]=ma;}}else v[na]=ma;return na;}function da(ma){return ma&&ma.getAttribute&&ma.getAttribute(u)||'';}function ea(ma,na){var oa=da(ma);if(oa!==na)delete v[oa];ma.setAttribute(u,na);v[na]=ma;}function fa(ma){if(!v.hasOwnProperty(ma)||!ga(v[ma],ma))v[ma]=la.findReactNodeByID(ma);return v[ma];}function ga(ma,na){if(ma){q(da(ma)===na);var oa=la.findReactContainerForID(na);if(oa&&m(oa,ma))return true;}return false;}function ha(ma){delete v[ma];}var ia=null;function ja(ma){var na=v[ma];if(na&&ga(na,ma)){ia=na;}else return false;}function ka(ma){ia=null;k.traverseAncestors(ma,ja);var na=ia;ia=null;return na;}var la={_instancesByReactRootID:y,scrollMonitor:function(ma,na){na();},_updateRootComponent:function(ma,na,oa,pa){var qa=na.props;la.scrollMonitor(oa,function(){ma.replaceProps(qa,pa);});return ma;},_registerComponent:function(ma,na){q(na&&(na.nodeType===w||na.nodeType===x));h.ensureScrollValueMonitoring();var oa=la.registerContainer(na);y[oa]=ma;return oa;},_renderNewRootComponent:l.measure('ReactMount','_renderNewRootComponent',function(ma,na,oa){s(i.current==null,'_renderNewRootComponent(): Render methods should be a pure function '+'of props and state; triggering nested component updates from '+'render is not allowed. If necessary, trigger nested updates in '+'componentDidUpdate.');var pa=p(ma,null),qa=la._registerComponent(pa,na);pa.mountComponentIntoNode(qa,na,oa);return pa;}),render:function(ma,na,oa){q(j.isValidElement(ma));var pa=y[ba(na)];if(pa){var qa=pa._currentElement;if(r(qa,ma)){return la._updateRootComponent(pa,ma,na,oa);}else la.unmountComponentAtNode(na);}var ra=o(na),sa=ra&&la.isRenderedByReact(ra),ta=sa&&!pa,ua=la._renderNewRootComponent(ma,na,ta);oa&&oa.call(ua);return ua;},constructAndRenderComponent:function(ma,na,oa){var pa=j.createElement(ma,na);return la.render(pa,oa);},constructAndRenderComponentByID:function(ma,na,oa){var pa=document.getElementById(oa);q(pa);return la.constructAndRenderComponent(ma,na,pa);},registerContainer:function(ma){var na=ba(ma);if(na)na=k.getReactRootIDFromNodeID(na);if(!na)na=k.createReactRootID();z[na]=ma;return na;},unmountComponentAtNode:function(ma){s(i.current==null,'unmountComponentAtNode(): Render methods should be a pure function of '+'props and state; triggering nested component updates from render is '+'not allowed. If necessary, trigger nested updates in '+'componentDidUpdate.');q(ma&&(ma.nodeType===w||ma.nodeType===x));var na=ba(ma),oa=y[na];if(!oa)return false;la.unmountComponentFromNode(oa,ma);delete y[na];delete z[na];return true;},unmountComponentFromNode:function(ma,na){ma.unmountComponent();if(na.nodeType===x)na=na.documentElement;while(na.lastChild)na.removeChild(na.lastChild);},findReactContainerForID:function(ma){var na=k.getReactRootIDFromNodeID(ma),oa=z[na];return oa;},findReactNodeByID:function(ma){var na=la.findReactContainerForID(ma);return la.findComponentRoot(na,ma);},isRenderedByReact:function(ma){if(ma.nodeType!==1)return false;var na=la.getID(ma);return na?na.charAt(0)===t:false;},getFirstReactDOM:function(ma){var na=ma;while(na&&na.parentNode!==na){if(la.isRenderedByReact(na))return na;na=na.parentNode;}return null;},findComponentRoot:function(ma,na){var oa=aa,pa=0,qa=ka(na)||ma;oa[0]=qa.firstChild;oa.length=1;while(pa<oa.length){var ra=oa[pa++],sa;while(ra){var ta=la.getID(ra);if(ta){if(na===ta){sa=ra;}else if(k.isAncestorIDOf(ta,na)){oa.length=pa=0;oa.push(ra.firstChild);}}else oa.push(ra.firstChild);ra=ra.nextSibling;}if(sa){oa.length=0;return sa;}}oa.length=0;q(false);},getReactRootID:ba,getID:ca,setID:ea,getNode:fa,purgeID:ha};la.renderComponent=n('ReactMount','renderComponent','render',this,la.render);e.exports=la;},null);
__d("ReactBrowserComponentMixin",["ReactEmptyComponent","ReactMount","invariant"],function(a,b,c,d,e,f,g,h,i){"use strict";var j={getDOMNode:function(){i(this.isMounted());if(g.isNullComponentID(this._rootNodeID))return null;return h.getNode(this._rootNodeID);}};e.exports=j;},null);
__d("ReactMultiChildUpdateTypes",["keyMirror"],function(a,b,c,d,e,f,g){"use strict";var h=g({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});e.exports=h;},null);
__d("ReactTextComponent",["DOMPropertyOperations","ReactComponent","ReactElement","Object.assign","escapeTextForBrowser","invariant"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";var m=function(o){};j(m.prototype,h.Mixin,{mountComponent:function(o,p,q){h.Mixin.mountComponent.call(this,o,p,q);var r=k(this.props);if(p.renderToStaticMarkup)return r;return ('<span '+g.createMarkupForID(o)+'>'+r+'</span>');},receiveComponent:function(o,p){var q=o.props;if(q!==this.props){this.props=q;h.BackendIDOperations.updateTextContentByID(this._rootNodeID,q);}},updateComponent:function(){l(false);}});var n=function(o){return new i(m,null,null,null,null,o);};n.type=m;e.exports=n;},null);
__d("flattenChildren",["ReactTextComponent","traverseAllChildren","warning"],function(a,b,c,d,e,f,g,h,i){"use strict";function j(l,m,n){var o=l,p=!o.hasOwnProperty(n);i(p,'flattenChildren(...): Encountered two children with the same key, '+'`%s`. Child keys must be unique; when two children share a key, only '+'the first child will be used.',n);if(p&&m!=null){var q=typeof m,r;if(q==='string'){r=g(m);}else if(q==='number'){r=g(''+m);}else r=m;o[n]=r;}}function k(l){if(l==null)return l;var m={};h(l,j,m);return m;}e.exports=k;},null);
__d("ReactDOMComponent",["CSSPropertyOperations","DOMProperty","DOMPropertyOperations","ReactBrowserComponentMixin","ReactComponent","ReactBrowserEventEmitter","ReactMount","ReactMultiChild","ReactPerf","Object.assign","escapeTextForBrowser","invariant","isEventSupported","keyOf","monitorCodeUse"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){"use strict";var v=l.deleteListener,w=l.listenTo,x=l.registrationNameModules,y={string:true,number:true},z=t({style:null}),aa=1;function ba(ja){if(!ja)return;r(ja.children==null||ja.dangerouslySetInnerHTML==null);r(ja.style==null||typeof ja.style==='object');}function ca(ja,ka,la,ma){var na=m.findReactContainerForID(ja);if(na){var oa=na.nodeType===aa?na.ownerDocument:na;w(ka,oa);}ma.getPutListenerQueue().enqueuePutListener(ja,ka,la);}var da={area:true,base:true,br:true,col:true,embed:true,hr:true,img:true,input:true,keygen:true,link:true,meta:true,param:true,source:true,track:true,wbr:true},ea=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,fa={},ga={}.hasOwnProperty;function ha(ja){if(!ga.call(fa,ja)){r(ea.test(ja));fa[ja]=true;}}function ia(ja){ha(ja);this._tag=ja;this.tagName=ja.toUpperCase();}ia.displayName='ReactDOMComponent';ia.Mixin={mountComponent:o.measure('ReactDOMComponent','mountComponent',function(ja,ka,la){k.Mixin.mountComponent.call(this,ja,ka,la);ba(this.props);var ma=da[this._tag]?'':'</'+this._tag+'>';return (this._createOpenTagMarkupAndPutListeners(ka)+this._createContentMarkup(ka)+ma);}),_createOpenTagMarkupAndPutListeners:function(ja){var ka=this.props,la='<'+this._tag;for(var ma in ka){if(!ka.hasOwnProperty(ma))continue;var na=ka[ma];if(na==null)continue;if(x.hasOwnProperty(ma)){ca(this._rootNodeID,ma,na,ja);}else{if(ma===z){if(na)na=ka.style=p({},ka.style);na=g.createMarkupForStyles(na);}var oa=i.createMarkupForProperty(ma,na);if(oa)la+=' '+oa;}}if(ja.renderToStaticMarkup)return la+'>';var pa=i.createMarkupForID(this._rootNodeID);return la+' '+pa+'>';},_createContentMarkup:function(ja){var ka='';if(this._tag==='listing'||this._tag==='pre'||this._tag==='textarea')ka='\n';var la=this.props.dangerouslySetInnerHTML;if(la!=null){if(la.__html!=null)return ka+la.__html;}else{var ma=y[typeof this.props.children]?this.props.children:null,na=ma!=null?null:this.props.children;if(ma!=null){return ka+q(ma);}else if(na!=null){var oa=this.mountChildren(na,ja);return ka+oa.join('');}}return ka;},receiveComponent:function(ja,ka){if(ja===this._currentElement&&ja._owner!=null)return;k.Mixin.receiveComponent.call(this,ja,ka);},updateComponent:o.measure('ReactDOMComponent','updateComponent',function(ja,ka,la){ba(this._currentElement.props);k.Mixin.updateComponent.call(this,ja,ka,la);this._updateDOMProperties(ka.props,ja);this._updateDOMChildren(ka.props,ja);}),_updateDOMProperties:function(ja,ka){var la=this.props,ma,na,oa;for(ma in ja){if(la.hasOwnProperty(ma)||!ja.hasOwnProperty(ma))continue;if(ma===z){var pa=ja[ma];for(na in pa)if(pa.hasOwnProperty(na)){oa=oa||{};oa[na]='';}}else if(x.hasOwnProperty(ma)){v(this._rootNodeID,ma);}else if(h.isStandardName[ma]||h.isCustomAttribute(ma))k.BackendIDOperations.deletePropertyByID(this._rootNodeID,ma);}for(ma in la){var qa=la[ma],ra=ja[ma];if(!la.hasOwnProperty(ma)||qa===ra)continue;if(ma===z){if(qa)qa=la.style=p({},qa);if(ra){for(na in ra)if(ra.hasOwnProperty(na)&&(!qa||!qa.hasOwnProperty(na))){oa=oa||{};oa[na]='';}for(na in qa)if(qa.hasOwnProperty(na)&&ra[na]!==qa[na]){oa=oa||{};oa[na]=qa[na];}}else oa=qa;}else if(x.hasOwnProperty(ma)){ca(this._rootNodeID,ma,qa,ka);}else if(h.isStandardName[ma]||h.isCustomAttribute(ma))k.BackendIDOperations.updatePropertyByID(this._rootNodeID,ma,qa);}if(oa)k.BackendIDOperations.updateStylesByID(this._rootNodeID,oa);},_updateDOMChildren:function(ja,ka){var la=this.props,ma=y[typeof ja.children]?ja.children:null,na=y[typeof la.children]?la.children:null,oa=ja.dangerouslySetInnerHTML&&ja.dangerouslySetInnerHTML.__html,pa=la.dangerouslySetInnerHTML&&la.dangerouslySetInnerHTML.__html,qa=ma!=null?null:ja.children,ra=na!=null?null:la.children,sa=ma!=null||oa!=null,ta=na!=null||pa!=null;if(qa!=null&&ra==null){this.updateChildren(null,ka);}else if(sa&&!ta)this.updateTextContent('');if(na!=null){if(ma!==na)this.updateTextContent(''+na);}else if(pa!=null){if(oa!==pa)k.BackendIDOperations.updateInnerHTMLByID(this._rootNodeID,pa);}else if(ra!=null)this.updateChildren(ra,ka);},unmountComponent:function(){this.unmountChildren();l.deleteAllListeners(this._rootNodeID);k.Mixin.unmountComponent.call(this);}};p(ia.prototype,k.Mixin,ia.Mixin,n.Mixin,j);e.exports=ia;},null);
__d("EventPropagators",["EventConstants","EventPluginHub","accumulateInto","forEachAccumulated"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k=g.PropagationPhases,l=h.getListener;function m(v,event,w){var x=event.dispatchConfig.phasedRegistrationNames[w];return l(v,x);}function n(v,w,event){var x=w?k.bubbled:k.captured,y=m(v,event,x);if(y){event._dispatchListeners=i(event._dispatchListeners,y);event._dispatchIDs=i(event._dispatchIDs,v);}}function o(event){if(event&&event.dispatchConfig.phasedRegistrationNames)h.injection.getInstanceHandle().traverseTwoPhase(event.dispatchMarker,n,event);}function p(v,w,event){if(event&&event.dispatchConfig.registrationName){var x=event.dispatchConfig.registrationName,y=l(v,x);if(y){event._dispatchListeners=i(event._dispatchListeners,y);event._dispatchIDs=i(event._dispatchIDs,v);}}}function q(event){if(event&&event.dispatchConfig.registrationName)p(event.dispatchMarker,null,event);}function r(v){j(v,o);}function s(v,w,x,y){h.injection.getInstanceHandle().traverseEnterLeave(x,y,p,v,w);}function t(v){j(v,q);}var u={accumulateTwoPhaseDispatches:r,accumulateDirectDispatches:t,accumulateEnterLeaveDispatches:s};e.exports=u;},null);
__d("getEventTarget",[],function(a,b,c,d,e,f){"use strict";function g(h){var i=h.target||h.srcElement||window;return i.nodeType===3?i.parentNode:i;}e.exports=g;},null);
__d("SyntheticEvent",["PooledClass","Object.assign","emptyFunction","getEventTarget"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k={type:null,target:j,currentTarget:i.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(event){return event.timeStamp||Date.now();},defaultPrevented:null,isTrusted:null};function l(m,n,o){this.dispatchConfig=m;this.dispatchMarker=n;this.nativeEvent=o;var p=this.constructor.Interface;for(var q in p){if(!p.hasOwnProperty(q))continue;var r=p[q];if(r){this[q]=r(o);}else this[q]=o[q];}var s=o.defaultPrevented!=null?o.defaultPrevented:o.returnValue===false;if(s){this.isDefaultPrevented=i.thatReturnsTrue;}else this.isDefaultPrevented=i.thatReturnsFalse;this.isPropagationStopped=i.thatReturnsFalse;}h(l.prototype,{preventDefault:function(){this.defaultPrevented=true;var event=this.nativeEvent;event.preventDefault?event.preventDefault():event.returnValue=false;this.isDefaultPrevented=i.thatReturnsTrue;},stopPropagation:function(){var event=this.nativeEvent;event.stopPropagation?event.stopPropagation():event.cancelBubble=true;this.isPropagationStopped=i.thatReturnsTrue;},persist:function(){this.isPersistent=i.thatReturnsTrue;},isPersistent:i.thatReturnsFalse,destructor:function(){var m=this.constructor.Interface;for(var n in m)this[n]=null;this.dispatchConfig=null;this.dispatchMarker=null;this.nativeEvent=null;}});l.Interface=k;l.augmentClass=function(m,n){var o=this,p=Object.create(o.prototype);h(p,m.prototype);m.prototype=p;m.prototype.constructor=m;m.Interface=h({},o.Interface,n);m.augmentClass=o.augmentClass;g.addPoolingTo(m,g.threeArgumentPooler);};g.addPoolingTo(l,g.threeArgumentPooler);e.exports=l;},null);
__d("SyntheticInputEvent",["SyntheticEvent"],function(a,b,c,d,e,f,g){"use strict";var h={data:null};function i(j,k,l){g.call(this,j,k,l);}g.augmentClass(i,h);e.exports=i;},null);
__d("BeforeInputEventPlugin",["EventConstants","EventPropagators","ExecutionEnvironment","SyntheticInputEvent","keyOf"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=(i.canUseDOM&&'TextEvent' in window&&!('documentMode' in document||m()));function m(){var v=window.opera;return (typeof v==='object'&&typeof v.version==='function'&&parseInt(v.version(),10)<=12);}var n=32,o=String.fromCharCode(n),p=g.topLevelTypes,q={beforeInput:{phasedRegistrationNames:{bubbled:k({onBeforeInput:null}),captured:k({onBeforeInputCapture:null})},dependencies:[p.topCompositionEnd,p.topKeyPress,p.topTextInput,p.topPaste]}},r=null,s=false;function t(v){return ((v.ctrlKey||v.altKey||v.metaKey)&&!(v.ctrlKey&&v.altKey));}var u={eventTypes:q,extractEvents:function(v,w,x,y){var z;if(l){switch(v){case p.topKeyPress:var aa=y.which;if(aa!==n)return;s=true;z=o;break;case p.topTextInput:z=y.data;if(z===o&&s)return;break;default:return;}}else{switch(v){case p.topPaste:r=null;break;case p.topKeyPress:if(y.which&&!t(y))r=String.fromCharCode(y.which);break;case p.topCompositionEnd:r=y.data;break;}if(r===null)return;z=r;}if(!z)return;var event=j.getPooled(q.beforeInput,x,y);event.data=z;r=null;h.accumulateTwoPhaseDispatches(event);return event;}};e.exports=u;},null);
__d("isTextInputElement",[],function(a,b,c,d,e,f){"use strict";var g={color:true,date:true,datetime:true,'datetime-local':true,email:true,month:true,number:true,password:true,range:true,search:true,tel:true,text:true,time:true,url:true,week:true};function h(i){return i&&((i.nodeName==='INPUT'&&g[i.type])||i.nodeName==='TEXTAREA');}e.exports=h;},null);
__d("ChangeEventPlugin",["EventConstants","EventPluginHub","EventPropagators","ExecutionEnvironment","ReactUpdates","SyntheticEvent","isEventSupported","isTextInputElement","keyOf"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){"use strict";var p=g.topLevelTypes,q={change:{phasedRegistrationNames:{bubbled:o({onChange:null}),captured:o({onChangeCapture:null})},dependencies:[p.topBlur,p.topChange,p.topClick,p.topFocus,p.topInput,p.topKeyDown,p.topKeyUp,p.topSelectionChange]}},r=null,s=null,t=null,u=null;function v(oa){return (oa.nodeName==='SELECT'||(oa.nodeName==='INPUT'&&oa.type==='file'));}var w=false;if(j.canUseDOM)w=m('change')&&(!('documentMode' in document)||document.documentMode>8);function x(oa){var event=l.getPooled(q.change,s,oa);i.accumulateTwoPhaseDispatches(event);k.batchedUpdates(y,event);}function y(event){h.enqueueEvents(event);h.processEventQueue();}function z(oa,pa){r=oa;s=pa;r.attachEvent('onchange',x);}function aa(){if(!r)return;r.detachEvent('onchange',x);r=null;s=null;}function ba(oa,pa,qa){if(oa===p.topChange)return qa;}function ca(oa,pa,qa){if(oa===p.topFocus){aa();z(pa,qa);}else if(oa===p.topBlur)aa();}var da=false;if(j.canUseDOM)da=m('input')&&(!('documentMode' in document)||document.documentMode>9);var ea={get:function(){return u.get.call(this);},set:function(oa){t=''+oa;u.set.call(this,oa);}};function fa(oa,pa){r=oa;s=pa;t=oa.value;u=Object.getOwnPropertyDescriptor(oa.constructor.prototype,'value');Object.defineProperty(r,'value',ea);r.attachEvent('onpropertychange',ha);}function ga(){if(!r)return;delete r.value;r.detachEvent('onpropertychange',ha);r=null;s=null;t=null;u=null;}function ha(oa){if(oa.propertyName!=='value')return;var pa=oa.srcElement.value;if(pa===t)return;t=pa;x(oa);}function ia(oa,pa,qa){if(oa===p.topInput)return qa;}function ja(oa,pa,qa){if(oa===p.topFocus){ga();fa(pa,qa);}else if(oa===p.topBlur)ga();}function ka(oa,pa,qa){if(oa===p.topSelectionChange||oa===p.topKeyUp||oa===p.topKeyDown)if(r&&r.value!==t){t=r.value;return s;}}function la(oa){return (oa.nodeName==='INPUT'&&(oa.type==='checkbox'||oa.type==='radio'));}function ma(oa,pa,qa){if(oa===p.topClick)return qa;}var na={eventTypes:q,extractEvents:function(oa,pa,qa,ra){var sa,ta;if(v(pa)){if(w){sa=ba;}else ta=ca;}else if(n(pa)){if(da){sa=ia;}else{sa=ka;ta=ja;}}else if(la(pa))sa=ma;if(sa){var ua=sa(oa,pa,qa);if(ua){var event=l.getPooled(q.change,ua,ra);i.accumulateTwoPhaseDispatches(event);return event;}}if(ta)ta(oa,pa,qa);}};e.exports=na;},null);
__d("ClientReactRootIndex",[],function(a,b,c,d,e,f){"use strict";var g=0,h={createReactRootIndex:function(){return g++;}};e.exports=h;},null);
__d("getNodeForCharacterOffset",[],function(a,b,c,d,e,f){"use strict";function g(j){while(j&&j.firstChild)j=j.firstChild;return j;}function h(j){while(j){if(j.nextSibling)return j.nextSibling;j=j.parentNode;}}function i(j,k){var l=g(j),m=0,n=0;while(l){if(l.nodeType==3){n=m+l.textContent.length;if(m<=k&&n>=k)return {node:l,offset:k-m};m=n;}l=g(h(l));}}e.exports=i;},null);
__d("getTextContentAccessor",["ExecutionEnvironment"],function(a,b,c,d,e,f,g){"use strict";var h=null;function i(){if(!h&&g.canUseDOM)h='textContent' in document.documentElement?'textContent':'innerText';return h;}e.exports=i;},null);
__d("ReactDOMSelection",["ExecutionEnvironment","getNodeForCharacterOffset","getTextContentAccessor"],function(a,b,c,d,e,f,g,h,i){"use strict";function j(q,r,s,t){return q===s&&r===t;}function k(q){var r=document.selection,s=r.createRange(),t=s.text.length,u=s.duplicate();u.moveToElementText(q);u.setEndPoint('EndToStart',s);var v=u.text.length,w=v+t;return {start:v,end:w};}function l(q){var r=window.getSelection&&window.getSelection();if(!r||r.rangeCount===0)return null;var s=r.anchorNode,t=r.anchorOffset,u=r.focusNode,v=r.focusOffset,w=r.getRangeAt(0),x=j(r.anchorNode,r.anchorOffset,r.focusNode,r.focusOffset),y=x?0:w.toString().length,z=w.cloneRange();z.selectNodeContents(q);z.setEnd(w.startContainer,w.startOffset);var aa=j(z.startContainer,z.startOffset,z.endContainer,z.endOffset),ba=aa?0:z.toString().length,ca=ba+y,da=document.createRange();da.setStart(s,t);da.setEnd(u,v);var ea=da.collapsed;return {start:ea?ca:ba,end:ea?ba:ca};}function m(q,r){var s=document.selection.createRange().duplicate(),t,u;if(typeof r.end==='undefined'){t=r.start;u=t;}else if(r.start>r.end){t=r.end;u=r.start;}else{t=r.start;u=r.end;}s.moveToElementText(q);s.moveStart('character',t);s.setEndPoint('EndToStart',s);s.moveEnd('character',u-t);s.select();}function n(q,r){if(!window.getSelection)return;var s=window.getSelection(),t=q[i()].length,u=Math.min(r.start,t),v=typeof r.end==='undefined'?u:Math.min(r.end,t);if(!s.extend&&u>v){var w=v;v=u;u=w;}var x=h(q,u),y=h(q,v);if(x&&y){var z=document.createRange();z.setStart(x.node,x.offset);s.removeAllRanges();if(u>v){s.addRange(z);s.extend(y.node,y.offset);}else{z.setEnd(y.node,y.offset);s.addRange(z);}}}var o=g.canUseDOM&&document.selection,p={getOffsets:o?k:l,setOffsets:o?m:n};e.exports=p;},null);
__d("focusNode",[],function(a,b,c,d,e,f){"use strict";function g(h){try{h.focus();}catch(i){}}e.exports=g;},null);
__d("ReactInputSelection",["ReactDOMSelection","containsNode","focusNode","getActiveElement"],function(a,b,c,d,e,f,g,h,i,j){"use strict";function k(m){return h(document.documentElement,m);}var l={hasSelectionCapabilities:function(m){return m&&((m.nodeName==='INPUT'&&m.type==='text')||m.nodeName==='TEXTAREA'||m.contentEditable==='true');},getSelectionInformation:function(){var m=j();return {focusedElem:m,selectionRange:l.hasSelectionCapabilities(m)?l.getSelection(m):null};},restoreSelection:function(m){var n=j(),o=m.focusedElem,p=m.selectionRange;if(n!==o&&k(o)){if(l.hasSelectionCapabilities(o))l.setSelection(o,p);i(o);}},getSelection:function(m){var n;if('selectionStart' in m){n={start:m.selectionStart,end:m.selectionEnd};}else if(document.selection&&m.nodeName==='INPUT'){var o=document.selection.createRange();if(o.parentElement()===m)n={start:-o.moveStart('character',-m.value.length),end:-o.moveEnd('character',-m.value.length)};}else n=g.getOffsets(m);return n||{start:0,end:0};},setSelection:function(m,n){var o=n.start,p=n.end;if(typeof p==='undefined')p=o;if('selectionStart' in m){m.selectionStart=o;m.selectionEnd=Math.min(p,m.value.length);}else if(document.selection&&m.nodeName==='INPUT'){var q=m.createTextRange();q.collapse(true);q.moveStart('character',o);q.moveEnd('character',p-o);q.select();}else g.setOffsets(m,n);}};e.exports=l;},null);
__d("SyntheticCompositionEvent",["SyntheticEvent"],function(a,b,c,d,e,f,g){"use strict";var h={data:null};function i(j,k,l){g.call(this,j,k,l);}g.augmentClass(i,h);e.exports=i;},null);
__d("CompositionEventPlugin",["EventConstants","EventPropagators","ExecutionEnvironment","ReactInputSelection","SyntheticCompositionEvent","getTextContentAccessor","keyOf"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n=[9,13,27,32],o=229,p=(i.canUseDOM&&'CompositionEvent' in window),q=(!p||('documentMode' in document&&document.documentMode>8&&document.documentMode<=11)),r=g.topLevelTypes,s=null,t={compositionEnd:{phasedRegistrationNames:{bubbled:m({onCompositionEnd:null}),captured:m({onCompositionEndCapture:null})},dependencies:[r.topBlur,r.topCompositionEnd,r.topKeyDown,r.topKeyPress,r.topKeyUp,r.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:m({onCompositionStart:null}),captured:m({onCompositionStartCapture:null})},dependencies:[r.topBlur,r.topCompositionStart,r.topKeyDown,r.topKeyPress,r.topKeyUp,r.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:m({onCompositionUpdate:null}),captured:m({onCompositionUpdateCapture:null})},dependencies:[r.topBlur,r.topCompositionUpdate,r.topKeyDown,r.topKeyPress,r.topKeyUp,r.topMouseDown]}};function u(z){switch(z){case r.topCompositionStart:return t.compositionStart;case r.topCompositionEnd:return t.compositionEnd;case r.topCompositionUpdate:return t.compositionUpdate;}}function v(z,aa){return (z===r.topKeyDown&&aa.keyCode===o);}function w(z,aa){switch(z){case r.topKeyUp:return (n.indexOf(aa.keyCode)!==-1);case r.topKeyDown:return (aa.keyCode!==o);case r.topKeyPress:case r.topMouseDown:case r.topBlur:return true;default:return false;}}function x(z){this.root=z;this.startSelection=j.getSelection(z);this.startValue=this.getText();}x.prototype.getText=function(){return this.root.value||this.root[l()];};x.prototype.getData=function(){var z=this.getText(),aa=this.startSelection.start,ba=this.startValue.length-this.startSelection.end;return z.substr(aa,z.length-ba-aa);};var y={eventTypes:t,extractEvents:function(z,aa,ba,ca){var da,ea;if(p){da=u(z);}else if(!s){if(v(z,ca))da=t.compositionStart;}else if(w(z,ca))da=t.compositionEnd;if(q)if(!s&&da===t.compositionStart){s=new x(aa);}else if(da===t.compositionEnd)if(s){ea=s.getData();s=null;}if(da){var event=k.getPooled(da,ba,ca);if(ea)event.data=ea;h.accumulateTwoPhaseDispatches(event);return event;}}};e.exports=y;},null);
__d("getEventModifierState",[],function(a,b,c,d,e,f){"use strict";var g={Alt:'altKey',Control:'ctrlKey',Meta:'metaKey',Shift:'shiftKey'};function h(j){var k=this,l=k.nativeEvent;if(l.getModifierState)return l.getModifierState(j);var m=g[j];return m?!!l[m]:false;}function i(j){return h;}e.exports=i;},null);
__d("SyntheticMouseEvent",["SyntheticUIEvent","ViewportMetrics","getEventModifierState"],function(a,b,c,d,e,f,g,h,i){"use strict";var j={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:i,button:function(event){var l=event.button;if('which' in event)return l;return l===2?2:l===4?1:0;},buttons:null,relatedTarget:function(event){return event.relatedTarget||(event.fromElement===event.srcElement?event.toElement:event.fromElement);},pageX:function(event){return 'pageX' in event?event.pageX:event.clientX+h.currentScrollLeft;},pageY:function(event){return 'pageY' in event?event.pageY:event.clientY+h.currentScrollTop;}};function k(l,m,n){g.call(this,l,m,n);}g.augmentClass(k,j);e.exports=k;},null);
__d("EnterLeaveEventPlugin",["EventConstants","EventPropagators","SyntheticMouseEvent","ReactMount","keyOf"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=g.topLevelTypes,m=j.getFirstReactDOM,n={mouseEnter:{registrationName:k({onMouseEnter:null}),dependencies:[l.topMouseOut,l.topMouseOver]},mouseLeave:{registrationName:k({onMouseLeave:null}),dependencies:[l.topMouseOut,l.topMouseOver]}},o=[null,null],p={eventTypes:n,extractEvents:function(q,r,s,t){if(q===l.topMouseOver&&(t.relatedTarget||t.fromElement))return null;if(q!==l.topMouseOut&&q!==l.topMouseOver)return null;var u;if(r.window===r){u=r;}else{var v=r.ownerDocument;if(v){u=v.defaultView||v.parentWindow;}else u=window;}var w,x;if(q===l.topMouseOut){w=r;x=m(t.relatedTarget||t.toElement)||u;}else{w=u;x=r;}if(w===x)return null;var y=w?j.getID(w):'',z=x?j.getID(x):'',aa=i.getPooled(n.mouseLeave,y,t);aa.type='mouseleave';aa.target=w;aa.relatedTarget=x;var ba=i.getPooled(n.mouseEnter,z,t);ba.type='mouseenter';ba.target=x;ba.relatedTarget=w;h.accumulateEnterLeaveDispatches(aa,ba,y,z);o[0]=aa;o[1]=ba;return o;}};e.exports=p;},null);
__d("HTMLDOMPropertyConfig-upstream",["DOMProperty","ExecutionEnvironment"],function(a,b,c,d,e,f,g,h){"use strict";var i=g.injection.MUST_USE_ATTRIBUTE,j=g.injection.MUST_USE_PROPERTY,k=g.injection.HAS_BOOLEAN_VALUE,l=g.injection.HAS_SIDE_EFFECTS,m=g.injection.HAS_NUMERIC_VALUE,n=g.injection.HAS_POSITIVE_NUMERIC_VALUE,o=g.injection.HAS_OVERLOADED_BOOLEAN_VALUE,p;if(h.canUseDOM){var q=document.implementation;p=(q&&q.hasFeature&&q.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure','1.1'));}var r={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:i|k,allowTransparency:i,alt:null,async:k,autoComplete:null,autoPlay:k,cellPadding:null,cellSpacing:null,charSet:i,checked:j|k,classID:i,className:p?i:j,cols:i|n,colSpan:null,content:null,contentEditable:null,contextMenu:i,controls:j|k,coords:null,crossOrigin:null,data:null,dateTime:i,defer:k,dir:null,disabled:i|k,download:o,draggable:null,encType:null,form:i,formNoValidate:k,frameBorder:i,height:i,hidden:i|k,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:j,label:null,lang:null,list:i,loop:j|k,manifest:i,max:null,maxLength:i,media:i,mediaGroup:null,method:null,min:null,multiple:j|k,muted:j|k,name:null,noValidate:k,open:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:j|k,rel:null,required:k,role:i,rows:i|n,rowSpan:null,sandbox:null,scope:null,scrolling:null,seamless:i|k,selected:j|k,shape:null,size:i|n,sizes:i,span:n,spellCheck:null,src:null,srcDoc:j,srcSet:i,start:m,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:j|l,width:i,wmode:i,autoCapitalize:null,autoCorrect:null,itemProp:i,itemScope:i|k,itemType: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:'enctype',hrefLang:'hreflang',radioGroup:'radiogroup',spellCheck:'spellcheck',srcDoc:'srcdoc',srcSet:'srcset'}};e.exports=r;},null);
__d("HTMLDOMPropertyConfig",["HTMLDOMPropertyConfig-upstream","DOMProperty"],function(a,b,c,d,e,f,g,h){var i=h.injection.MUST_USE_ATTRIBUTE;g.Properties.ajaxify=i;e.exports=g;},null);
__d("MobileSafariClickEventPlugin",["EventConstants","emptyFunction"],function(a,b,c,d,e,f,g,h){"use strict";var i=g.topLevelTypes,j={eventTypes:null,extractEvents:function(k,l,m,n){if(k===i.topTouchStart){var o=n.target;if(o&&!o.onclick)o.onclick=h;}}};e.exports=j;},null);
__d("Danger",["ExecutionEnvironment","createNodesFromMarkup","emptyFunction","getMarkupWrap","invariant"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=/^(<[^ \/>]+)/,m='data-danger-index';function n(p){return p.substring(1,p.indexOf(' '));}var o={dangerouslyRenderMarkup:function(p){k(g.canUseDOM);var q,r={};for(var s=0;s<p.length;s++){k(p[s]);q=n(p[s]);q=j(q)?q:'*';r[q]=r[q]||[];r[q][s]=p[s];}var t=[],u=0;for(q in r){if(!r.hasOwnProperty(q))continue;var v=r[q];for(var w in v)if(v.hasOwnProperty(w)){var x=v[w];v[w]=x.replace(l,'$1 '+m+'="'+w+'" ');}var y=h(v.join(''),i);for(s=0;s<y.length;++s){var z=y[s];if(z.hasAttribute&&z.hasAttribute(m)){w=+z.getAttribute(m);z.removeAttribute(m);k(!t.hasOwnProperty(w));t[w]=z;u+=1;}}}k(u===t.length);k(t.length===p.length);return t;},dangerouslyReplaceNodeWithMarkup:function(p,q){k(g.canUseDOM);k(q);k(p.tagName.toLowerCase()!=='html');var r=h(q,i)[0];p.parentNode.replaceChild(r,p);}};e.exports=o;},null);
__d("DOMChildrenOperations",["Danger","ReactMultiChildUpdateTypes","getTextContentAccessor","invariant"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k=i();function l(o,p,q){o.insertBefore(p,o.childNodes[q]||null);}var m;if(k==='textContent'){m=function(o,p){o.textContent=p;};}else m=function(o,p){while(o.firstChild)o.removeChild(o.firstChild);if(p){var q=o.ownerDocument||document;o.appendChild(q.createTextNode(p));}};var n={dangerouslyReplaceNodeWithMarkup:g.dangerouslyReplaceNodeWithMarkup,updateTextContent:m,processUpdates:function(o,p){var q,r=null,s=null;for(var t=0;q=o[t];t++)if(q.type===h.MOVE_EXISTING||q.type===h.REMOVE_NODE){var u=q.fromIndex,v=q.parentNode.childNodes[u],w=q.parentID;j(v);r=r||{};r[w]=r[w]||[];r[w][u]=v;s=s||[];s.push(v);}var x=g.dangerouslyRenderMarkup(p);if(s)for(var y=0;y<s.length;y++)s[y].parentNode.removeChild(s[y]);for(var z=0;q=o[z];z++)switch(q.type){case h.INSERT_MARKUP:l(q.parentNode,x[q.markupIndex],q.toIndex);break;case h.MOVE_EXISTING:l(q.parentNode,r[q.parentID][q.fromIndex],q.toIndex);break;case h.TEXT_CONTENT:m(q.parentNode,q.textContent);break;case h.REMOVE_NODE:break;}}};e.exports=n;},null);
__d("setInnerHTML",["ExecutionEnvironment"],function(a,b,c,d,e,f,g){"use strict";var h=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,j=function(l,m){l.innerHTML=m;};if(g.canUseDOM){var k=document.createElement('div');k.innerHTML=' ';if(k.innerHTML==='')j=function(l,m){if(l.parentNode)l.parentNode.replaceChild(l,l);if(h.test(m)||m[0]==='<'&&i.test(m)){l.innerHTML='\uFEFF'+m;var n=l.firstChild;if(n.data.length===1){l.removeChild(n);}else n.deleteData(0,1);}else l.innerHTML=m;};}e.exports=j;},null);
__d("ReactDOMIDOperations",["CSSPropertyOperations","DOMChildrenOperations","DOMPropertyOperations","ReactMount","ReactPerf","invariant","setInnerHTML"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n={dangerouslySetInnerHTML:'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',style:'`style` must be set using `updateStylesByID()`.'},o={updatePropertyByID:k.measure('ReactDOMIDOperations','updatePropertyByID',function(p,q,r){var s=j.getNode(p);l(!n.hasOwnProperty(q));if(r!=null){i.setValueForProperty(s,q,r);}else i.deleteValueForProperty(s,q);}),deletePropertyByID:k.measure('ReactDOMIDOperations','deletePropertyByID',function(p,q,r){var s=j.getNode(p);l(!n.hasOwnProperty(q));i.deleteValueForProperty(s,q,r);}),updateStylesByID:k.measure('ReactDOMIDOperations','updateStylesByID',function(p,q){var r=j.getNode(p);g.setValueForStyles(r,q);}),updateInnerHTMLByID:k.measure('ReactDOMIDOperations','updateInnerHTMLByID',function(p,q){var r=j.getNode(p);m(r,q);}),updateTextContentByID:k.measure('ReactDOMIDOperations','updateTextContentByID',function(p,q){var r=j.getNode(p);h.updateTextContent(r,q);}),dangerouslyReplaceNodeWithMarkupByID:k.measure('ReactDOMIDOperations','dangerouslyReplaceNodeWithMarkupByID',function(p,q){var r=j.getNode(p);h.dangerouslyReplaceNodeWithMarkup(r,q);}),dangerouslyProcessChildrenUpdates:k.measure('ReactDOMIDOperations','dangerouslyProcessChildrenUpdates',function(p,q){for(var r=0;r<p.length;r++)p[r].parentNode=j.getNode(p[r].parentID);h.processUpdates(p,q);})};e.exports=o;},null);
__d("adler32",[],function(a,b,c,d,e,f){"use strict";var g=65521;function h(i){var j=1,k=0;for(var l=0;l<i.length;l++){j=(j+i.charCodeAt(l))%g;k=(k+j)%g;}return j|(k<<16);}e.exports=h;},null);
__d("ReactMarkupChecksum",["adler32"],function(a,b,c,d,e,f,g){"use strict";var h={CHECKSUM_ATTR_NAME:'data-react-checksum',addChecksumToMarkup:function(i){var j=g(i);return i.replace('>',' '+h.CHECKSUM_ATTR_NAME+'="'+j+'">');},canReuseMarkup:function(i,j){var k=j.getAttribute(h.CHECKSUM_ATTR_NAME);k=k&&parseInt(k,10);var l=g(i);return l===k;}};e.exports=h;},null);
__d("ReactPutListenerQueue",["PooledClass","ReactBrowserEventEmitter","Object.assign"],function(a,b,c,d,e,f,g,h,i){"use strict";function j(){this.listenersToPut=[];}i(j.prototype,{enqueuePutListener:function(k,l,m){this.listenersToPut.push({rootNodeID:k,propKey:l,propValue:m});},putListeners:function(){for(var k=0;k<this.listenersToPut.length;k++){var l=this.listenersToPut[k];h.putListener(l.rootNodeID,l.propKey,l.propValue);}},reset:function(){this.listenersToPut.length=0;},destructor:function(){this.reset();}});g.addPoolingTo(j);e.exports=j;},null);
__d("ReactReconcileTransaction",["CallbackQueue","PooledClass","ReactBrowserEventEmitter","ReactInputSelection","ReactPutListenerQueue","Transaction","Object.assign"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n={initialize:j.getSelectionInformation,close:j.restoreSelection},o={initialize:function(){var u=i.isEnabled();i.setEnabled(false);return u;},close:function(u){i.setEnabled(u);}},p={initialize:function(){this.reactMountReady.reset();},close:function(){this.reactMountReady.notifyAll();}},q={initialize:function(){this.putListenerQueue.reset();},close:function(){this.putListenerQueue.putListeners();}},r=[q,n,o,p];function s(){this.reinitializeTransaction();this.renderToStaticMarkup=false;this.reactMountReady=g.getPooled(null);this.putListenerQueue=k.getPooled();}var t={getTransactionWrappers:function(){return r;},getReactMountReady:function(){return this.reactMountReady;},getPutListenerQueue:function(){return this.putListenerQueue;},destructor:function(){g.release(this.reactMountReady);this.reactMountReady=null;k.release(this.putListenerQueue);this.putListenerQueue=null;}};m(s.prototype,l.Mixin,t);h.addPoolingTo(s);e.exports=s;},null);
__d("ReactComponentBrowserEnvironment",["ReactDOMIDOperations","ReactMarkupChecksum","ReactMount","ReactPerf","ReactReconcileTransaction","getReactRootElementInContainer","invariant","setInnerHTML"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){"use strict";var o=1,p=9,q={ReactReconcileTransaction:k,BackendIDOperations:g,unmountIDFromEnvironment:function(r){i.purgeID(r);},mountImageIntoNode:j.measure('ReactComponentBrowserEnvironment','mountImageIntoNode',function(r,s,t){m(s&&(s.nodeType===o||s.nodeType===p));if(t)if(h.canReuseMarkup(r,l(s))){return;}else m(s.nodeType!==p);m(s.nodeType!==p);n(s,r);})};e.exports=q;},null);
__d("ReactDefaultBatchingStrategy",["ReactUpdates","Transaction","Object.assign","emptyFunction"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k={initialize:j,close:function(){p.isBatchingUpdates=false;}},l={initialize:j,close:g.flushBatchedUpdates.bind(g)},m=[l,k];function n(){this.reinitializeTransaction();}i(n.prototype,h.Mixin,{getTransactionWrappers:function(){return m;}});var o=new n(),p={isBatchingUpdates:false,batchedUpdates:function(q,r,s){var t=p.isBatchingUpdates;p.isBatchingUpdates=true;if(t){q(r,s);}else o.perform(q,null,r,s);}};e.exports=p;},null);
__d("AutoFocusMixin",["focusNode"],function(a,b,c,d,e,f,g){"use strict";var h={componentDidMount:function(){if(this.props.autoFocus)g(this.getDOMNode());}};e.exports=h;},null);
__d("LocalEventTrapMixin",["ReactBrowserEventEmitter","accumulateInto","forEachAccumulated","invariant"],function(a,b,c,d,e,f,g,h,i,j){"use strict";function k(event){event.remove();}var l={trapBubbledEvent:function(m,n){j(this.isMounted());var o=g.trapBubbledEvent(m,n,this.getDOMNode());this._localEventListeners=h(this._localEventListeners,o);},componentWillUnmount:function(){if(this._localEventListeners)i(this._localEventListeners,k);}};e.exports=l;},null);
__d("ReactDOMForm",["EventConstants","LocalEventTrapMixin","ReactBrowserComponentMixin","ReactClass","ReactElement"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=k.createFactory('form'),m=j.createClass({displayName:'ReactDOMForm',mixins:[i,h],render:function(){return l(this.props);},componentDidMount:function(){this.trapBubbledEvent(g.topLevelTypes.topReset,'reset');this.trapBubbledEvent(g.topLevelTypes.topSubmit,'submit');}});e.exports=m;},null);
__d("ReactDOMImg",["EventConstants","LocalEventTrapMixin","ReactBrowserComponentMixin","ReactClass","ReactElement"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=k.createFactory('img'),m=j.createClass({displayName:'ReactDOMImg',tagName:'IMG',mixins:[i,h],render:function(){return l(this.props);},componentDidMount:function(){this.trapBubbledEvent(g.topLevelTypes.topLoad,'load');this.trapBubbledEvent(g.topLevelTypes.topError,'error');}});e.exports=m;},null);
__d("ReactPropTypes",["ReactElement","ReactPropTypeLocationNames","deprecated","emptyFunction"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k='<<anonymous>>',l=s(),m=x(),n={array:p('array'),bool:p('boolean'),func:p('function'),number:p('number'),object:p('object'),string:p('string'),any:q(),arrayOf:r,element:l,instanceOf:t,node:m,objectOf:v,oneOf:u,oneOfType:w,shape:y,component:i('React.PropTypes','component','element',this,l),renderable:i('React.PropTypes','renderable','node',this,m)};function o(ca){function da(fa,ga,ha,ia,ja){ia=ia||k;if(ga[ha]==null){var ka=h[ja];if(fa)return new Error(("Required "+ka+" `"+ha+"` was not specified in ")+("`"+ia+"`."));}else return ca(ga,ha,ia,ja);}var ea=da.bind(null,false);ea.isRequired=da.bind(null,true);return ea;}function p(ca){function da(ea,fa,ga,ha){var ia=ea[fa],ja=aa(ia);if(ja!==ca){var ka=h[ha],la=ba(ia);return new Error(("Invalid "+ka+" `"+fa+"` of type `"+la+"` ")+("supplied to `"+ga+"`, expected `"+ca+"`."));}}return o(da);}function q(){return o(j.thatReturns());}function r(ca){function da(ea,fa,ga,ha){var ia=ea[fa];if(!Array.isArray(ia)){var ja=h[ha],ka=aa(ia);return new Error(("Invalid "+ja+" `"+fa+"` of type ")+("`"+ka+"` supplied to `"+ga+"`, expected an array."));}for(var la=0;la<ia.length;la++){var ma=ca(ia,la,ga,ha);if(ma instanceof Error)return ma;}}return o(da);}function s(){function ca(da,ea,fa,ga){if(!g.isValidElement(da[ea])){var ha=h[ga];return new Error(("Invalid "+ha+" `"+ea+"` supplied to ")+("`"+fa+"`, expected a ReactElement."));}}return o(ca);}function t(ca){function da(ea,fa,ga,ha){if(!(ea[fa] instanceof ca)){var ia=h[ha],ja=ca.name||k;return new Error(("Invalid "+ia+" `"+fa+"` supplied to ")+("`"+ga+"`, expected instance of `"+ja+"`."));}}return o(da);}function u(ca){function da(ea,fa,ga,ha){var ia=ea[fa];for(var ja=0;ja<ca.length;ja++)if(ia===ca[ja])return;var ka=h[ha],la=JSON.stringify(ca);return new Error(("Invalid "+ka+" `"+fa+"` of value `"+ia+"` ")+("supplied to `"+ga+"`, expected one of "+la+"."));}return o(da);}function v(ca){function da(ea,fa,ga,ha){var ia=ea[fa],ja=aa(ia);if(ja!=='object'){var ka=h[ha];return new Error(("Invalid "+ka+" `"+fa+"` of type ")+("`"+ja+"` supplied to `"+ga+"`, expected an object."));}for(var la in ia)if(ia.hasOwnProperty(la)){var ma=ca(ia,la,ga,ha);if(ma instanceof Error)return ma;}}return o(da);}function w(ca){function da(ea,fa,ga,ha){for(var ia=0;ia<ca.length;ia++){var ja=ca[ia];if(ja(ea,fa,ga,ha)==null)return;}var ka=h[ha];return new Error(("Invalid "+ka+" `"+fa+"` supplied to ")+("`"+ga+"`."));}return o(da);}function x(){function ca(da,ea,fa,ga){if(!z(da[ea])){var ha=h[ga];return new Error(("Invalid "+ha+" `"+ea+"` supplied to ")+("`"+fa+"`, expected a ReactNode."));}}return o(ca);}function y(ca){function da(ea,fa,ga,ha){var ia=ea[fa],ja=aa(ia);if(ja!=='object'){var ka=h[ha];return new Error(("Invalid "+ka+" `"+fa+"` of type `"+ja+"` ")+("supplied to `"+ga+"`, expected `object`."));}for(var la in ca){var ma=ca[la];if(!ma)continue;var na=ma(ia,la,ga,ha);if(na)return na;}}return o(da,'expected `object`');}function z(ca){switch(typeof ca){case 'number':case 'string':return true;case 'boolean':return !ca;case 'object':if(Array.isArray(ca))return ca.every(z);if(g.isValidElement(ca))return true;for(var da in ca)if(!z(ca[da]))return false;return true;default:return false;}}function aa(ca){var da=typeof ca;if(Array.isArray(ca))return 'array';if(ca instanceof RegExp)return 'object';return da;}function ba(ca){var da=aa(ca);if(da==='object')if(ca instanceof Date){return 'date';}else if(ca instanceof RegExp)return 'regexp';return da;}e.exports=n;},null);
__d("LinkedValueUtils",["ReactPropTypes","invariant"],function(a,b,c,d,e,f,g,h){"use strict";var i={button:true,checkbox:true,image:true,hidden:true,radio:true,reset:true,submit:true};function j(p){h(p.props.checkedLink==null||p.props.valueLink==null);}function k(p){j(p);h(p.props.value==null&&p.props.onChange==null);}function l(p){j(p);h(p.props.checked==null&&p.props.onChange==null);}function m(p){this.props.valueLink.requestChange(p.target.value);}function n(p){this.props.checkedLink.requestChange(p.target.checked);}var o={Mixin:{propTypes:{value:function(p,q,r){if(!p[q]||i[p.type]||p.onChange||p.readOnly||p.disabled)return;return 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(p,q,r){if(!p[q]||p.onChange||p.readOnly||p.disabled)return;return 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:g.func}},getValue:function(p){if(p.props.valueLink){k(p);return p.props.valueLink.value;}return p.props.value;},getChecked:function(p){if(p.props.checkedLink){l(p);return p.props.checkedLink.value;}return p.props.checked;},getOnChange:function(p){if(p.props.valueLink){k(p);return m;}else if(p.props.checkedLink){l(p);return n;}return p.props.onChange;}};e.exports=o;},null);
__d("ReactDOMInput",["AutoFocusMixin","DOMPropertyOperations","LinkedValueUtils","ReactBrowserComponentMixin","ReactClass","ReactElement","ReactMount","ReactUpdates","Object.assign","invariant"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){"use strict";var q=l.createFactory('input'),r={};function s(){if(this.isMounted())this.forceUpdate();}var t=k.createClass({displayName:'ReactDOMInput',mixins:[g,i.Mixin,j],getInitialState:function(){var u=this.props.defaultValue;return {initialChecked:this.props.defaultChecked||false,initialValue:u!=null?u:null};},render:function(){var u=o({},this.props);u.defaultChecked=null;u.defaultValue=null;var v=i.getValue(this);u.value=v!=null?v:this.state.initialValue;var w=i.getChecked(this);u.checked=w!=null?w:this.state.initialChecked;u.onChange=this._handleChange;return q(u,this.props.children);},componentDidMount:function(){var u=m.getID(this.getDOMNode());r[u]=this;},componentWillUnmount:function(){var u=this.getDOMNode(),v=m.getID(u);delete r[v];},componentDidUpdate:function(u,v,w){var x=this.getDOMNode();if(this.props.checked!=null)h.setValueForProperty(x,'checked',this.props.checked||false);var y=i.getValue(this);if(y!=null)h.setValueForProperty(x,'value',''+y);},_handleChange:function(event){var u,v=i.getOnChange(this);if(v)u=v.call(this,event);n.asap(s,this);var w=this.props.name;if(this.props.type==='radio'&&w!=null){var x=this.getDOMNode(),y=x;while(y.parentNode)y=y.parentNode;var z=y.querySelectorAll('input[name='+JSON.stringify(''+w)+'][type="radio"]');for(var aa=0,ba=z.length;aa<ba;aa++){var ca=z[aa];if(ca===x||ca.form!==x.form)continue;var da=m.getID(ca);p(da);var ea=r[da];p(ea);n.asap(s,ea);}}return u;}});e.exports=t;},null);
__d("ReactDOMOption",["ReactBrowserComponentMixin","ReactClass","ReactElement","warning"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k=i.createFactory('option'),l=h.createClass({displayName:'ReactDOMOption',mixins:[g],componentWillMount:function(){},render:function(){return k(this.props,this.props.children);}});e.exports=l;},null);
__d("ReactDOMSelect",["AutoFocusMixin","LinkedValueUtils","ReactBrowserComponentMixin","ReactClass","ReactElement","ReactUpdates","Object.assign"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n=k.createFactory('select');function o(){if(this.isMounted()){this.setState({value:this._pendingValue});this._pendingValue=0;}}function p(s,t,u){if(s[t]==null)return;if(s.multiple){if(!Array.isArray(s[t]))return new Error(("The `"+t+"` prop supplied to <select> must be an array if ")+("`multiple` is true."));}else if(Array.isArray(s[t]))return new Error(("The `"+t+"` prop supplied to <select> must be a scalar ")+("value if `multiple` is false."));}function q(s,t){var u=s.props.multiple,v=t!=null?t:s.state.value,w=s.getDOMNode().options,x,y,z;if(u){x={};for(y=0,z=v.length;y<z;++y)x[''+v[y]]=true;}else x=''+v;for(y=0,z=w.length;y<z;y++){var aa=u?x.hasOwnProperty(w[y].value):w[y].value===x;if(aa!==w[y].selected)w[y].selected=aa;}}var r=j.createClass({displayName:'ReactDOMSelect',mixins:[g,h.Mixin,i],propTypes:{defaultValue:p,value:p},getInitialState:function(){return {value:this.props.defaultValue||(this.props.multiple?[]:'')};},componentWillMount:function(){this._pendingValue=null;},componentWillReceiveProps:function(s){if(!this.props.multiple&&s.multiple){this.setState({value:[this.state.value]});}else if(this.props.multiple&&!s.multiple)this.setState({value:this.state.value[0]});},render:function(){var s=m({},this.props);s.onChange=this._handleChange;s.value=null;return n(s,this.props.children);},componentDidMount:function(){q(this,h.getValue(this));},componentDidUpdate:function(s){var t=h.getValue(this),u=!!s.multiple,v=!!this.props.multiple;if(t!=null||u!==v)q(this,t);},_handleChange:function(event){var s,t=h.getOnChange(this);if(t)s=t.call(this,event);var u;if(this.props.multiple){u=[];var v=event.target.options;for(var w=0,x=v.length;w<x;w++)if(v[w].selected)u.push(v[w].value);}else u=event.target.value;this._pendingValue=u;l.asap(o,this);return s;}});e.exports=r;},null);
__d("ReactDOMTextarea",["AutoFocusMixin","DOMPropertyOperations","LinkedValueUtils","ReactBrowserComponentMixin","ReactClass","ReactElement","ReactUpdates","Object.assign","invariant","warning"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){"use strict";var q=l.createFactory('textarea');function r(){if(this.isMounted())this.forceUpdate();}var s=k.createClass({displayName:'ReactDOMTextarea',mixins:[g,i.Mixin,j],getInitialState:function(){var t=this.props.defaultValue,u=this.props.children;if(u!=null){o(t==null);if(Array.isArray(u)){o(u.length<=1);u=u[0];}t=''+u;}if(t==null)t='';var v=i.getValue(this);return {initialValue:''+(v!=null?v:t)};},render:function(){var t=n({},this.props);o(t.dangerouslySetInnerHTML==null);t.defaultValue=null;t.value=null;t.onChange=this._handleChange;return q(t,this.state.initialValue);},componentDidUpdate:function(t,u,v){var w=i.getValue(this);if(w!=null){var x=this.getDOMNode();h.setValueForProperty(x,'value',''+w);}},_handleChange:function(event){var t,u=i.getOnChange(this);if(u)t=u.call(this,event);m.asap(r,this);return t;}});e.exports=s;},null);
__d("ReactEventListener",["EventListener","ExecutionEnvironment","PooledClass","ReactInstanceHandles","ReactMount","ReactUpdates","Object.assign","getEventTarget","getUnboundedScrollPosition"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){"use strict";function p(u){var v=k.getID(u),w=j.getReactRootIDFromNodeID(v),x=k.findReactContainerForID(w),y=k.getFirstReactDOM(x);return y;}function q(u,v){this.topLevelType=u;this.nativeEvent=v;this.ancestors=[];}m(q.prototype,{destructor:function(){this.topLevelType=null;this.nativeEvent=null;this.ancestors.length=0;}});i.addPoolingTo(q,i.twoArgumentPooler);function r(u){var v=k.getFirstReactDOM(n(u.nativeEvent))||window,w=v;while(w){u.ancestors.push(w);w=p(w);}for(var x=0,y=u.ancestors.length;x<y;x++){v=u.ancestors[x];var z=k.getID(v)||'';t._handleTopLevel(u.topLevelType,v,z,u.nativeEvent);}}function s(u){var v=o(window);u(v);}var t={_enabled:true,_handleTopLevel:null,WINDOW_HANDLE:h.canUseDOM?window:null,setHandleTopLevel:function(u){t._handleTopLevel=u;},setEnabled:function(u){t._enabled=!!u;},isEnabled:function(){return t._enabled;},trapBubbledEvent:function(u,v,w){var x=w;if(!x)return;return g.listen(x,v,t.dispatchEvent.bind(null,u));},trapCapturedEvent:function(u,v,w){var x=w;if(!x)return;return g.capture(x,v,t.dispatchEvent.bind(null,u));},monitorScrollValue:function(u){var v=s.bind(null,u);g.listen(window,'scroll',v);g.listen(window,'resize',v);},dispatchEvent:function(u,v){if(!t._enabled)return;var w=q.getPooled(u,v);try{l.batchedUpdates(r,w);}finally{q.release(w);}}};e.exports=t;},null);
__d("ReactInjection",["DOMProperty","EventPluginHub","ReactComponent","ReactClass","ReactEmptyComponent","ReactBrowserEventEmitter","ReactNativeComponent","ReactPerf","ReactRootIndex","ReactUpdates"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){"use strict";var q={Component:i.injection,Class:j.injection,DOMProperty:g.injection,EmptyComponent:k.injection,EventPluginHub:h.injection,EventEmitter:l.injection,NativeComponent:m.injection,Perf:n.injection,RootIndex:o.injection,Updates:p.injection};e.exports=q;},null);
__d("shallowEqual",[],function(a,b,c,d,e,f){"use strict";function g(h,i){if(h===i)return true;var j;for(j in h)if(h.hasOwnProperty(j)&&(!i.hasOwnProperty(j)||h[j]!==i[j]))return false;for(j in i)if(i.hasOwnProperty(j)&&!h.hasOwnProperty(j))return false;return true;}e.exports=g;},null);
__d("SelectEventPlugin",["EventConstants","EventPropagators","ReactInputSelection","SyntheticEvent","getActiveElement","isTextInputElement","keyOf","shallowEqual"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){"use strict";var o=g.topLevelTypes,p={select:{phasedRegistrationNames:{bubbled:m({onSelect:null}),captured:m({onSelectCapture:null})},dependencies:[o.topBlur,o.topContextMenu,o.topFocus,o.topKeyDown,o.topMouseDown,o.topMouseUp,o.topSelectionChange]}},q=null,r=null,s=null,t=false;function u(x){if('selectionStart' in x&&i.hasSelectionCapabilities(x)){return {start:x.selectionStart,end:x.selectionEnd};}else if(window.getSelection){var y=window.getSelection();return {anchorNode:y.anchorNode,anchorOffset:y.anchorOffset,focusNode:y.focusNode,focusOffset:y.focusOffset};}else if(document.selection){var z=document.selection.createRange();return {parentElement:z.parentElement(),text:z.text,top:z.boundingTop,left:z.boundingLeft};}}function v(x){if(t||q==null||q!=k())return;var y=u(q);if(!s||!n(s,y)){s=y;var z=j.getPooled(p.select,r,x);z.type='select';z.target=q;h.accumulateTwoPhaseDispatches(z);return z;}}var w={eventTypes:p,extractEvents:function(x,y,z,aa){switch(x){case o.topFocus:if(l(y)||y.contentEditable==='true'){q=y;r=z;s=null;}break;case o.topBlur:q=null;r=null;s=null;break;case o.topMouseDown:t=true;break;case o.topContextMenu:case o.topMouseUp:t=false;return v(aa);case o.topSelectionChange:case o.topKeyDown:case o.topKeyUp:return v(aa);}}};e.exports=w;},null);
__d("ServerReactRootIndex",[],function(a,b,c,d,e,f){"use strict";var g=Math.pow(2,53),h={createReactRootIndex:function(){return Math.ceil(Math.random()*g);}};e.exports=h;},null);
__d("SyntheticClipboardEvent",["SyntheticEvent"],function(a,b,c,d,e,f,g){"use strict";var h={clipboardData:function(event){return ('clipboardData' in event?event.clipboardData:window.clipboardData);}};function i(j,k,l){g.call(this,j,k,l);}g.augmentClass(i,h);e.exports=i;},null);
__d("SyntheticFocusEvent",["SyntheticUIEvent"],function(a,b,c,d,e,f,g){"use strict";var h={relatedTarget:null};function i(j,k,l){g.call(this,j,k,l);}g.augmentClass(i,h);e.exports=i;},null);
__d("getEventCharCode",[],function(a,b,c,d,e,f){"use strict";function g(h){var i,j=h.keyCode;if('charCode' in h){i=h.charCode;if(i===0&&j===13)i=13;}else i=j;if(i>=32||i===13)return i;return 0;}e.exports=g;},null);
__d("getEventKey",["getEventCharCode"],function(a,b,c,d,e,f,g){"use strict";var h={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'};function j(k){if(k.key){var l=h[k.key]||k.key;if(l!=='Unidentified')return l;}if(k.type==='keypress'){var m=g(k);return m===13?'Enter':String.fromCharCode(m);}if(k.type==='keydown'||k.type==='keyup')return i[k.keyCode]||'Unidentified';return '';}e.exports=j;},null);
__d("SyntheticKeyboardEvent",["SyntheticUIEvent","getEventCharCode","getEventKey","getEventModifierState"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k={key:i,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:j,charCode:function(event){if(event.type==='keypress')return h(event);return 0;},keyCode:function(event){if(event.type==='keydown'||event.type==='keyup')return event.keyCode;return 0;},which:function(event){if(event.type==='keypress')return h(event);if(event.type==='keydown'||event.type==='keyup')return event.keyCode;return 0;}};function l(m,n,o){g.call(this,m,n,o);}g.augmentClass(l,k);e.exports=l;},null);
__d("SyntheticDragEvent",["SyntheticMouseEvent"],function(a,b,c,d,e,f,g){"use strict";var h={dataTransfer:null};function i(j,k,l){g.call(this,j,k,l);}g.augmentClass(i,h);e.exports=i;},null);
__d("SyntheticTouchEvent",["SyntheticUIEvent","getEventModifierState"],function(a,b,c,d,e,f,g,h){"use strict";var i={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:h};function j(k,l,m){g.call(this,k,l,m);}g.augmentClass(j,i);e.exports=j;},null);
__d("SyntheticWheelEvent",["SyntheticMouseEvent"],function(a,b,c,d,e,f,g){"use strict";var h={deltaX:function(event){return ('deltaX' in event?event.deltaX:'wheelDeltaX' in event?-event.wheelDeltaX:0);},deltaY:function(event){return ('deltaY' in event?event.deltaY:'wheelDeltaY' in event?-event.wheelDeltaY:'wheelDelta' in event?-event.wheelDelta:0);},deltaZ:null,deltaMode:null};function i(j,k,l){g.call(this,j,k,l);}g.augmentClass(i,h);e.exports=i;},null);
__d("SimpleEventPlugin",["EventConstants","EventPluginUtils","EventPropagators","SyntheticClipboardEvent","SyntheticEvent","SyntheticFocusEvent","SyntheticKeyboardEvent","SyntheticMouseEvent","SyntheticDragEvent","SyntheticTouchEvent","SyntheticUIEvent","SyntheticWheelEvent","getEventCharCode","invariant","keyOf","warning"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){"use strict";var w=g.topLevelTypes,x={blur:{phasedRegistrationNames:{bubbled:u({onBlur:true}),captured:u({onBlurCapture:true})}},click:{phasedRegistrationNames:{bubbled:u({onClick:true}),captured:u({onClickCapture:true})}},contextMenu:{phasedRegistrationNames:{bubbled:u({onContextMenu:true}),captured:u({onContextMenuCapture:true})}},copy:{phasedRegistrationNames:{bubbled:u({onCopy:true}),captured:u({onCopyCapture:true})}},cut:{phasedRegistrationNames:{bubbled:u({onCut:true}),captured:u({onCutCapture:true})}},doubleClick:{phasedRegistrationNames:{bubbled:u({onDoubleClick:true}),captured:u({onDoubleClickCapture:true})}},drag:{phasedRegistrationNames:{bubbled:u({onDrag:true}),captured:u({onDragCapture:true})}},dragEnd:{phasedRegistrationNames:{bubbled:u({onDragEnd:true}),captured:u({onDragEndCapture:true})}},dragEnter:{phasedRegistrationNames:{bubbled:u({onDragEnter:true}),captured:u({onDragEnterCapture:true})}},dragExit:{phasedRegistrationNames:{bubbled:u({onDragExit:true}),captured:u({onDragExitCapture:true})}},dragLeave:{phasedRegistrationNames:{bubbled:u({onDragLeave:true}),captured:u({onDragLeaveCapture:true})}},dragOver:{phasedRegistrationNames:{bubbled:u({onDragOver:true}),captured:u({onDragOverCapture:true})}},dragStart:{phasedRegistrationNames:{bubbled:u({onDragStart:true}),captured:u({onDragStartCapture:true})}},drop:{phasedRegistrationNames:{bubbled:u({onDrop:true}),captured:u({onDropCapture:true})}},focus:{phasedRegistrationNames:{bubbled:u({onFocus:true}),captured:u({onFocusCapture:true})}},input:{phasedRegistrationNames:{bubbled:u({onInput:true}),captured:u({onInputCapture:true})}},keyDown:{phasedRegistrationNames:{bubbled:u({onKeyDown:true}),captured:u({onKeyDownCapture:true})}},keyPress:{phasedRegistrationNames:{bubbled:u({onKeyPress:true}),captured:u({onKeyPressCapture:true})}},keyUp:{phasedRegistrationNames:{bubbled:u({onKeyUp:true}),captured:u({onKeyUpCapture:true})}},load:{phasedRegistrationNames:{bubbled:u({onLoad:true}),captured:u({onLoadCapture:true})}},error:{phasedRegistrationNames:{bubbled:u({onError:true}),captured:u({onErrorCapture:true})}},mouseDown:{phasedRegistrationNames:{bubbled:u({onMouseDown:true}),captured:u({onMouseDownCapture:true})}},mouseMove:{phasedRegistrationNames:{bubbled:u({onMouseMove:true}),captured:u({onMouseMoveCapture:true})}},mouseOut:{phasedRegistrationNames:{bubbled:u({onMouseOut:true}),captured:u({onMouseOutCapture:true})}},mouseOver:{phasedRegistrationNames:{bubbled:u({onMouseOver:true}),captured:u({onMouseOverCapture:true})}},mouseUp:{phasedRegistrationNames:{bubbled:u({onMouseUp:true}),captured:u({onMouseUpCapture:true})}},paste:{phasedRegistrationNames:{bubbled:u({onPaste:true}),captured:u({onPasteCapture:true})}},reset:{phasedRegistrationNames:{bubbled:u({onReset:true}),captured:u({onResetCapture:true})}},scroll:{phasedRegistrationNames:{bubbled:u({onScroll:true}),captured:u({onScrollCapture:true})}},submit:{phasedRegistrationNames:{bubbled:u({onSubmit:true}),captured:u({onSubmitCapture:true})}},touchCancel:{phasedRegistrationNames:{bubbled:u({onTouchCancel:true}),captured:u({onTouchCancelCapture:true})}},touchEnd:{phasedRegistrationNames:{bubbled:u({onTouchEnd:true}),captured:u({onTouchEndCapture:true})}},touchMove:{phasedRegistrationNames:{bubbled:u({onTouchMove:true}),captured:u({onTouchMoveCapture:true})}},touchStart:{phasedRegistrationNames:{bubbled:u({onTouchStart:true}),captured:u({onTouchStartCapture:true})}},wheel:{phasedRegistrationNames:{bubbled:u({onWheel:true}),captured:u({onWheelCapture:true})}}},y={topBlur:x.blur,topClick:x.click,topContextMenu:x.contextMenu,topCopy:x.copy,topCut:x.cut,topDoubleClick:x.doubleClick,topDrag:x.drag,topDragEnd:x.dragEnd,topDragEnter:x.dragEnter,topDragExit:x.dragExit,topDragLeave:x.dragLeave,topDragOver:x.dragOver,topDragStart:x.dragStart,topDrop:x.drop,topError:x.error,topFocus:x.focus,topInput:x.input,topKeyDown:x.keyDown,topKeyPress:x.keyPress,topKeyUp:x.keyUp,topLoad:x.load,topMouseDown:x.mouseDown,topMouseMove:x.mouseMove,topMouseOut:x.mouseOut,topMouseOver:x.mouseOver,topMouseUp:x.mouseUp,topPaste:x.paste,topReset:x.reset,topScroll:x.scroll,topSubmit:x.submit,topTouchCancel:x.touchCancel,topTouchEnd:x.touchEnd,topTouchMove:x.touchMove,topTouchStart:x.touchStart,topWheel:x.wheel};for(var z in y)y[z].dependencies=[z];var aa={eventTypes:x,executeDispatch:function(event,ba,ca){var da=h.executeDispatch(event,ba,ca);v(typeof da!=='boolean','Returning `false` from an event handler is deprecated and will be '+'ignored in a future release. Instead, manually call '+'e.stopPropagation() or e.preventDefault(), as appropriate.');if(da===false){event.stopPropagation();event.preventDefault();}},extractEvents:function(ba,ca,da,ea){var fa=y[ba];if(!fa)return null;var ga;switch(ba){case w.topInput:case w.topLoad:case w.topError:case w.topReset:case w.topSubmit:ga=k;break;case w.topKeyPress:if(s(ea)===0)return null;case w.topKeyDown:case w.topKeyUp:ga=m;break;case w.topBlur:case w.topFocus:ga=l;break;case w.topClick:if(ea.button===2)return null;case w.topContextMenu:case w.topDoubleClick:case w.topMouseDown:case w.topMouseMove:case w.topMouseOut:case w.topMouseOver:case w.topMouseUp:ga=n;break;case w.topDrag:case w.topDragEnd:case w.topDragEnter:case w.topDragExit:case w.topDragLeave:case w.topDragOver:case w.topDragStart:case w.topDrop:ga=o;break;case w.topTouchCancel:case w.topTouchEnd:case w.topTouchMove:case w.topTouchStart:ga=p;break;case w.topScroll:ga=q;break;case w.topWheel:ga=r;break;case w.topCopy:case w.topCut:case w.topPaste:ga=j;break;}t(ga);var event=ga.getPooled(fa,da,ea);i.accumulateTwoPhaseDispatches(event);return event;}};e.exports=aa;},null);
__d("SVGDOMPropertyConfig",["DOMProperty"],function(a,b,c,d,e,f,g){"use strict";var h=g.injection.MUST_USE_ATTRIBUTE,i={Properties:{cx:h,cy:h,d:h,dx:h,dy:h,fill:h,fillOpacity:h,fontFamily:h,fontSize:h,fx:h,fy:h,gradientTransform:h,gradientUnits:h,markerEnd:h,markerMid:h,markerStart:h,offset:h,opacity:h,patternContentUnits:h,patternUnits:h,points:h,preserveAspectRatio:h,r:h,rx:h,ry:h,spreadMethod:h,stopColor:h,stopOpacity:h,stroke:h,strokeDasharray:h,strokeLinecap:h,strokeOpacity:h,strokeWidth:h,textAnchor:h,transform:h,version:h,viewBox:h,x1:h,x2:h,x:h,y1:h,y2:h,y:h},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'}};e.exports=i;},null);
__d("createFullPageComponent",["ReactClass","ReactElement","invariant"],function(a,b,c,d,e,f,g,h,i){"use strict";function j(k){var l=h.createFactory(k),m=g.createClass({displayName:'ReactFullPageComponent'+k,componentWillUnmount:function(){i(false);},render:function(){return l(this.props);}});return m;}e.exports=j;},null);
__d("ReactDefaultPerfAnalysis",["Object.assign"],function(a,b,c,d,e,f,g){var h=1.2,i={mountImageIntoNode:'set innerHTML',INSERT_MARKUP:'set innerHTML',MOVE_EXISTING:'move',REMOVE_NODE:'remove',TEXT_CONTENT:'set textContent',updatePropertyByID:'update attribute',deletePropertyByID:'delete attribute',updateStylesByID:'update styles',updateInnerHTMLByID:'set innerHTML',dangerouslyReplaceNodeWithMarkupByID:'replace'};function j(p){var q=0;for(var r=0;r<p.length;r++){var s=p[r];q+=s.totalTime;}return q;}function k(p){var q=[];for(var r=0;r<p.length;r++){var s=p[r],t;for(t in s.writes)s.writes[t].forEach(function(u){q.push({id:t,type:i[u.type]||u.type,args:u.args});});}return q;}function l(p){var q={},r;for(var s=0;s<p.length;s++){var t=p[s],u=g({},t.exclusive,t.inclusive);for(var v in u){r=t.displayNames[v].current;q[r]=q[r]||{componentName:r,inclusive:0,exclusive:0,render:0,count:0};if(t.render[v])q[r].render+=t.render[v];if(t.exclusive[v])q[r].exclusive+=t.exclusive[v];if(t.inclusive[v])q[r].inclusive+=t.inclusive[v];if(t.counts[v])q[r].count+=t.counts[v];}}var w=[];for(r in q)if(q[r].exclusive>=h)w.push(q[r]);w.sort(function(x,y){return y.exclusive-x.exclusive;});return w;}function m(p,q){var r={},s;for(var t=0;t<p.length;t++){var u=p[t],v=g({},u.exclusive,u.inclusive),w;if(q)w=n(u);for(var x in v){if(q&&!w[x])continue;var y=u.displayNames[x];s=y.owner+' > '+y.current;r[s]=r[s]||{componentName:s,time:0,count:0};if(u.inclusive[x])r[s].time+=u.inclusive[x];if(u.counts[x])r[s].count+=u.counts[x];}}var z=[];for(s in r)if(r[s].time>=h)z.push(r[s]);z.sort(function(aa,ba){return ba.time-aa.time;});return z;}function n(p){var q={},r=Object.keys(p.writes),s=g({},p.exclusive,p.inclusive);for(var t in s){var u=false;for(var v=0;v<r.length;v++)if(r[v].indexOf(t)===0){u=true;break;}if(!u&&p.counts[t]>0)q[t]=true;}return q;}var o={getExclusiveSummary:l,getInclusiveSummary:m,getDOMSummary:k,getTotalTime:j};e.exports=o;},null);
__d("performanceNow",["performance"],function(a,b,c,d,e,f,g){var h=g;if(!h||!h.now)h=Date;var i=h.now.bind(h);e.exports=i;},null);
__d("ReactDefaultPerf",["DOMProperty","ReactDefaultPerfAnalysis","ReactMount","ReactPerf","performanceNow"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";function l(o){return Math.floor(o*100)/100;}function m(o,p,q){o[p]=(o[p]||0)+q;}var n={_allMeasurements:[],_mountStack:[0],_injected:false,start:function(){if(!n._injected)j.injection.injectMeasure(n.measure);n._allMeasurements.length=0;j.enableMeasure=true;},stop:function(){j.enableMeasure=false;},getLastMeasurements:function(){return n._allMeasurements;},printExclusive:function(o){o=o||n._allMeasurements;var p=h.getExclusiveSummary(o);console.table(p.map(function(q){return {'Component class name':q.componentName,'Total inclusive time (ms)':l(q.inclusive),'Exclusive mount time (ms)':l(q.exclusive),'Exclusive render time (ms)':l(q.render),'Mount time per instance (ms)':l(q.exclusive/q.count),'Render time per instance (ms)':l(q.render/q.count),Instances:q.count};}));},printInclusive:function(o){o=o||n._allMeasurements;var p=h.getInclusiveSummary(o);console.table(p.map(function(q){return {'Owner > component':q.componentName,'Inclusive time (ms)':l(q.time),Instances:q.count};}));},getMeasurementsSummaryMap:function(o){var p=h.getInclusiveSummary(o,true);return p.map(function(q){return {'Owner > component':q.componentName,'Wasted time (ms)':q.time,Instances:q.count};});},printWasted:function(o){o=o||n._allMeasurements;console.table(n.getMeasurementsSummaryMap(o));},printDOM:function(o){o=o||n._allMeasurements;var p=h.getDOMSummary(o);console.table(p.map(function(q){var r={};r[g.ID_ATTRIBUTE_NAME]=q.id;r.type=q.type;r.args=JSON.stringify(q.args);return r;}));},_recordWrite:function(o,p,q,r){var s=n._allMeasurements[n._allMeasurements.length-1].writes;s[o]=s[o]||[];s[o].push({type:p,time:q,args:r});},measure:function(o,p,q){return function(){for(var r=[],s=0,t=arguments.length;s<t;s++)r.push(arguments[s]);var u,v,w;if(p==='_renderNewRootComponent'||p==='flushBatchedUpdates'){n._allMeasurements.push({exclusive:{},inclusive:{},render:{},counts:{},writes:{},displayNames:{},totalTime:0});w=k();v=q.apply(this,r);n._allMeasurements[n._allMeasurements.length-1].totalTime=k()-w;return v;}else if(o==='ReactDOMIDOperations'||o==='ReactComponentBrowserEnvironment'){w=k();v=q.apply(this,r);u=k()-w;if(p==='mountImageIntoNode'){var x=i.getID(r[1]);n._recordWrite(x,p,u,r[0]);}else if(p==='dangerouslyProcessChildrenUpdates'){r[0].forEach(function(ea){var fa={};if(ea.fromIndex!==null)fa.fromIndex=ea.fromIndex;if(ea.toIndex!==null)fa.toIndex=ea.toIndex;if(ea.textContent!==null)fa.textContent=ea.textContent;if(ea.markupIndex!==null)fa.markup=r[1][ea.markupIndex];n._recordWrite(ea.parentID,ea.type,u,fa);});}else n._recordWrite(r[0],p,u,Array.prototype.slice.call(r,1));return v;}else if(o==='ReactCompositeComponent'&&(p==='mountComponent'||p==='updateComponent'||p==='_renderValidatedComponent')){var y=p==='mountComponent'?r[0]:this._rootNodeID,z=p==='_renderValidatedComponent',aa=p==='mountComponent',ba=n._mountStack,ca=n._allMeasurements[n._allMeasurements.length-1];if(z){m(ca.counts,y,1);}else if(aa)ba.push(0);w=k();v=q.apply(this,r);u=k()-w;if(z){m(ca.render,y,u);}else if(aa){var da=ba.pop();ba[ba.length-1]+=u;m(ca.exclusive,y,u-da);m(ca.inclusive,y,u);}else m(ca.inclusive,y,u);ca.displayNames[y]={current:this.constructor.displayName,owner:this._owner?this._owner.constructor.displayName:'<root>'};return v;}else return q.apply(this,r);};}};e.exports=n;},null);
__d("ReactDefaultInjection",["BeforeInputEventPlugin","ChangeEventPlugin","ClientReactRootIndex","CompositionEventPlugin","DefaultEventPluginOrder","EnterLeaveEventPlugin","ExecutionEnvironment","HTMLDOMPropertyConfig","MobileSafariClickEventPlugin","ReactBrowserComponentMixin","ReactComponentBrowserEnvironment","ReactDefaultBatchingStrategy","ReactDOMComponent","ReactDOMButton","ReactDOMForm","ReactDOMImg","ReactDOMInput","ReactDOMOption","ReactDOMSelect","ReactDOMTextarea","ReactEventListener","ReactInjection","ReactInstanceHandles","ReactMount","SelectEventPlugin","ServerReactRootIndex","SimpleEventPlugin","SVGDOMPropertyConfig","createFullPageComponent","ReactDefaultPerf"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ba,ca,da,ea,fa,ga,ha,ia){"use strict";function ja(){ba.EventEmitter.injectReactEventListener(aa);ba.EventPluginHub.injectEventPluginOrder(k);ba.EventPluginHub.injectInstanceHandle(ca);ba.EventPluginHub.injectMount(da);ba.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:ga,EnterLeaveEventPlugin:l,ChangeEventPlugin:h,CompositionEventPlugin:j,MobileSafariClickEventPlugin:o,SelectEventPlugin:ea,BeforeInputEventPlugin:g});ba.NativeComponent.injectGenericComponentClass(s);ba.NativeComponent.injectComponentClasses({button:t,form:u,img:v,input:w,option:x,select:y,textarea:z,html:ia('html'),head:ia('head'),body:ia('body')});ba.Class.injectMixin(p);ba.DOMProperty.injectDOMPropertyConfig(n);ba.DOMProperty.injectDOMPropertyConfig(ha);ba.EmptyComponent.injectEmptyComponent('noscript');ba.Updates.injectReconcileTransaction(q.ReactReconcileTransaction);ba.Updates.injectBatchingStrategy(r);ba.RootIndex.injectCreateReactRootIndex(m.canUseDOM?i.createReactRootIndex:fa.createReactRootIndex);ba.Component.injectEnvironment(q);}e.exports={inject:ja};},null);
__d("ReactServerRenderingTransaction",["PooledClass","CallbackQueue","ReactPutListenerQueue","Transaction","Object.assign","emptyFunction"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";var m={initialize:function(){this.reactMountReady.reset();},close:l},n={initialize:function(){this.putListenerQueue.reset();},close:l},o=[n,m];function p(r){this.reinitializeTransaction();this.renderToStaticMarkup=r;this.reactMountReady=h.getPooled(null);this.putListenerQueue=i.getPooled();}var q={getTransactionWrappers:function(){return o;},getReactMountReady:function(){return this.reactMountReady;},getPutListenerQueue:function(){return this.putListenerQueue;},destructor:function(){h.release(this.reactMountReady);this.reactMountReady=null;i.release(this.putListenerQueue);this.putListenerQueue=null;}};k(p.prototype,j.Mixin,q);g.addPoolingTo(p);e.exports=p;},null);
__d("ReactServerRendering",["ReactElement","ReactInstanceHandles","ReactMarkupChecksum","ReactServerRenderingTransaction","instantiateReactComponent","invariant"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";function m(o){l(g.isValidElement(o));var p;try{var q=h.createReactRootID();p=j.getPooled(false);return p.perform(function(){var r=k(o,null),s=r.mountComponent(q,p,0);return i.addChecksumToMarkup(s);},null);}finally{j.release(p);}}function n(o){l(g.isValidElement(o));var p;try{var q=h.createReactRootID();p=j.getPooled(true);return p.perform(function(){var r=k(o,null);return r.mountComponent(q,p,0);},null);}finally{j.release(p);}}e.exports={renderToString:m,renderToStaticMarkup:n};},null);
__d("onlyChild",["ReactElement","invariant"],function(a,b,c,d,e,f,g,h){"use strict";function i(j){h(g.isValidElement(j));return j;}e.exports=i;},null);
__d("React",["DOMPropertyOperations","EventPluginUtils","ReactChildren","ReactComponent","ReactClass","ReactContext","ReactCurrentOwner","ReactElement","ReactElementValidator","ReactDOM","ReactDOMComponent","ReactDefaultInjection","ReactInstanceHandles","ReactMount","ReactMultiChild","ReactPerf","ReactPropTypes","ReactServerRendering","ReactTextComponent","Object.assign","deprecated","onlyChild","ExecutionEnvironment"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ba){"use strict";r.inject();var ca=n.createElement,da=n.createFactory,ea=v.measure('React','render',t.render),fa={Children:{map:i.map,forEach:i.forEach,count:i.count,only:ba},DOM:p,PropTypes:w,initializeTouchEvents:function(ga){h.useTouchEvents=ga;},createClass:k.createClass,createElement:ca,createFactory:da,constructAndRenderComponent:t.constructAndRenderComponent,constructAndRenderComponentByID:t.constructAndRenderComponentByID,render:ea,renderToString:x.renderToString,renderToStaticMarkup:x.renderToStaticMarkup,unmountComponentAtNode:t.unmountComponentAtNode,isValidElement:n.isValidElement,withContext:l.withContext,__spread:z,renderComponent:aa('React','renderComponent','render',this,ea),renderComponentToString:aa('React','renderComponentToString','renderToString',this,x.renderToString),renderComponentToStaticMarkup:aa('React','renderComponentToStaticMarkup','renderToStaticMarkup',this,x.renderToStaticMarkup),isValidComponent:aa('React','isValidComponent','isValidElement',this,n.isValidElement)};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__!=='undefined'&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject==='function')__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({Component:j,CurrentOwner:m,DOMComponent:q,DOMPropertyOperations:g,InstanceHandles:s,Mount:t,MultiChild:u,TextComponent:y});fa.version='0.13.0-alpha';e.exports=fa;},null);
__d("PhotoResizeMath",[],function(a,b,c,d,e,f){var g={getScaledPhotoDimensions:function(h,i,j,k,l){var m=h/i,n=j/k;if(j&&k&&l==='stretch')return {width:j,height:k};if((!j&&k)||((l==='contain')!==(m>=n)))return {width:k*m,height:k};if(j)return {width:j,height:j/m};return {width:h,height:i};}};e.exports=g;},null);
__d("PixelzFocus",[],function(a,b,c,d,e,f){"use strict";var g={search:function(h,i){var j=0,k=h.length-1;while(j<=k){var l=j+Math.floor((k-j)/2),m=h[l];if(m>i){k=l-1;}else if(m<i){j=l+1;}else return l;}return Math.min(j,k);},forceSpecificPoint:function(h,i,j){var k=1e-09,l=g.search(h,i-j-k)+1,m=g.search(h,i+j);return h.slice(l,m+1);},findBiggestSets:function(h,i){var j=[],k=-1;for(var l=0;l<h.length;++l){var m=h[l],n=l,o=g.search(h,m+i),p=o-n;if(p>k)j=[];if(p>=k){k=p;j.push({low:n,high:o});}}return j;},getBestSet:function(h,i,j){var k=-1,l=null;for(var m=0;m<i.length;++m){var n=i[m],o=h[n.low],p=h[n.high],q=o+(p-o)/2,r=Math.min(o-(q-j),(q+j)-p);if(r>k){k=r;l=n;}}return l;},getFocusFromSet:function(h,i){var j=h[i.low],k=h[i.high];return j+(k-j)/2;},clampFocus:function(h,i){var j=i/2,k=1-(i/2);if(h<j)return j;if(h>k)return k;return h;},convertFromCenterToCSS:function(h,i){if(Math.abs(1-i)<1e-05)return 0;return (h-i/2)/(1-i);},convertFromCSSToCenter:function(h,i){return h*(1-i)+i/2;},getVisible:function(h,i){if(h<i)return h/i;return i/h;},getHidden:function(h,i){return 1-g.getVisible(h,i);},focusHorizontally:function(h,i){return h<i;},convertVectorFromCenterToCSS:function(h,i,j){var k=g.focusHorizontally(i,j),l;if(k){l=h.x/100;}else l=h.x/100;var m=g.convertFromCenterToCSS(l,g.getVisible(i,j));if(k){return {x:m,y:0};}else return {x:0,y:m};},getCropRect:function(h,i,j){var k=g.focusHorizontally(i,j),l=g.getVisible(i,j);if(k){var m=(1-l)*h.x;return {left:m,top:0,width:l,height:1};}else{var n=(1-l)*h.y;return {left:0,top:n,width:1,height:l};}}};e.exports=g;},null);
__d("Pixelz.react",["arrayContains","copyProperties","cx","loadImage","joinClasses","React","PhotoResizeMath","PixelzFocus"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){"use strict";var o=l.PropTypes,p=l.createClass({displayName:'Pixelz',propTypes:{width:o.number,height:o.number,resizeMode:o.oneOf(['contain','cover','stretch']),alt:o.string,letterbox:o.bool,borderRadius:o.number,insetBorderColor:o.string,animated:o.bool,upscale:o.bool,cropRect:function(q,r,s){var t=q[r],u='Invalid prop `'+r+'` supplied to `'+s+'`, expected a rectangle with values normalized '+'between 0 and 1.';if(t.left<0||t.top<0||t.width<0||t.height<0||t.left+t.width>1||t.top+t.height>1)return new Error(u);},focus:function(q,r,s){var t=q[r],u='Invalid prop `'+r+'` supplied to `'+s+'`, expected either a {x, y, type} vector where type '+'is `css` or `center` or an array of {x, y} vectors. All the vectors '+'have with values normalized between 0 and 1.';if(Array.isArray(t)){for(var v=0;v<t.length;++v)if(!(t[v].x>=0&&t[v].x<=1)||!(t[v].y>=0&&t[v].y<=1))return new Error(u);}else{if(!t.type)t.type='css';if(!(t.x>=0&&t.x<=1)||!(t.y>=0&&t.y<=1)||!g(['center','css'],t.type))return new Error(u);}}},getDefaultProps:function(){return {resizeMode:'cover',alt:'',letterbox:true,upscale:true,cropRect:{width:1,height:1,top:0,left:0},focus:{x:.5,y:.5,type:'css'}};},getInitialState:function(){return {srcDimensions:{}};},getSrcDimensions:function(){var q=this.props.src,r=this.state.srcDimensions[q];if(r)return r;j(q,function(s,t){var u={};u[q]={width:s,height:t};this.isMounted()&&this.setState({srcDimensions:u});}.bind(this));return null;},getCropSrcDimensions:function(){var q=this.getSrcDimensions();return {width:q.width*this.props.cropRect.width,height:q.height*this.props.cropRect.height};},getUpscaleCropDimensions:function(){var q=this.getCropSrcDimensions();return m.getScaledPhotoDimensions(q.width,q.height,this.props.width,this.props.height,this.props.resizeMode);},getCropDimensions:function(){var q=this.getUpscaleCropDimensions(),r=this.getCropSrcDimensions();if(!this.props.upscale)return {width:Math.min(q.width,r.width),height:Math.min(q.height,r.height)};return q;},getCropAspectRatio:function(){var q=this.getCropDimensions();return q.width/q.height;},getContainerDimensions:function(){if(this.props.letterbox&&this.props.width&&this.props.height)return {width:this.props.width,height:this.props.height};return this.getCropDimensions();},getContainerAspectRatio:function(){var q=this.getContainerDimensions();return q.width/q.height;},getContainerPosition:function(){return {left:0,top:0};},getFocus:function(){var q=this.props.focus;if(!Array.isArray(q)&&q.type==='css')return {x:q.x,y:q.y};var r=this.getContainerAspectRatio(),s=this.getCropAspectRatio(),t=n.getVisible(r,s),u=n.focusHorizontally(r,s),v;if(!Array.isArray(q)){v=n.convertFromCenterToCSS(u?q.x:q.y,t);}else{var w=q.map(function(z){return u?z.x:z.y;});w.sort();var x=n.findBiggestSets(w,t),y=n.getBestSet(w,x,t);v=n.getFocusFromSet(w,y);}return {x:u?v:.5,y:u?.5:v};},getCropPosition:function(){var q=this.getCropDimensions(),r=this.getContainerDimensions(),s=this.getFocus();return {left:s.x*(r.width-q.width),top:s.y*(r.height-q.height)};},getScaleDimensions:function(){var q=this.getCropDimensions();return {width:q.width/this.props.cropRect.width,height:q.height/this.props.cropRect.height};},getScalePosition:function(){var q=this.getScaleDimensions();return {left:-q.width*this.props.cropRect.left,top:-q.height*this.props.cropRect.top};},getClipCropRectangle:function(){var q=this.getContainerDimensions(),r=this.getCropDimensions(),s=this.getContainerPosition(),t=this.getCropPosition(),u=Math.max(s.left,t.left),v=Math.max(s.top,t.top),w=Math.min(s.top+q.height,t.top+r.height),x=Math.min(s.left+q.width,t.left+r.width);return {left:u,top:v,width:x-u,height:w-v};},getClipCropPosition:function(){var q=this.getClipCropRectangle();return {left:q.left,top:q.top};},getClipCropDimensions:function(){var q=this.getClipCropRectangle();return {width:q.width,height:q.height};},getClipScalePosition:function(){var q=this.getScalePosition(),r=this.getClipCropPosition(),s=this.getCropPosition();return {left:q.left+(s.left-r.left),top:q.top+(s.top-r.top)};},getClipScaleDimensions:function(){return this.getScaleDimensions();},areDimensionsEqual:function(q,r){return q.width===r.width&&q.height===r.height;},shouldAddAllNodesAndStyles:function(){return this.props.animated;},hasCrop:function(){if(this.shouldAddAllNodesAndStyles())return true;var q=this.getContainerDimensions(),r=this.getClipCropDimensions(),s=this.getClipScaleDimensions();if(this.areDimensionsEqual(q,r)||this.areDimensionsEqual(r,s))return false;return true;},hasContainer:function(){if(this.shouldAddAllNodesAndStyles()||this.hasInsetBorder())return true;var q=this.getContainerDimensions(),r=this.getClipScaleDimensions();if(this.areDimensionsEqual(q,r))return false;return true;},hasInsetBorder:function(){return this.shouldAddAllNodesAndStyles()||this.props.insetBorderColor;},applyPositionStyle:function(q,r){if(this.shouldAddAllNodesAndStyles()||r.left)q.left=Math.round(r.left);if(this.shouldAddAllNodesAndStyles()||r.top)q.top=Math.round(r.top);},applyDimensionsStyle:function(q,r){q.width=Math.round(r.width);q.height=Math.round(r.height);},applyBorderRadiusStyle:function(q){if(this.shouldAddAllNodesAndStyles()||this.props.borderRadius)q.borderRadius=this.props.borderRadius||0;},getScaleStyle:function(){var q={},r=this.getClipCropDimensions(),s=this.getClipScaleDimensions();if(this.shouldAddAllNodesAndStyles()||!this.areDimensionsEqual(r,s)){this.applyPositionStyle(q,this.getClipScalePosition());}else this.applyPositionStyle(q,this.getClipCropPosition());this.applyDimensionsStyle(q,this.getClipScaleDimensions());this.applyBorderRadiusStyle(q);return q;},getCropStyle:function(){var q={};this.applyPositionStyle(q,this.getClipCropPosition());this.applyDimensionsStyle(q,this.getClipCropDimensions());this.applyBorderRadiusStyle(q);return q;},getInsetBorderStyle:function(){var q={borderColor:this.props.insetBorderColor||'transparent'};this.applyPositionStyle(q,this.getClipCropPosition());this.applyDimensionsStyle(q,this.getClipCropDimensions());this.applyBorderRadiusStyle(q);return q;},getContainerStyle:function(){var q={};this.applyDimensionsStyle(q,this.getContainerDimensions());this.applyBorderRadiusStyle(q);return q;},getScale:function(){var q=this.getScaleStyle(),r=q.width,s=q.height;q=h({},q);delete q.width;delete q.height;return (l.createElement("img",Object.assign({},this.props,{alt:this.props.alt,className:k(this.props.className,(("_56wb")+(this.shouldAddAllNodesAndStyles()?' '+"_56t5":''))),src:this.props.src,style:Object.assign({},(this.props.style||{}),q),width:r,height:s})));},getCrop:function(){var q=this.getScale();if(!this.hasCrop())return q;return (l.createElement("div",{className:(("_56ma")+(this.shouldAddAllNodesAndStyles()?' '+"_56t5":'')),style:this.getCropStyle()},q));},getInsetBorder:function(){if(!this.hasInsetBorder())return null;return (l.createElement("div",{className:(("_56lv")+(this.shouldAddAllNodesAndStyles()?' '+"_56t5":'')),style:this.getInsetBorderStyle()}));},getContainer:function(){var q=this.getCrop();if(!this.hasContainer())return q;var r=this.getInsetBorder();return (l.createElement("div",{className:(("_56jj")+(this.shouldAddAllNodesAndStyles()?' '+"_56t5":'')),style:this.getContainerStyle()},q,r));},render:function(){var q=this.getSrcDimensions();if(!q)return l.createElement("span",null);return this.getContainer();}});e.exports=p;},null);
__d("Scrollable",["Event","Parent","UserAgent_DEPRECATED"],function(a,b,c,d,e,f,g,h,i){var j=function(event){var m=h.byClass(event.getTarget(),'scrollable');if(!m)return;if((typeof event.axis!=='undefined'&&event.axis===event.HORIZONTAL_AXIS)||(event.wheelDeltaX&&!event.wheelDeltaY)||(event.deltaX&&!event.deltaY))return;var n=event.wheelDelta||-event.deltaY||-event.detail,o=m.scrollHeight,p=m.clientHeight;if(o>p){var q=m.scrollTop;if((n>0&&q===0)||(n<0&&q>=o-p-1)){event.prevent();}else if(i.ie()<9)if(m.currentStyle){var r=m.currentStyle.fontSize;if(r.indexOf('px')<0){var s=document.createElement('div');s.style.fontSize=r;s.style.height='1em';r=s.style.pixelHeight;}else r=parseInt(r,10);m.scrollTop=q-Math.round(n/120*r);event.prevent();}}},k=document.documentElement;if(i.firefox()){var l=('WheelEvent' in window)?'wheel':'DOMMouseScroll';k.addEventListener(l,j,false);}else g.listen(k,'mousewheel',j);},null);
__d("LegacyScrollableArea.react",["Bootloader","React","Style","cx","joinClasses","Scrollable"],function(a,b,c,d,e,f,g,h,i,j,k){b('Scrollable');var l="uiScrollableArea native",m="uiScrollableAreaWrap scrollable",n="uiScrollableAreaBody",o="uiScrollableAreaContent",p=h.createClass({displayName:'ReactLegacyScrollableArea',render:function(){var q={height:this.props.height};return (h.createElement("div",Object.assign({},this.props,{className:k(this.props.className,l),ref:"root",style:Object.assign({},(this.props.style||{}),q)}),h.createElement("div",{className:m,ref:"wrap"},h.createElement("div",{className:n,ref:"body"},h.createElement("div",{className:o},this.props.children)))));},getArea:function(){return this._area;},componentDidMount:function(){g.loadModules(["ScrollableArea"],this._loadScrollableArea);},_loadScrollableArea:function(q){this._area=q.fromNative(this.refs.root.getDOMNode(),{fade:this.props.fade,persistent:this.props.persistent,shadow:this.props.shadow===undefined?true:this.props.shadow});var r=this.refs.body.getDOMNode();i.set(r,'width',this.props.width+'px');this.props.onScroll&&this._area.subscribe('scroll',this.props.onScroll);}});e.exports=p;},null);
__d("flattenArray",[],function(a,b,c,d,e,f){function g(h){var i=h.slice(),j=[];while(i.length){var k=i.pop();if(Array.isArray(k)){Array.prototype.push.apply(i,k);}else j.push(k);}return j.reverse();}e.exports=g;},null);
__d("JSXDOM",["DOM","flattenArray"],function(a,b,c,d,e,f,g,h){var i=['a','blockquote','br','button','canvas','checkbox','dd','div','dl','dt','em','form','h1','h2','h3','h4','h5','h6','hr','i','iframe','img','input','label','li','option','p','pre','select','span','strong','table','tbody','thead','td','textarea','th','tr','ul','video'],j={};i.forEach(function(k){var l=function(m,n){if(arguments.length>2)n=Array.prototype.slice.call(arguments,1);if(!n&&m){n=m.children;delete m.children;}if(n)n=Array.isArray(n)?h(n):h([n]);return g.create(k,m,n);};j[k]=l;});e.exports=j;},null);
__d("TransformTextToDOMMixin",["DOMQuery","createArrayFrom","flattenArray"],function(a,b,c,d,e,f,g,h,i){var j=3,k={transform:function(l,m){return i(l.map(function(n){if(!g.isElementNode(n)){var o=n,p=[],q=this.MAX_ITEMS||j;while(q--){var r=m?[o].concat(m):[o],s=this.match.apply(this,r);if(!s)break;p.push(o.substring(0,s.startIndex));p.push(s.element);o=o.substring(s.endIndex);}o&&p.push(o);return p;}return n;}.bind(this)));},params:function(){var l=this;return {__params:true,obj:l,params:h(arguments)};}};e.exports=k;},null);
__d("Utf16",[],function(a,b,c,d,e,f){var g={decode:function(h){switch(h.length){case 1:return h.charCodeAt(0);case 2:return 65536|((h.charCodeAt(0)-55296)*1024)|(h.charCodeAt(1)-56320);}},encode:function(h){if(h<65536){return String.fromCharCode(h);}else return String.fromCharCode(55296+((h-65536)>>10))+String.fromCharCode(56320+(h%1024));}};e.exports=g;},null);
__d("SupportedEmoji",["cx","Utf16"],function(a,b,c,d,e,f,g,h){var i=new RegExp("([\u203C\u2049\u2100-\u21FF\u2300-\u27FF"+"\u2900-\u29FF\u2B00-\u2BFF\u3000-\u30FF\u3200-\u32FF]|"+"\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDEFF])([\uFE00-\uFE0F])?"),j={126980:"_4_o0",127378:"_4_o1",127385:"_4_o2",127386:"_4_o3",127489:"_4_o4",127490:"_4_o5",127514:"_4_o6",127535:"_4_o7",127539:"_4_o8",127541:"_4_o9",127542:"_4_oa",127543:"_4_ob",127544:"_4_oc",127545:"_4_od",127546:"_4_oe",127568:"_4_of",127744:"_2b_",127746:"_2c0",127747:"_4_og",127748:"_4_oh",127749:"_4_oi",127750:"_4_oj",127751:"_4_ok",127752:"_4_ol",127754:"_2c1",127769:"_2c2",127775:"_2c3",127793:"_2c4",127796:"_2c5",127797:"_2c6",127799:"_2c7",127800:"_2c8",127801:"_2c9",127802:"_2ca",127803:"_2cb",127806:"_2cc",127808:"_2cd",127809:"_2ce",127810:"_2cf",127811:"_2cg",127813:"_4_om",127814:"_4_on",127817:"_4_oo",127818:"_2ch",127822:"_2ci",127827:"_2cj",127828:"_2ck",127832:"_4_op",127833:"_4_oq",127834:"_4_or",127835:"_4_os",127836:"_4_ot",127837:"_4_ou",127838:"_4_ov",127839:"_4_ow",127841:"_4_ox",127842:"_4_oy",127843:"_4_oz",127846:"_4_o-",127847:"_4_o_",127856:"_4_p0",127857:"_4_p1",127858:"_4_p2",127859:"_4_p3",127860:"_4_p4",127861:"_4_p5",127862:"_4_p6",127864:"_2cl",127866:"_2cm",127867:"_4_p7",127872:"_4_p8",127873:"_2cn",127875:"_2co",127876:"_2cp",127877:"_2cq",127880:"_2cr",127881:"_2cs",127884:"_4_p9",127885:"_2ct",127886:"_2cu",127887:"_2cv",127888:"_2cw",127890:"_4_pa",127891:"_2cx",127905:"_4_pb",127906:"_4_pc",127908:"_4_pd",127909:"_4_pe",127910:"_4_pf",127911:"_4_pg",127912:"_4_ph",127913:"_4_pi",127915:"_4_pj",127916:"_4_pk",127917:"_4_pl",127919:"_4_pm",127921:"_4_pn",127925:"_2cy",127926:"_2cz",127927:"_4_po",127928:"_4_pp",127930:"_4_pq",127932:"_2c-",127934:"_4_pr",127935:"_4_ps",127936:"_4_pt",127937:"_4_pu",127942:"_4_pv",127944:"_4_pw",127968:"_4_px",127969:"_4_py",127970:"_4_pz",127971:"_4_p-",127973:"_4_p_",127974:"_4_q0",127975:"_4_q1",127976:"_4_q2",127977:"_4_q3",127978:"_4_q4",127979:"_4_q5",127980:"_4_q6",127981:"_4_q7",127983:"_4_q8",127984:"_4_q9",128013:"_2c_",128014:"_2d0",128017:"_2d1",128018:"_2d2",128020:"_2d3",128023:"_2d4",128024:"_2d5",128025:"_2d6",128026:"_2d7",128027:"_2d8",128031:"_2d9",128032:"_2da",128033:"_2db",128037:"_2dc",128038:"_2dd",128039:"_2de",128040:"_2df",128041:"_2dg",128043:"_2dh",128044:"_2di",128045:"_2dj",128046:"_2dk",128047:"_2dl",128048:"_2dm",128049:"_2dn",128051:"_2do",128052:"_2dp",128053:"_2dq",128054:"_491",128055:"_2dr",128056:"_2ds",128057:"_2dt",128058:"_2du",128059:"_2dv",128062:"_2dw",128064:"_2dx",128066:"_2dy",128067:"_2dz",128068:"_2d-",128069:"_2d_",128070:"_2e0",128071:"_2e1",128072:"_2e2",128073:"_2e3",128074:"_2e4",128075:"_2e5",128076:"_2e6",128077:"_2e7",128078:"_2e8",128079:"_2e9",128080:"_2ea",128081:"_4_qa",128082:"_4_qb",128084:"_4_qc",128085:"_4_qd",128087:"_4_qe",128088:"_4_qf",128089:"_4_qg",128092:"_4_qh",128095:"_4_qi",128096:"_4_qj",128097:"_4_qk",128098:"_4_ql",128102:"_2eb",128103:"_2ec",128104:"_2ed",128105:"_2ee",128107:"_2ef",128110:"_2eg",128111:"_2eh",128113:"_2ei",128114:"_2ej",128115:"_2ek",128116:"_2el",128117:"_2em",128118:"_2en",128119:"_2eo",128120:"_2ep",128123:"_2eq",128124:"_2er",128125:"_2es",128126:"_2et",128127:"_2eu",128128:"_2ev",128130:"_2ew",128131:"_2ex",128132:"_4_qm",128133:"_2ey",128136:"_4_qn",128137:"_4_qo",128138:"_4_qp",128139:"_2ez",128140:"_4_qq",128141:"_4_qr",128142:"_4_qs",128143:"_2e-",128144:"_2e_",128145:"_2f0",128146:"_4_qt",128147:"_2f1",128148:"_2f2",128150:"_2f3",128151:"_2f4",128152:"_2f5",128153:"_2f6",128154:"_2f7",128155:"_2f8",128156:"_2f9",128157:"_2fa",128158:"_4_qu",128159:"_4_qv",128160:"_4_qw",128161:"_4_qx",128162:"_2fb",128163:"_4_qy",128164:"_2fc",128166:"_2fd",128167:"_4_qz",128168:"_2fe",128169:"_2ff",128170:"_2fg",128176:"_4_q-",128178:"_4_q_",128180:"_4_r0",128181:"_4_r1",128186:"_4_r2",128187:"_2fh",128188:"_4_r3",128189:"_2fi",128190:"_2fj",128191:"_2fk",128192:"_2fl",128214:"_4_r4",128221:"_4_r5",128222:"_2fm",128224:"_2fn",128225:"_4_r6",128226:"_4_r7",128227:"_4_r8",128232:"_4_r9",128233:"_4_ra",128234:"_4_rb",128235:"_4_rc",128236:"_4_rd",128237:"_4_re",128238:"_4_rf",128241:"_2fo",128242:"_2fp",128243:"_4_rg",128244:"_4_rh",128246:"_4_ri",128247:"_4_rj",128250:"_2fq",128251:"_4_rk",128252:"_4_rl",128264:"_4_rm",128269:"_4_rn",128270:"_4_ro",128271:"_4_rp",128272:"_4_rq",128273:"_4_rr",128274:"_4_rs",128275:"_4_rt",128276:"_2fr",128286:"_4_ru",128293:"_492",128296:"_4_rv",128299:"_4_rw",128304:"_4_rx",128305:"_4_ry",128306:"_4_rz",128307:"_4_r-",128308:"_4_r_",128309:"_4_s0",128310:"_4_s1",128311:"_4_s2",128312:"_4_s3",128313:"_4_s4",128507:"_4_s5",128508:"_4_s6",128509:"_4_s7",128513:"_2fs",128514:"_2ft",128515:"_2fu",128516:"_2fv",128518:"_2fw",128521:"_2fx",128522:"_1q3y",128524:"_2fz",128525:"_2f-",128527:"_2f_",128530:"_2g0",128531:"_2g1",128532:"_2g2",128534:"_2g3",128536:"_2g4",128538:"_2g5",128540:"_2g6",128541:"_2g7",128542:"_2g8",128544:"_2g9",128545:"_2ga",128546:"_2gb",128547:"_2gc",128548:"_2gd",128549:"_2ge",128552:"_2gf",128553:"_2gg",128554:"_2gh",128555:"_2gi",128557:"_2gj",128560:"_2gk",128561:"_2gl",128562:"_2gm",128563:"_2gn",128565:"_2go",128567:"_2gp",128568:"_2gq",128569:"_2gr",128570:"_2gs",128571:"_2gt",128572:"_2gu",128573:"_2gv",128575:"_2gw",128576:"_2gx",128587:"_2gy",128588:"_2gz",128589:"_2g-",128591:"_2g_",128640:"_4_s8",128643:"_4_s9",128644:"_4_sa",128645:"_4_sb",128649:"_4_sc",128652:"_4_sd",128655:"_4_se",128657:"_4_sf",128658:"_4_sg",128659:"_4_sh",128661:"_4_si",128663:"_4_sj",128665:"_4_sk",128666:"_4_sl",128674:"_4_sm",128676:"_4_sn",128677:"_4_so",128679:"_4_sp",128684:"_4_sq",128685:"_4_sr",128690:"_4_ss",128697:"_4_st",128698:"_4_su",128699:"_4_sv",128700:"_4_sw",128701:"_4_sx",128702:"_4_sy",128704:"_4_sz",9642:"_4_s-",9643:"_4_s_",9723:"_4_t0",9724:"_4_t1",9725:"_4_t2",9726:"_4_t3",9742:"_4_t4",9757:"_2h0",9786:"_2h1",9855:"_4_t5",9888:"_4_t6",9889:"_2h2",9898:"_4_t7",9899:"_4_t8",9917:"_4_t9",9918:"_4_ta",9924:"_2h3",9940:"_4_tb",9962:"_4_tc",9970:"_4_td",9971:"_4_te",9973:"_4_tf",9978:"_4_tg",9981:"_4_th",9994:"_2h4",9995:"_2h5",9996:"_2h6",10060:"_4_ti",10062:"_4_tj",10145:"_4_tk",10175:"_4_tl",11013:"_4_tm",11014:"_4_tn",11015:"_4_to",11035:"_4_tp",11036:"_4_tq",11088:"_4_tr",11093:"_4_ts",12349:"_4_tt",8598:"_4_tu",8599:"_4_tv",8600:"_4_tw",8601:"_4_tx",9728:"_2h7",9729:"_2h8",9748:"_2h9",9749:"_2ha",9824:"_4_ty",9827:"_4_tz",9829:"_4_t-",9830:"_4_t_",9832:"_4_u0",9986:"_4_u1",9992:"_4_u2",9993:"_4_u3",10006:"_4_u4",10024:"_2hb",10035:"_4_u5",10036:"_4_u6",10067:"_4_u7",10068:"_4_u8",10069:"_4_u9",10071:"_4_ua",10084:"_2hc",10548:"_4_ub",10549:"_4_uc",12951:"_4_ud",12953:"_4_ue"},k=function(l){var m=0;while(l.length>0){var n=i.exec(l);if(!n||!n.length)return false;var o=n[1],p=n.index,q=h.decode(o),r=j[q];if(!r){m+=p+1;l=l.substr(p+1);continue;}n.index+=m;n.emoji=r;return n;}return false;};e.exports={findEmoji:k,emoji:j,_utf16Regex:i};},null);
__d("DOMEmoji",["CSS","JSXDOM","TransformTextToDOMMixin","SupportedEmoji","copyProperties","cx"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m={MAX_ITEMS:40,match:function(n){var o=j.findEmoji(n);if(!o||!o.length)return false;var p=o[0],q=o.index,r=o.emoji;return {startIndex:q,endIndex:q+p.length,element:this._element(r)};},_element:function(n){var o=h.span(null);g.addClass(o,"_1az");g.addClass(o,"_1a-");g.addClass(o,n);return o;}};e.exports=k(m,i);},null);
__d("EmoticonsList",[],function(a,b,c,d,e,f){e.exports={emotes:{":)":"smile",":-)":"smile",":]":"smile","=)":"smile","(:":"smile","(=":"smile",":(":"frown",":-(":"frown",":[":"frown","=(":"frown",")=":"frown",":poop:":"poop",":putnam:":"putnam",":P":"tongue",":-P":"tongue",":-p":"tongue",":p":"tongue","=P":"tongue","=D":"grin",":-D":"grin",":D":"grin",":o":"gasp",":-O":"gasp",":O":"gasp",":-o":"gasp",";)":"wink",";-)":"wink","8-)":"glasses","B-)":"glasses","B|":"sunglasses","8-|":"sunglasses","8|":"sunglasses","B-|":"sunglasses",">:(":"grumpy",">:-(":"grumpy",":/":"unsure",":-/":"unsure",":\\":"unsure",":-\\":"unsure","=/":"unsure","=\\":"unsure",":'(":"cry","3:)":"devil","3:-)":"devil","O:)":"angel","O:-)":"angel",":*":"kiss",":-*":"kiss","<3":"heart","<3":"heart","♥":"heart","^_^":"kiki","-_-":"squint","o.O":"confused","O.o":"confused_rev",">:o":"upset",">:O":"upset",">:-O":"upset",">:-o":"upset",">_<":"upset",">.<":"upset",":v":"pacman",":|]":"robot",":3":"colonthree","<(\")":"penguin","(^^^)":"shark","(y)":"like",":like:":"like","(Y)":"like"},symbols:{smile:":)",frown:":(",poop:":poop:",putnam:":putnam:",tongue:":P",grin:"=D",gasp:":o",wink:";)",glasses:"8-)",sunglasses:"B|",grumpy:">:(",unsure:":/",cry:":'(",devil:"3:)",angel:"O:)",kiss:":*",heart:"<3",kiki:"^_^",squint:"-_-",confused:"o.O",confused_rev:"O.o",upset:">:o",pacman:":v",robot:":|]",colonthree:":3",penguin:"<(\")",shark:"(^^^)",like:"(y)"},regexp:/(^|[\s'".])(:\)(?!\))|:\-\)(?!\))|:\]|=\)(?!\))|\(:|\(=|:\(|:\-\(|:\[|=\(|\)=|:poop:|:putnam:|:P|:\-P|:\-p|:p|=P|=D|:\-D|:D|:o|:\-O|:O|:\-o|;\)(?!\))|;\-\)(?!\))|8\-\)(?!\))|B\-\)(?!\))|B\||8\-\||8\||B\-\||>:\(|>:\-\(|:\/|:\-\/|:\\|:\-\\|=\/|=\\|:'\(|3:\)(?!\))|3:\-\)(?!\))|O:\)(?!\))|O:\-\)(?!\))|:\*|:\-\*|<3|<3|\u2665|\^_\^|\-_\-|o\.O|O\.o|>:o|>:O|>:\-O|>:\-o|>_<|>\.<|:v|:\|\]|:3|<\("\)(?!\))|\(\^\^\^\)(?!\))|\(y\)(?!\))|:like:|\(Y\)(?!\)))([\s'".,!?]|<br>|$)/,noncapturingRegexp:/(?:^|[\s'".])(:\)(?!\))|:\-\)(?!\))|:\]|=\)(?!\))|\(:|\(=|:\(|:\-\(|:\[|=\(|\)=|:poop:|:putnam:|:P|:\-P|:\-p|:p|=P|=D|:\-D|:D|:o|:\-O|:O|:\-o|;\)(?!\))|;\-\)(?!\))|8\-\)(?!\))|B\-\)(?!\))|B\||8\-\||8\||B\-\||>:\(|>:\-\(|:\/|:\-\/|:\\|:\-\\|=\/|=\\|:'\(|3:\)(?!\))|3:\-\)(?!\))|O:\)(?!\))|O:\-\)(?!\))|:\*|:\-\*|<3|<3|\u2665|\^_\^|\-_\-|o\.O|O\.o|>:o|>:O|>:\-O|>:\-o|>_<|>\.<|:v|:\|\]|:3|<\("\)(?!\))|\(\^\^\^\)(?!\))|\(y\)(?!\))|:like:|\(Y\)(?!\)))(?:[\s'".,!?]|<br>|$)/};},null);
__d("DOMEmote",["CSS","EmoticonsList","JSXDOM","TransformTextToDOMMixin","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k){var l={MAX_ITEMS:40,match:function(m){var n=h.regexp.exec(m);if(!n||!n.length)return false;var o=n[2],p=n.index+n[1].length;return {startIndex:p,endIndex:p+o.length,element:this._element(o,h.emotes[o])};},_element:function(m,n){var o=i.span({className:"emoticon_text",'aria-hidden':"true"},m),p=i.span({title:m,className:"emoticon"});g.addClass(p,'emoticon_'+n);return [o,p];}};e.exports=k(l,j);},null);
__d("transformTextToDOM",["createArrayFrom"],function(a,b,c,d,e,f,g){function h(i,j){var k=[i];j=g(j);j.forEach(function(l){var m,n=l;if(l.__params){m=l.params;n=l.obj;}k=n.transform(k,m);});return k;}e.exports=h;},null);
__d("emojiAndEmote",["DOMEmoji","DOMEmote","transformTextToDOM"],function(a,b,c,d,e,f,g,h,i){var j=function(k){var l=[g,h];return i(k,l);};e.exports=j;},null);
__d("Emoji",["DOMEmoji","JSXDOM","emojiAndEmote","transformTextToDOM"],function(a,b,c,d,e,f,g,h,i,j){var k={htmlEmojiAndEmote:function(l,m){return (h.span(null,i(l))).innerHTML;},htmlEmojiAndEmoteWithoutFBID:function(l,m){return (h.span(null,i(l,false))).innerHTML;},htmlEmoji:function(l){return (h.span(null,j(l,g))).innerHTML;}};e.exports=k;},null);
__d("Emote",["DOMEmote","JSXDOM","transformTextToDOM"],function(a,b,c,d,e,f,g,h,i){var j={htmlEmoteWithoutFBID:function(k,l){return (h.span(null,i(k,g))).innerHTML;},htmlEmote:function(k,l){return (h.span(null,i(k,[g]))).innerHTML;}};e.exports=j;},null);
__d("TextWithEmoticons.react",["Emoji","Emote","React"],function(a,b,c,d,e,f,g,h,i){var j=i.createClass({displayName:'ReactTextWithEmoticons',render:function(){if(!this.props.renderEmoticons&&!this.props.renderEmoji)return i.createElement("span",null,this.props.text);var k;if(this.props.renderEmoticons&&this.props.renderEmoji){k=g.htmlEmojiAndEmoteWithoutFBID(this.props.text);}else if(this.props.renderEmoticons){k=h.htmlEmoteWithoutFBID(this.props.text);}else k=g.htmlEmoji(this.props.text);return i.createElement("span",{dangerouslySetInnerHTML:{__html:k}});}});e.exports=j;},null);
__d("UntrustedLink",["DOM","Event","URI","UserAgent_DEPRECATED","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k){function l(m,n,o,p){this.dom=m;this.url=m.href;this.hash=n;this.func_get_params=p||function(){return {};};h.listen(this.dom,'click',this.onclick.bind(this));h.listen(this.dom,'mousedown',this.onmousedown.bind(this));h.listen(this.dom,'mouseup',this.onmouseup.bind(this));h.listen(this.dom,'mouseout',this.onmouseout.bind(this));this.onmousedown(h.$E(o));}l.bootstrap=function(m,n,o,p){if(m.__untrusted)return;m.__untrusted=true;new l(m,n,o,p);};l.prototype.getRewrittenURI=function(){var m=k({u:this.url,h:this.hash},this.func_get_params(this.dom)),n=new i('/l.php').setSubdomain('www');if(new i(this.url).getProtocol()=='https'){return n.setQueryData(m).setProtocol('https');}else return n.setQueryData(m).setProtocol('http');};l.prototype.onclick=function(){setTimeout((function(){this.setHref(this.url);}).bind(this),100);this.setHref(this.getRewrittenURI());};l.prototype.onmousedown=function(m){if(m.button==2)this.setHref(this.getRewrittenURI());};l.prototype.onmouseup=function(){this.setHref(this.getRewrittenURI());};l.prototype.onmouseout=function(){this.setHref(this.url);};l.prototype.setHref=function(m){if(j.ie()<9){var n=g.create('span');g.appendContent(this.dom,n);this.dom.href=m;g.remove(n);}else this.dom.href=m;};e.exports=l;},null);
__d("Link.react",["ErrorUtils","React","UntrustedLink","URI","invariant","isFacebookURI","keyOf"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n=m({url:null}),o=h.createClass({displayName:'Link',propTypes:{href:function(p,q,r){var s=p[q],t=typeof s;k(s==null||t==='string'||s instanceof j||(t==='object'&&n in s));}},getURIData:function(){var p=this.props.href,q=null;if(p instanceof j){p=p.toString();}else if(p&&typeof p==='object'){var r=p;p=r.url;q=r.shimhash;}return {href:p||'#',shimhash:q};},render:function(){var p=this.getURIData(),q=this.props.rel;if(p.shimhash){q=q?(q+' nofollow'):'nofollow';}else try{if(!l(j(p.href)))g.reportError(new Error('Rendering external link '+p.href+' without shim'),true);}catch(r){}return (h.createElement("a",Object.assign({},this.props,{href:p.href,rel:q,onMouseDown:this._handleMouseDown}),this.props.children));},_handleMouseDown:function(event){var p=this.getURIData();if(p.shimhash)i.bootstrap(this.getDOMNode(),p.shimhash);this.props.onMouseDown&&this.props.onMouseDown(event);}});e.exports=o;},null);
__d("Newline.react",["React"],function(a,b,c,d,e,f,g){var h=g.createClass({displayName:'Newline',render:function(){return g.createElement("br",Object.assign({},this.props));}});e.exports=h;},null);
__d("Text.react",["React"],function(a,b,c,d,e,f,g){var h=g.createClass({displayName:'Text',render:function(){return (g.createElement("span",Object.assign({},this.props),this.props.children));}});e.exports=h;},null);
__d("ES6StringUtils",[],function(a,b,c,d,e,f){var g={fromCodePoint:function(){for(var h=[],i=0,j=arguments.length;i<j;i++)h.push(arguments[i]);if(String.fromCodePoint)return String.fromCodePoint.apply(this,h);var k=[];for(var l=0;l<h.length;l++){var m=Number(h[l]);if(!isFinite(m)||m<0||1114111<m||Math.floor(m)!=m)throw RangeError('Invalid code point: '+h[l]);if(m<65536){k.push(String.fromCharCode(m));}else{m-=65536;k.push(String.fromCharCode((m>>10)+55296),String.fromCharCode((m%1024)+56320));}}return k.join('');},codePointAt:function(h){"use strict";if(String.prototype.codePointAt)return String.prototype.codePointAt.call(this,h);if(this===null||this===undefined)throw TypeError('Invalid context: '+this);var i=String(this),j=i.length;h=h?Number(h):0;if(h!=h)h=0;if(h<0||j<=h)return undefined;var k=i.charCodeAt(h);if(55296<=k&&k<=56319&&j>h+1){var l=i.charCodeAt(h+1);if(56320<=l&&l<=57343)return (k-55296)*1024+l-56320+65536;}return k;}};e.exports=g;},null);
__d("UnicodeUtils",["ES6StringUtils"],function(a,b,c,d,e,f,g){"use strict";var h=55296,i=57343,j=/[\uD800-\uDFFF]/;function k(s){return h<=s&&s<=i;}function l(s){return j.test(s);}function m(s,t){return 1+k(s.charCodeAt(t));}function n(s){if(!l(s))return s.length;var t=0;for(var u=0;u<s.length;u+=m(s,u))t++;return t;}function o(s,t,u){t=t||0;u=(u===undefined)?Infinity:(u||0);if(!l(s))return s.substr(t,u);var v=s.length;if(v<=0||t>v||u<=0)return '';var w=0;if(t>0){for(;t>0&&w<v;t--)w+=m(s,w);if(w>=v)return '';}else if(t<0){for(w=v;t<0&&0<w;t++)w-=m(s,w-1);if(w<0)w=0;}var x=v;if(u<v)for(x=w;u>0&&x<v;u--)x+=m(s,x);return s.substring(w,x);}function p(s,t,u){t=t||0;u=(u===undefined)?Infinity:(u||0);if(t<0)t=0;if(u<0)u=0;var v=Math.abs(u-t);t=(t<u)?t:u;return o(s,t,v);}function q(s){var t=[];for(var u=0;u<s.length;u+=m(s,u)){var v=g.codePointAt.call(s,u);t.push(v);}return t;}var r={isCodeUnitInSurrogateRange:k,getUTF16Length:m,strlen:n,substr:o,substring:p,getCodePoints:q};e.exports=r;},null);
__d("BaseTextWithEntities.react",["Newline.react","React","Text.react","UnicodeUtils"],function(a,b,c,d,e,f,g,h,i,j){"use strict";function k(o,p){return o.offset-p.offset;}var l=/(\r\n|[\r\n])/,m=h.PropTypes.shape({length:h.PropTypes.number.isRequired,offset:h.PropTypes.number.isRequired}),n=h.createClass({displayName:'BaseTextWithEntities',propTypes:{aggregatedRanges:h.PropTypes.array,imageRanges:h.PropTypes.array,ranges:h.PropTypes.arrayOf(m),rangeRenderer:h.PropTypes.func.isRequired,text:h.PropTypes.string.isRequired,textRenderer:h.PropTypes.func.isRequired},_getSortedRanges:function(){var o=[];[this.props.ranges,this.props.aggregatedRanges,this.props.imageRanges].filter(function(p){return p!=null;}).forEach(function(p){return o=o.concat(p);});return o.sort(k);},_renderText:function(o){var p=o.split(l),q={};for(var r=0;r<p.length;r++){var s=p[r];if(s)if(r%2===1){q[r]=h.createElement(g,null);}else q[r]=this.props.textRenderer(p[r]);}return q;},render:function(){var o=0,p=this.props.text,q=this._getSortedRanges(),r={},s=q.length;for(var t=0,u=s;t<u;t++){var v=q[t];if(v.offset<o)continue;if(v.offset>o)r['text'+t]=this._renderText(j.substring(p,o,v.offset));var w=j.substr(p,v.offset,v.length);r['range'+t]=this.props.rangeRenderer(w,v);o=v.offset+v.length;}if(p.length>o)r.end=this._renderText(j.substr(p,o));return (h.createElement(i,{className:this.props.className,style:this.props.style},r));}});e.exports=n;},null);
__d("TextWithEntities.react",["Link.react","React","BaseTextWithEntities.react","TextWithEmoticons.react"],function(a,b,c,d,e,f,g,h,i,j){"use strict";function k(m){return (m).replace(/<3\b|♥/g,'\u2665');}var l=h.createClass({displayName:'TextWithEntities',_renderText:function(m){if(this.props.renderEmoticons||this.props.renderEmoji){return (h.createElement(j,{text:m,renderEmoticons:this.props.renderEmoticons,renderEmoji:this.props.renderEmoji}));}else return k(m);},_renderRange:function(m,n){if(this.props.interpolator){return this.props.interpolator(m,n);}else return (h.createElement(g,{href:n.entity},m));},render:function(){return (h.createElement(i,Object.assign({},this.props,{textRenderer:this._renderText,rangeRenderer:this._renderRange,ranges:this.props.ranges,imageRanges:this.props.imageRanges,aggregatedRanges:this.props.aggregatedRanges,text:this.props.text})));}});e.exports=l;},null);
__d("ARIA",["DOM","emptyFunction","ge"],function(a,b,c,d,e,f,g,h,i){var j,k,l=function(){j=i('ariaAssertiveAlert');if(!j){j=g.create('div',{id:'ariaAssertiveAlert',className:'accessible_elem','aria-live':'assertive'});g.appendContent(document.body,j);}k=i('ariaPoliteAlert');if(!k){k=j.cloneNode(false);k.setAttribute('id','ariaPoliteAlert');k.setAttribute('aria-live','polite');g.appendContent(document.body,k);}l=h;};function m(o,p){l();var q=p?j:k;g.setContent(q,o);}var n={owns:function(o,p){o.setAttribute('aria-owns',g.getID(p));},setPopup:function(o,p){var q=g.getID(p);o.setAttribute('aria-owns',q);o.setAttribute('aria-haspopup','true');if(o.tabIndex==-1)o.tabIndex=0;},announce:function(o){m(o,true);},notify:function(o){m(o);}};e.exports=n;},null);
__d("getVendorPrefixedName",["ExecutionEnvironment","camelize","invariant"],function(a,b,c,d,e,f,g,h,i){var j={},k=['Webkit','ms','Moz','O'],l=new RegExp('^('+k.join('|')+')'),m=g.canUseDOM?document.createElement('div').style:{};function n(p){for(var q=0;q<k.length;q++){var r=k[q]+p;if(r in m)return r;}return null;}function o(p){var q=h(p);if(j[q]===undefined){var r=q.charAt(0).toUpperCase()+q.slice(1);if(l.test(r))i(false);j[q]=(q in m)?q:n(r);}return j[q];}e.exports=o;},null);
__d("BrowserSupport",["DOM","ExecutionEnvironment","UserAgent_DEPRECATED","getVendorPrefixedName"],function(a,b,c,d,e,f,g,h,i,j){var k={},l=h.canUseDOM?document.createElement('div'):null,m={hasCSSAnimations:function(){return !!j('animationName');},hasCSSTransforms:function(){return !!j('transform');},hasCSS3DTransforms:function(){return !!j('perspective');},hasCSSTransitions:function(){return !!j('transition');},hasPositionSticky:function(){if(!h.canUseDOM)return false;if(k.sticky===undefined){l.style.cssText='position:-moz-sticky;position:-webkit-sticky;'+'position:-o-sticky;position:-ms-sticky;position:sticky;';k.sticky=/sticky/.test(l.style.position);}return k.sticky;},hasPointerEvents:function(){if(!h.canUseDOM)return false;if(k.pointerEvents===undefined)if(!('pointerEvents' in l.style)){k.pointerEvents=false;}else{l.style.pointerEvents='auto';l.style.pointerEvents='x';g.appendContent(document.documentElement,l);k.pointerEvents=window.getComputedStyle&&getComputedStyle(l,'').pointerEvents==='auto';g.remove(l);}return k.pointerEvents;},hasFileAPI:function(){if(k.fileAPI===undefined)k.fileAPI=!(i.webkit()&&!i.chrome()&&i.windows())&&'FileList' in window&&'FormData' in window;return k.fileAPI;},hasBlobFactory:function(){if(k.blobFactory===undefined)k.blobFactory=!!a.blob;return k.blobFactory;},getTransitionEndEvent:function(){if(k.transitionEnd===undefined){var n={transition:'transitionend',WebkitTransition:'webkitTransitionEnd',MozTransition:'mozTransitionEnd',OTransition:'oTransitionEnd'},o=j('transition');k.transitionEnd=n[o]||null;}return k.transitionEnd;},hasClipboardEvents:function(){if(!h.canUseDOM)return false;if(k.clipboardEvents===undefined){var n=document.createElement('textarea'),o='oncut',p=(o in n);if(!p){n.setAttribute(o,'return;');p=typeof n[o]=='function';}k.clipboardEvents=p;}return k.clipboardEvents;}};e.exports=m;},null);
__d("shield",[],function(a,b,c,d,e,f){function g(h,i){if(typeof h!='function')throw new TypeError();var j=Array.prototype.slice.call(arguments,2);return function(){return h.apply(i,j);};}e.exports=g;},null);
__d("Animation",["BrowserSupport","CSS","DataStore","DOM","Style","getVendorPrefixedName","setIntervalAcrossTransitions","setTimeoutAcrossTransitions","shield"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){var p,q=[],r;function s(ja){if(a==this){return new s(ja);}else{this.obj=ja;this._reset_state();this.queue=[];this.last_attr=null;}}function t(ja){if(g.hasCSS3DTransforms()){return w(ja);}else return v(ja);}function u(ja){return ja.toFixed(8);}function v(ja){ja=[ja[0],ja[4],ja[1],ja[5],ja[12],ja[13]];return 'matrix('+ja.map(u).join(',')+')';}function w(ja){return 'matrix3d('+ja.map(u).join(',')+')';}function x(ja,ka){if(!ja)ja=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1];var la=[];for(var ma=0;ma<4;ma++)for(var na=0;na<4;na++){var oa=0;for(var pa=0;pa<4;pa++)oa+=ja[ma*4+pa]*ka[pa*4+na];la[ma*4+na]=oa;}return la;}var y=0;s.prototype._reset_state=function(){this.state={attrs:{},duration:500};};s.prototype.stop=function(){this._reset_state();this.queue=[];return this;};s.prototype._build_container=function(){if(this.container_div){this._refresh_container();return;}if(this.obj.firstChild&&this.obj.firstChild.__animation_refs){this.container_div=this.obj.firstChild;this.container_div.__animation_refs++;this._refresh_container();return;}var ja=document.createElement('div');ja.style.padding='0px';ja.style.margin='0px';ja.style.border='0px';ja.__animation_refs=1;var ka=this.obj.childNodes;while(ka.length)ja.appendChild(ka[0]);this.obj.appendChild(ja);this._orig_overflow=this.obj.style.overflow;this.obj.style.overflow='hidden';this.container_div=ja;this._refresh_container();};s.prototype._refresh_container=function(){this.container_div.style.height='auto';this.container_div.style.width='auto';this.container_div.style.height=this.container_div.offsetHeight+'px';this.container_div.style.width=this.container_div.offsetWidth+'px';};s.prototype._destroy_container=function(){if(!this.container_div)return;if(!--this.container_div.__animation_refs){var ja=this.container_div.childNodes;while(ja.length)this.obj.appendChild(ja[0]);this.obj.removeChild(this.container_div);}this.container_div=null;this.obj.style.overflow=this._orig_overflow;};var z=1,aa=2,ba=3;s.prototype._attr=function(ja,ka,la){ja=ja.replace(/-[a-z]/gi,function(na){return na.substring(1).toUpperCase();});var ma=false;switch(ja){case 'background':this._attr('backgroundColor',ka,la);return this;case 'backgroundColor':case 'borderColor':case 'color':ka=fa(ka);break;case 'opacity':ka=parseFloat(ka,10);break;case 'height':case 'width':if(ka=='auto'){ma=true;}else ka=parseInt(ka,10);break;case 'borderWidth':case 'lineHeight':case 'fontSize':case 'margin':case 'marginBottom':case 'marginLeft':case 'marginRight':case 'marginTop':case 'padding':case 'paddingBottom':case 'paddingLeft':case 'paddingRight':case 'paddingTop':case 'bottom':case 'left':case 'right':case 'top':case 'scrollTop':case 'scrollLeft':ka=parseInt(ka,10);break;case 'rotateX':case 'rotateY':case 'rotateZ':ka=parseInt(ka,10)*Math.PI/180;break;case 'translateX':case 'translateY':case 'translateZ':case 'scaleX':case 'scaleY':case 'scaleZ':ka=parseFloat(ka,10);break;case 'rotate3d':this._attr('rotateX',ka[0],la);this._attr('rotateY',ka[1],la);this._attr('rotateZ',ka[2],la);return this;case 'rotate':this._attr('rotateZ',ka,la);return this;case 'scale3d':this._attr('scaleZ',ka[2],la);case 'scale':this._attr('scaleX',ka[0],la);this._attr('scaleY',ka[1],la);return this;case 'translate3d':this._attr('translateZ',ka[2],la);case 'translate':this._attr('translateX',ka[0],la);this._attr('translateY',ka[1],la);return this;default:throw new Error(ja+' is not a supported attribute!');}if(this.state.attrs[ja]===undefined)this.state.attrs[ja]={};if(ma)this.state.attrs[ja].auto=true;switch(la){case ba:this.state.attrs[ja].start=ka;break;case aa:this.state.attrs[ja].by=true;case z:this.state.attrs[ja].value=ka;break;}};function ca(ja){var ka=parseInt(k.get(ja,'paddingLeft'),10),la=parseInt(k.get(ja,'paddingRight'),10),ma=parseInt(k.get(ja,'borderLeftWidth'),10),na=parseInt(k.get(ja,'borderRightWidth'),10);return ja.offsetWidth-(ka?ka:0)-(la?la:0)-(ma?ma:0)-(na?na:0);}function da(ja){var ka=parseInt(k.get(ja,'paddingTop'),10),la=parseInt(k.get(ja,'paddingBottom'),10),ma=parseInt(k.get(ja,'borderTopWidth'),10),na=parseInt(k.get(ja,'borderBottomWidth'),10);return ja.offsetHeight-(ka?ka:0)-(la?la:0)-(ma?ma:0)-(na?na:0);}s.prototype.to=function(ja,ka){if(ka===undefined){this._attr(this.last_attr,ja,z);}else{this._attr(ja,ka,z);this.last_attr=ja;}return this;};s.prototype.by=function(ja,ka){if(ka===undefined){this._attr(this.last_attr,ja,aa);}else{this._attr(ja,ka,aa);this.last_attr=ja;}return this;};s.prototype.from=function(ja,ka){if(ka===undefined){this._attr(this.last_attr,ja,ba);}else{this._attr(ja,ka,ba);this.last_attr=ja;}return this;};s.prototype.duration=function(ja){this.state.duration=ja?ja:0;return this;};s.prototype.checkpoint=function(ja,ka){if(ja===undefined)ja=1;this.state.checkpoint=ja;this.queue.push(this.state);this._reset_state();this.state.checkpointcb=ka;return this;};s.prototype.blind=function(){this.state.blind=true;return this;};s.prototype.hide=function(){this.state.hide=true;return this;};s.prototype.show=function(){this.state.show=true;return this;};s.prototype.ease=function(ja){this.state.ease=ja;return this;};s.prototype.go=function(){var ja=Date.now();this.queue.push(this.state);for(var ka=0;ka<this.queue.length;ka++){this.queue[ka].start=ja-y;if(this.queue[ka].checkpoint)ja+=this.queue[ka].checkpoint*this.queue[ka].duration;}ga(this);return this;};s.prototype._show=function(){h.show(this.obj);};s.prototype._hide=function(){h.hide(this.obj);};s.prototype._frame=function(ja){var ka=true,la=false,ma;function na(kb){return document.documentElement[kb]||document.body[kb];}function oa(kb,lb){return ((kb===document.body)?na(lb):kb[lb]);}function pa(kb,lb){return (lb.lastScrollTop!==oa(kb.obj,'scrollTop')||lb.lastScrollLeft!==oa(kb.obj,'scrollLeft'));}function qa(kb,lb){lb.lastScrollTop=oa(kb.obj,'scrollTop');lb.lastScrollLeft=oa(kb.obj,'scrollLeft');}for(var ra=0;ra<this.queue.length;ra++){var sa=this.queue[ra];if(sa.start>ja){ka=false;continue;}if(sa.checkpointcb){this._callback(sa.checkpointcb,ja-sa.start);sa.checkpointcb=null;}if(sa.started===undefined){if(sa.show)this._show();for(var ta in sa.attrs){if(sa.attrs[ta].start!==undefined)continue;switch(ta){case 'backgroundColor':case 'borderColor':case 'color':ma=fa(k.get(this.obj,ta=='borderColor'?'borderLeftColor':ta));if(sa.attrs[ta].by){sa.attrs[ta].value[0]=Math.min(255,Math.max(0,sa.attrs[ta].value[0]+ma[0]));sa.attrs[ta].value[1]=Math.min(255,Math.max(0,sa.attrs[ta].value[1]+ma[1]));sa.attrs[ta].value[2]=Math.min(255,Math.max(0,sa.attrs[ta].value[2]+ma[2]));}break;case 'opacity':ma=k.getOpacity(this.obj);if(sa.attrs[ta].by)sa.attrs[ta].value=Math.min(1,Math.max(0,sa.attrs[ta].value+ma));break;case 'height':ma=da(this.obj);if(sa.attrs[ta].by)sa.attrs[ta].value+=ma;break;case 'width':ma=ca(this.obj);if(sa.attrs[ta].by)sa.attrs[ta].value+=ma;break;case 'scrollLeft':case 'scrollTop':ma=oa(this.obj,ta);if(sa.attrs[ta].by)sa.attrs[ta].value+=ma;qa(this,sa);break;case 'rotateX':case 'rotateY':case 'rotateZ':case 'translateX':case 'translateY':case 'translateZ':ma=i.get(this.obj,ta,0);if(sa.attrs[ta].by)sa.attrs[ta].value+=ma;break;case 'scaleX':case 'scaleY':case 'scaleZ':ma=i.get(this.obj,ta,1);if(sa.attrs[ta].by)sa.attrs[ta].value+=ma;break;default:ma=parseInt(k.get(this.obj,ta),10)||0;if(sa.attrs[ta].by)sa.attrs[ta].value+=ma;break;}sa.attrs[ta].start=ma;}if((sa.attrs.height&&sa.attrs.height.auto)||(sa.attrs.width&&sa.attrs.width.auto)){this._destroy_container();for(var ta in {height:1,width:1,fontSize:1,borderLeftWidth:1,borderRightWidth:1,borderTopWidth:1,borderBottomWidth:1,paddingLeft:1,paddingRight:1,paddingTop:1,paddingBottom:1})if(sa.attrs[ta])this.obj.style[ta]=sa.attrs[ta].value+(typeof sa.attrs[ta].value=='number'?'px':'');if(sa.attrs.height&&sa.attrs.height.auto)sa.attrs.height.value=da(this.obj);if(sa.attrs.width&&sa.attrs.width.auto)sa.attrs.width.value=ca(this.obj);}sa.started=true;if(sa.blind)this._build_container();}var ua=(ja-sa.start)/sa.duration;if(ua>=1){ua=1;if(sa.hide)this._hide();}else ka=false;var va=sa.ease?sa.ease(ua):ua;if(!la&&ua!=1&&sa.blind)la=true;for(var ta in sa.attrs)switch(ta){case 'backgroundColor':case 'borderColor':case 'color':if(sa.attrs[ta].start[3]!=sa.attrs[ta].value[3]){this.obj.style[ta]='rgba('+ea(va,sa.attrs[ta].start[0],sa.attrs[ta].value[0],true)+','+ea(va,sa.attrs[ta].start[1],sa.attrs[ta].value[1],true)+','+ea(va,sa.attrs[ta].start[2],sa.attrs[ta].value[2],true)+','+ea(va,sa.attrs[ta].start[3],sa.attrs[ta].value[3],false)+')';}else this.obj.style[ta]='rgb('+ea(va,sa.attrs[ta].start[0],sa.attrs[ta].value[0],true)+','+ea(va,sa.attrs[ta].start[1],sa.attrs[ta].value[1],true)+','+ea(va,sa.attrs[ta].start[2],sa.attrs[ta].value[2],true)+')';break;case 'opacity':k.set(this.obj,'opacity',ea(va,sa.attrs[ta].start,sa.attrs[ta].value));break;case 'height':case 'width':this.obj.style[ta]=va==1&&sa.attrs[ta].auto?'auto':ea(va,sa.attrs[ta].start,sa.attrs[ta].value,true)+'px';break;case 'scrollLeft':case 'scrollTop':var wa=this.obj===document.body;if(pa(this,sa)){delete sa.attrs.scrollTop;delete sa.attrs.scrollLeft;}else{var xa=ea(va,sa.attrs[ta].start,sa.attrs[ta].value,true);if(!wa){this.obj[ta]=xa;}else if(ta=='scrollLeft'){a.scrollTo(xa,na('scrollTop'));}else a.scrollTo(na('scrollLeft'),xa);qa(this,sa);}break;case 'translateX':case 'translateY':case 'translateZ':case 'rotateX':case 'rotateY':case 'rotateZ':case 'scaleX':case 'scaleY':case 'scaleZ':i.set(this.obj,ta,ea(va,sa.attrs[ta].start,sa.attrs[ta].value,false));break;default:this.obj.style[ta]=ea(va,sa.attrs[ta].start,sa.attrs[ta].value,true)+'px';break;}var ya=null,za=i.get(this.obj,'translateX',0),ab=i.get(this.obj,'translateY',0),bb=i.get(this.obj,'translateZ',0);if(za||ab||bb)ya=x(ya,[1,0,0,0,0,1,0,0,0,0,1,0,za,ab,bb,1]);var cb=i.get(this.obj,'scaleX',1),db=i.get(this.obj,'scaleY',1),eb=i.get(this.obj,'scaleZ',1);if(cb-1||db-1||eb-1)ya=x(ya,[cb,0,0,0,0,db,0,0,0,0,eb,0,0,0,0,1]);var fb=i.get(this.obj,'rotateX',0);if(fb)ya=x(ya,[1,0,0,0,0,Math.cos(fb),Math.sin(-fb),0,0,Math.sin(fb),Math.cos(fb),0,0,0,0,1]);var gb=i.get(this.obj,'rotateY',0);if(gb)ya=x(ya,[Math.cos(gb),0,Math.sin(gb),0,0,1,0,0,Math.sin(-gb),0,Math.cos(gb),0,0,0,0,1]);var hb=i.get(this.obj,'rotateZ',0);if(hb)ya=x(ya,[Math.cos(hb),Math.sin(-hb),0,0,Math.sin(hb),Math.cos(hb),0,0,0,0,1,0,0,0,0,1]);var ib=l('transform');if(ib)if(ya){var jb=t(ya);k.set(this.obj,ib,jb);}else if(ka)k.set(this.obj,ib,null);if(ua==1){this.queue.splice(ra--,1);this._callback(sa.ondone,ja-sa.start-sa.duration);}}if(!la&&this.container_div)this._destroy_container();return !ka;};s.prototype.ondone=function(ja){this.state.ondone=ja;return this;};s.prototype._callback=function(ja,ka){if(ja){y=ka;ja.call(this);y=0;}};function ea(ja,ka,la,ma){return (ma?parseInt:parseFloat)((la-ka)*ja+ka,10);}function fa(ja){var ka=/^#([a-f0-9]{1,2})([a-f0-9]{1,2})([a-f0-9]{1,2})$/i.exec(ja);if(ka){return [parseInt(ka[1].length==1?ka[1]+ka[1]:ka[1],16),parseInt(ka[2].length==1?ka[2]+ka[2]:ka[2],16),parseInt(ka[3].length==1?ka[3]+ka[3]:ka[3],16),1];}else{var la=/^rgba? *\(([0-9]+), *([0-9]+), *([0-9]+)(?:, *([0-9\.]+))?\)$/.exec(ja);if(la){return [parseInt(la[1],10),parseInt(la[2],10),parseInt(la[3],10),la[4]?parseFloat(la[4]):1];}else if(ja=='transparent'){return [255,255,255,0];}else throw 'Named color attributes are not supported.';}}function ga(ja){q.push(ja);if(q.length===1){if(!p){var ka=a.requestAnimationFrame||a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame;if(ka)p=ka.bind(a);}if(p){p(ia);}else r=m(ia,20);}if(p)ha();ia(Date.now(),true);}function ha(){if(!p)throw new Error('Ending timer only valid with requestAnimationFrame');var ja=0;for(var ka=0;ka<q.length;ka++){var la=q[ka];for(var ma=0;ma<la.queue.length;ma++){var na=la.queue[ma].start+la.queue[ma].duration;if(na>ja)ja=na;}}if(r){clearTimeout(r);r=null;}var oa=Date.now();if(ja>oa)r=n(o(ia),ja-oa);}function ia(ja,ka){var la=Date.now();for(var ma=(ka===true)?q.length-1:0;ma<q.length;ma++)try{if(!q[ma]._frame(la))q.splice(ma--,1);}catch(na){q.splice(ma--,1);}if(q.length===0){if(r){if(p){clearTimeout(r);}else clearInterval(r);r=null;}}else if(p)p(ia);}s.ease={};s.ease.begin=function(ja){return Math.sin(Math.PI/2*(ja-1))+1;};s.ease.end=function(ja){return Math.sin(.5*Math.PI*ja);};s.ease.both=function(ja){return .5*Math.sin(Math.PI*(ja-.5))+.5;};s.prependInsert=function(ja,ka){s.insert(ja,ka,j.prependContent);};s.appendInsert=function(ja,ka){s.insert(ja,ka,j.appendContent);};s.insert=function(ja,ka,la){k.set(ka,'opacity',0);la(ja,ka);new s(ka).from('opacity',0).to('opacity',1).duration(400).go();};e.exports=s;},null);
__d("ViewportBounds",["Arbiter","ArbiterMixin","DOM","Style","Vector","csx","copyProperties","emptyFunction","removeFromArray"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){var p={top:[],right:[],bottom:[],left:[]};function q(u){return function(){var v=0;p[u].forEach(function(w){v=Math.max(v,w.getSize());});return v;};}function r(u,v){return function(w){return new s(u,w,v);};}function s(u,v,w){this.getSide=n.thatReturns(u);this.getSize=function(){return typeof v==='function'?v():v;};this.isPersistent=n.thatReturns(w);p[u].push(this);t.inform('change');}s.prototype.remove=function(){o(p[this.getSide()],this);t.inform('change');};g.subscribe('page_transition',function(){for(var u in p)p[u].forEach(function(v){if(!v.isPersistent())v.remove();});});var t=m({getTop:q('top'),getRight:q('right'),getBottom:q('bottom'),getLeft:q('left'),getElementPosition:function(u){var v=k.getElementPosition(u);v.y-=t.getTop();return v;},addTop:r('top'),addRight:r('right'),addBottom:r('bottom'),addLeft:r('left'),addPersistentTop:r('top',true),addPersistentRight:r('right',true),addPersistentBottom:r('bottom',true),addPersistentLeft:r('left',true)},h);t.addPersistentTop(function(){var u=i.scry(document,"div._4f7n")[0];if(u&&j.isFixed(u)){var v=i.scry(document,"div._21mm")[0];return v?v.offsetHeight:0;}return 0;});e.exports=t;},null);
__d("DOMScroll",["Animation","Arbiter","DOM","DOMQuery","Vector","ViewportBounds","ge","isAsyncScrollQuery"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){var o={SCROLL:'dom-scroll',getScrollState:function(){var p=k.getViewportDimensions(),q=k.getDocumentDimensions(),r=(q.x>p.x),s=(q.y>p.y);r+=0;s+=0;return new k(r,s);},_scrollbarSize:null,_initScrollbarSize:function(){var p=i.create('p');p.style.width='100%';p.style.height='200px';var q=i.create('div');q.style.position='absolute';q.style.top='0px';q.style.left='0px';q.style.visibility='hidden';q.style.width='200px';q.style.height='150px';q.style.overflow='hidden';q.appendChild(p);document.body.appendChild(q);var r=p.offsetWidth;q.style.overflow='scroll';var s=p.offsetWidth;if(r==s)s=q.clientWidth;document.body.removeChild(q);o._scrollbarSize=r-s;},getScrollbarSize:function(){if(o._scrollbarSize===null)o._initScrollbarSize();return o._scrollbarSize;},scrollTo:function(p,q,r,s,t,u){if(typeof q=='undefined'||q===true)q=750;if(n())q=false;if(!(p instanceof k)){var v=k.getScrollPosition().x,w=k.getElementPosition(m(p)).y;p=new k(v,w,'document');if(!s)p.y-=l.getTop()/(r?2:1);}if(r){p.y-=k.getViewportDimensions().y/2;}else if(s){p.y-=k.getViewportDimensions().y;p.y+=s;}if(t)p.y-=t;p=p.convertTo('document');if(q){return new g(document.body).to('scrollTop',p.y).to('scrollLeft',p.x).ease(g.ease.end).duration(q).ondone(u).go();}else if(window.scrollTo){window.scrollTo(p.x,p.y);u&&u();}h.inform(o.SCROLL);},ensureVisible:function(p,q,r,s,t){if(r===undefined)r=10;p=m(p);if(q)p=j.find(p,q);var u=k.getScrollPosition().x,v=k.getScrollPosition().y,w=v+k.getViewportDimensions().y,x=k.getElementPosition(p).y,y=x+k.getElementDimensions(p).y;x-=l.getTop();x-=r;y+=r;if(x<v){o.scrollTo(new k(u,x,'document'),s,false,false,0,t);}else if(y>w)if(x-(y-w)<v){o.scrollTo(new k(u,x,'document'),s,false,false,0,t);}else o.scrollTo(new k(u,y,'document'),s,false,true,0,t);},scrollToTop:function(p){var q=k.getScrollPosition();o.scrollTo(new k(q.x,0,'document'),p!==false);}};e.exports=o;},null);
__d("HistoryManager",["Cookie","Env","Event","URI","UserAgent_DEPRECATED","isFacebookURI","copyProperties","emptyFunction","goOrReplace","isInIframe","setIntervalAcrossTransitions","EagleEye"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q){b('EagleEye');var r={history:null,current:0,fragment:null,isInitialized:function(){return !!r._initialized;},init:function(){if(!h.ALLOW_TRANSITION_IN_IFRAME&&p())return;if(r._initialized)return r;var s=j(),t=s.getFragment()||'';if(t.charAt(0)==='!'){t=t.substr(1);s.setFragment(t);}m(r,{_initialized:true,fragment:t,orig_fragment:t,history:[s],callbacks:[],lastChanged:Date.now(),canonical:j('#'),user:0,enabled:true,debug:n});if(window.history&&history.pushState){this.lastURI=document.URL;window.history.replaceState(this.lastURI,null);i.listen(window,'popstate',function(u){var v=u&&u.state&&typeof u.state==='string';if(v&&r.lastURI!=u.state){r.lastURI=u.state;r.lastChanged=Date.now();r.notify(j(u.state).getUnqualifiedURI().toString());}}.bind(r));if(k.webkit()<534||k.chrome()<=13){q(r.checkURI,42);r._updateRefererURI(this.lastURI);}return r;}r._updateRefererURI(j.getRequestURI(false));if(k.webkit()<500||k.firefox()<2){r.enabled=false;return r;}if('onhashchange' in window){i.listen(window,'hashchange',function(){setTimeout(r.checkURI.bind(r),0);});}else q(r.checkURI,42);return r;},registerURIHandler:function(s){r.callbacks.push(s);return r;},setCanonicalLocation:function(s){r.canonical=j(s);return r;},notify:function(s){if(s==r.orig_fragment)s=r.canonical.getFragment();for(var t=0;t<r.callbacks.length;t++)try{if(r.callbacks[t](s))return true;}catch(u){}return false;},checkURI:function(){if(Date.now()-r.lastChanged<400)return;if(window.history&&history.pushState){var s=j(document.URL).removeQueryData('ref').toString(),t=j(r.lastURI).removeQueryData('ref').toString();if(s!=t){r.lastChanged=Date.now();r.lastURI=s;if(k.webkit()<534)r._updateRefererURI(s);r.notify(j(s).getUnqualifiedURI().toString());}return;}if(k.webkit()&&window.history.length==200){if(!r.warned)r.warned=true;return;}var u=j().getFragment();if(u.charAt(0)=='!')u=u.substr(1);u=u.replace(/%23/g,'#');if(u!=r.fragment.replace(/%23/g,'#')){r.debug([u,' vs ',r.fragment,'whl: ',window.history.length,'QHL: ',r.history.length].join(' '));for(var v=r.history.length-1;v>=0;--v)if(r.history[v].getFragment().replace(/%23/g,'#')==u)break;++r.user;if(v>=0){r.go(v-r.current);}else r.go('#'+u);--r.user;}},_updateRefererURI:function(s){s=s.toString();if(s.charAt(0)!='/'&&s.indexOf('//')==-1)return;var t=new j(window.location);if(l(t)){var u=t.getPath()+window.location.search;}else var u='';var v=j(s).getQualifiedURI().setFragment(u).toString(),w=2048;if(v.length>w)v=v.substring(0,w)+'...';g.set('x-referer',v);},go:function(s,t,u){if(window.history&&history.pushState){t||typeof(s)=='number';var v=j(s).removeQueryData('ref').toString();r.lastChanged=Date.now();this.lastURI=v;if(u){window.history.replaceState(s,null,v);}else window.history.pushState(s,null,v);if(k.webkit()<534)r._updateRefererURI(s);return false;}r.debug('go: '+s);if(t===undefined)t=true;if(!r.enabled)if(!t)return false;if(typeof(s)=='number'){if(!s)return false;var w=s+r.current,x=Math.max(0,Math.min(r.history.length-1,w));r.current=x;w=r.history[x].getFragment()||r.orig_fragment;w=j(w).removeQueryData('ref').getUnqualifiedURI().toString();r.fragment=w;r.lastChanged=Date.now();if(!r.user)o(window.location,window.location.href.split('#')[0]+'#!'+w,u);if(t)r.notify(w);r._updateRefererURI(w);return false;}s=j(s);if(s.getDomain()==j().getDomain())s=j('#'+s.getUnqualifiedURI());var y=r.history[r.current].getFragment(),z=s.getFragment();if(z==y||(y==r.orig_fragment&&z==r.canonical.getFragment())){if(t)r.notify(z);r._updateRefererURI(z);return false;}if(u)r.current--;var aa=(r.history.length-r.current)-1;r.history.splice(r.current+1,aa);r.history.push(j(s));return r.go(1,t,u);},getCurrentFragment:function(){var s=j.getRequestURI(false).getFragment();return s==r.orig_fragment?r.canonical.getFragment():s;}};e.exports=r;},null);
__d("LayerHideOnEscape",["Event","Keys","copyProperties"],function(a,b,c,d,e,f,g,h,i){function j(k){"use strict";this._layer=k;}j.prototype.enable=function(){"use strict";this._subscription=this._layer.subscribe('key',this._handle.bind(this));};j.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;};j.prototype._handle=function(k,event){"use strict";if(g.getKeyCode(event)===h.ESC){this._layer.hide();return false;}};i(j.prototype,{_subscription:null});e.exports=j;},null);
__d("LinkController",["Event","DataStore","Parent","trackReferrer"],function(a,b,c,d,e,f,g,h,i,j){var k='LinkControllerHandler',l=[],m=[];function n(event){var r=event.getTarget(),s=i.byTag(r,'a'),t=s&&s.getAttribute('href',2);if(!t||s.rel||!p(t)||(r.nodeName=='INPUT'&&r.type=='file')||h.get(s,k))return;var u=g.listen(s,'click',function(v){if(t.charAt(t.length-1)=='#'){v.prevent();return;}j(s,t);o(s,v);});h.set(s,k,u);}function o(r,event){if(r.target||r.rel||event.getModifiers().any||(event.which&&event.which!=1))return;var s=l.concat(m);for(var t=0,u=s.length;t<u;t++)if(s[t](r,event)===false)return event.prevent();}function p(r){var s=r.match(/^(\w+):/);return !s||s[1].match(/^http/i);}var q={registerHandler:function(r){l.push(r);},registerFallbackHandler:function(r){m.push(r);}};g.listen(document.documentElement,'mousedown',n);g.listen(document.documentElement,'keydown',n);e.exports=q;},null);
__d("ScrollAwareDOM",["ArbiterMixin","CSS","DOM","DOMDimensions","DOMQuery","HTML","Vector","ViewportBounds","copyProperties","getElementPosition","isAsyncScrollQuery"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q){function r(w,x){return function(){var y=arguments;v.monitor(arguments[w],function(){x.apply(null,y);});};}function s(w){if(!(w instanceof Array))w=[w];for(var x=0;x<w.length;x++){var y=l.replaceJSONWrapper(w[x]);if(y instanceof l){return y.getRootNode();}else if(i.isNode(y))return y;}return null;}function t(w){return p(w).y>n.getTop();}function u(w){var x=p(w).y+j.getElementDimensions(w).height,y=j.getViewportDimensions().height-n.getBottom();return x>=y;}var v=o({monitor:function(w,x){if(q())return x();var y=s(w);if(y){var z=!!y.offsetParent;if(z&&(t(y)||u(y)))return x();var aa=m.getDocumentDimensions(),ba=x();if(z||(y.offsetParent&&!t(y))){var ca=m.getDocumentDimensions().sub(aa),da={delta:ca,target:y};if(v.inform('scroll',da)!==false)ca.scrollElementBy(k.getDocumentScrollElement());}return ba;}else return x();},replace:function(w,x){var y=s(x);if(!y||h.hasClass(y,'hidden_elem'))y=w;return v.monitor(y,function(){i.replace(w,x);});},prependContent:r(1,i.prependContent),insertAfter:r(1,i.insertAfter),insertBefore:r(1,i.insertBefore),setContent:r(0,i.setContent),appendContent:r(1,i.appendContent),remove:r(0,i.remove),empty:r(0,i.empty)},g);e.exports=v;},null);
__d("debounceAcrossTransitions",["debounce"],function(a,b,c,d,e,f,g){function h(i,j,k){return g(i,j,k,true);}e.exports=h;},null);
__d("ModalLayer",["Arbiter","ArbiterMixin","CSS","DataStore","DOM","DOMDimensions","DOMQuery","Event","ScrollAwareDOM","Style","UserAgent_DEPRECATED","Vector","copyProperties","csx","cx","debounceAcrossTransitions","isAsyncScrollQuery","removeFromArray","setTimeoutAcrossTransitions"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y){var z=[],aa=null,ba=null,ca=null;function da(){if(!ca)ca=m.scry(document.body,"._li")[0];return ca;}function ea(la){var ma={position:r.getScrollPosition()},na=la.offsetTop-ma.position.y;i.addClass(la,"_31e");p.set(la,'top',na+'px');g.inform('reflow');ma.listener=o.subscribe('scroll',function(oa,pa){if(m.contains(la,pa.target)){var qa=la.offsetTop-pa.delta.y;p.set(la,'top',qa+'px');ma.position=ma.position.add(pa.delta);return false;}});j.set(la,'ModalLayerData',ma);}function fa(la,ma){var na=j.get(la,'ModalLayerData');if(na){var oa=function(){i.removeClass(la,"_31e");p.set(la,'top','');if(ma){var ra=m.getDocumentScrollElement();ra.scrollTop=na.position.y;if(ra.scrollTop!==na.position.y){ra.scrollTop=na.position.y+1;ra.scrollTop=na.position.y;}}g.inform('reflow');na.listener.unsubscribe();na.listener=null;j.remove(la,'ModalLayerData');};if(ma&&w()){var pa=k.create('div',{className:"_42w"});p.set(pa,'height',la.offsetHeight+'px');k.appendContent(document.body,pa);var qa=m.getDocumentScrollElement();qa.scrollTop=na.position.y;ma=false;setTimeout(function(){oa();k.remove(pa);},0);}else oa();}}function ga(){var la=da();if(!i.hasClass(la,"_31e"))ea(la);}function ha(){if(!z.length)fa(da(),true);}function ia(){var la=z.length;while(la--){var ma=z[la],na=ma.getLayerRoot();ja(na,'');var oa=ma.getLayerContentRoot(),pa=oa.offsetWidth+l.measureElementBox(oa,'width',0,0,1);ja(na,pa);}}function ja(la,ma){p.set(la,'min-width',ma+(ma?'px':''));}function ka(la){"use strict";this._layer=la;}ka.prototype.enable=function(){"use strict";if(!da())return;this._subscription=this._layer.subscribe(['show','hide'],function(la){la=='show'?this._addModal():this._removeModal();}.bind(this));if(this._layer.isShown())this._addModal();};ka.prototype.disable=function(){"use strict";if(!da())return;this._subscription.unsubscribe();this._subscription=null;if(this._layer.isShown())this._removeModal();};ka.prototype._addModal=function(){"use strict";var la=this.getLayerRoot();i.addClass(la,"_3qw");this._wash=k.create('div',{className:"_3ixn"});k.prependContent(la,this._wash);var ma=z[z.length-1];if(ma){ea(ma.getLayerRoot());}else ga();var na=m.getDocumentScrollElement();na.scrollTop=0;if(!z.length){var oa=v(ia,100);aa=n.listen(window,'resize',oa);ba=g.subscribe('reflow',oa);}z.push(this);ka.inform('show',this);setTimeout(ia,0);};ka.prototype._removeModal=function(){"use strict";var la=this.getLayerRoot();i.removeClass(la,"_3qw");k.remove(this._wash);this._wash=null;ja(la,'');var ma=this===z[z.length-1];x(z,this);if(!z.length){aa.remove();aa=null;ba.unsubscribe();ba=null;}y(function(){var na=z[z.length-1];if(na){fa(na.getLayerRoot(),ma);ka.inform('show',na);}else{ha();ka.inform('hide',this);}if(z.length)setTimeout(ia,0);}.bind(this),400);};ka.prototype.getLayerRoot=function(){"use strict";return this._layer.getRoot();};ka.prototype.getLayerContentRoot=function(){"use strict";return this._layer.getContentRoot();};ka.getTopmostModalLayer=function(){"use strict";return z[z.length-1];};ka.unfixed=function(la){"use strict";if(q.chrome()){var ma=da();if(ma&&i.hasClass(ma,"_31e")){var na=m.getDocumentScrollElement(),oa=na.scrollTop;fa(ma,true);la();ea(ma);na.scrollTop=oa;return;}}la();};s(ka,h);e.exports=ka;},null);
__d("areEqual",[],function(a,b,c,d,e,f){var g=function(k,l,m,n){if(k===l)return k!==0||1/k==1/l;if(k==null||l==null)return false;if(typeof k!='object'||typeof l!='object')return false;var o=Object.prototype.toString,p=o.call(k);if(p!=o.call(l))return false;switch(p){case '[object String]':return k==String(l);case '[object Number]':return isNaN(k)||isNaN(l)?false:k==Number(l);case '[object Date]':case '[object Boolean]':return +k==+l;case '[object RegExp]':return k.source==l.source&&k.global==l.global&&k.multiline==l.multiline&&k.ignoreCase==l.ignoreCase;}var q=m.length;while(q--)if(m[q]==k)return n[q]==l;m.push(k);n.push(l);var r=0;if(p==='[object Array]'){r=k.length;if(r!==l.length)return false;while(r--)if(!g(k[r],l[r],m,n))return false;}else{if(k.constructor!==l.constructor)return false;if(k.hasOwnProperty('valueOf')&&l.hasOwnProperty('valueOf'))return k.valueOf()==l.valueOf();var s=Object.keys(k);if(s.length!=Object.keys(l).length)return false;for(var t=0;t<s.length;t++)if(!g(k[s[t]],l[s[t]],m,n))return false;}m.pop();n.pop();return true;},h=[],i=[],j=function(k,l){var m=h.length?h.pop():[],n=i.length?i.pop():[],o=g(k,l,m,n);m.length=0;n.length=0;h.push(m);i.push(n);return o;};e.exports=j;},null);
__d("computeRelativeURI",["URI","isFacebookURI","isEmpty"],function(a,b,c,d,e,f,g,h,i){function j(l,m){if(!m)return l;if(m.charAt(0)=='/')return m;var n=l.split('/').slice(0,-1);n[0]!=='';m.split('/').forEach(function(o){if(!(o=='.'))if(o=='..'){if(n.length>1)n=n.slice(0,-1);}else n.push(o);});return n.join('/');}function k(l,m){var n=new g(),o=m;l=new g(l);m=new g(m);if(m.getDomain()&&!h(m))return o;var p=l,q=['Protocol','Domain','Port','Path','QueryData','Fragment'];q.forEach(function(r){var s=r=='Path'&&p===l;if(s)n.setPath(j(l.getPath(),m.getPath()));if(!i(m['get'+r]()))p=m;if(!s)n['set'+r](p['get'+r]());});return n;}e.exports=k;},null);
__d("escapeJSQuotes",[],function(a,b,c,d,e,f){function g(h){if(typeof h=='undefined'||h==null||!h.valueOf())return '';return h.toString().replace(/\\/g,'\\\\').replace(/\n/g,'\\n').replace(/\r/g,'\\r').replace(/"/g,'\\x22').replace(/'/g,'\\\'').replace(/</g,'\\x3c').replace(/>/g,'\\x3e').replace(/&/g,'\\x26');}e.exports=g;},null);
__d("PageTransitions",["Arbiter","Bootloader","DOMQuery","DOMScroll","Env","Event","Form","HistoryManager","JSLogger","LayerHideOnEscape","LinkController","ModalLayer","OnloadHooks","Parent","React","URI","UserAgent_DEPRECATED","Vector","areEqual","clickRefAction","computeRelativeURI","copyProperties","escapeJSQuotes","ge","goOrReplace","invariant","isInIframe","setTimeoutAcrossTransitions","startsWith","tx","userAction"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ba,ca,da,ea,fa,ga,ha,ia,ja,ka){var la={};function ma(xa,ya){la[xa.getUnqualifiedURI()]=ya;}function na(xa){return la[xa.getUnqualifiedURI()];}function oa(xa){delete la[xa.getUnqualifiedURI()];}var pa=null,qa=null;function ra(xa){qa=xa;ha(function(){qa=null;},0);}function sa(event){if(qa){if(!event.isDefaultPrevented()){ta(qa);wa.lookBusy(qa);va.go(qa.getAttribute('href'));}event.prevent();}else{pa=event.getTarget();ha(function(){pa=null;},0);}}function ta(xa){var ya=xa.getAttribute('href'),za=aa(va._most_recent_uri.getQualifiedURI(),ya).toString();if(ya!=za)xa.setAttribute('href',za);}function ua(event){var xa=event.getTarget();if(m.getAttribute(xa,'rel')||m.getAttribute(xa,'target'))return;z('form',xa,event).set_namespace('page_transition');var ya=ka('page_transitions',xa,event,{mode:'DEDUP'}).uai_fallback(null,'form'),za=new v(m.getAttribute(xa,'action')||''),ab=aa(va._most_recent_uri,za);xa.setAttribute('action',ab.toString());if((m.getAttribute(xa,'method')||'GET').toUpperCase()==='GET'){var bb=m.serialize(xa),cb=pa;if(cb&&(i.isNodeOfType(cb,'input')&&cb.type==='submit'||(cb=t.byTag(cb,'button')))&&cb.name)bb[cb.name]=cb.value;va.go(ab.addQueryData(bb));event.kill();}}var va={_transition_handlers:[],_completion_callbacks:[],_scroll_locked:false,isInitialized:function(){return !!va._initialized;},_init:function(){if(!k.ALLOW_TRANSITION_IN_IFRAME&&ga())return;if(va._initialized)return va;va._initialized=true;var xa=v.getRequestURI(false),ya=xa.getUnqualifiedURI(),za=v(ya).setFragment(null),ab=ya.getFragment();if(ab.charAt(0)==='!'&&za.toString()===ab.substr(1))ya=za;ba(va,{_current_uri:ya,_most_recent_uri:ya,_next_uri:ya});var bb;if(ia(xa.getFragment(),'/')){bb=xa.getFragment();}else bb=ya;n.init().setCanonicalLocation('#'+bb).registerURIHandler(va._historyManagerHandler);q.registerFallbackHandler(ra);l.listen(document,'click',sa,l.Priority._BUBBLE);l.listen(document,'submit',ua,l.Priority._BUBBLE);l.listen(window,'scroll',function(){if(!va._scroll_locked)ma(va._current_uri,x.getScrollPosition());});return va;},registerHandler:function(xa,ya){va._init();ya=ya||5;if(!va._transition_handlers[ya])va._transition_handlers[ya]=[];va._transition_handlers[ya].push(xa);},removeHandler:function(xa,ya){va._init();ya=ya||5;var za=-1;if(va._transition_handlers[ya])za=va._transition_handlers[ya].indexOf(xa);if(za>-1)va._transition_handlers[ya].splice(za,1);},getCurrentURI:function(xa){if(!va._current_uri&&!xa)return new v(va._most_recent_uri);return new v(va._current_uri);},getMostRecentURI:function(){return new v(va._most_recent_uri);},go:function(xa,ya){var za=new v(xa).removeQueryData('quickling').getQualifiedURI();o.create('pagetransition').debug('go',{uri:za.toString()});oa(za);!ya&&z('uri',{href:za.toString()},null,'INDIRECT');wa.lookBusy();va._loadPage(za,function(ab){if(ab){r.unfixed(function(){n.go(za.toString(),false,ya);});}else ea(window.location,za,ya);});},_historyManagerHandler:function(xa){if(xa.charAt(0)!='/')return false;z('h',{href:xa});ka('page_transitions').uai(null,'history_manager');va._loadPage(new v(xa),function(ya){if(!ya)ea(window.location,xa,true);});return true;},_loadPage:function(xa,ya){if(v(xa).getFragment()&&y(v(xa).setFragment(null).getQualifiedURI(),v(va._current_uri).setFragment(null).getQualifiedURI())){g.inform("pre_page_fragment_transition",{from:v(va._current_uri).getFragment(),to:v(xa).getFragment()});if(va.restoreScrollPosition(xa)){va._current_uri=va._most_recent_uri=xa;wa.stopLookingBusy();g.inform("page_fragment_transition",{fragment:v(xa).getFragment()});return;}}var za;if(va._current_uri)za=na(va._current_uri);var ab=function(){if(za&&va._current_uri)ma(va._current_uri,za);va._current_uri=null;va._next_uri=xa;if(za)j.scrollTo(za,false);va._scroll_locked=true;var db=va._handleTransition(xa);ya&&ya(db);},bb=va._next_uri;va._next_uri=xa;var cb=s.runHooks('onbeforeleavehooks');va._next_uri=bb;if(cb){wa.stopLookingBusy();va._warnBeforeLeaving(cb,ab);}else ab();},_handleTransition:function(xa){window.onbeforeleavehooks=undefined;wa.lookBusy();if(!xa.isSameOrigin())return false;var ya,za=a.AsyncRequest;if(za)ya=za.getLastID();g.inform("pre_page_transition",{from:va.getMostRecentURI(),to:xa});for(var ab=va._transition_handlers.length-1;ab>=0;--ab){var bb=va._transition_handlers[ab];if(!bb)continue;for(var cb=bb.length-1;cb>=0;--cb)if(bb[cb](xa)===true){var db={sender:this,uri:xa,id:ya};try{g.inform("page_transition",db);}catch(eb){}return true;}else bb.splice(cb,1);}return false;},unifyURI:function(){va._current_uri=va._most_recent_uri=va._next_uri;},transitionComplete:function(xa){va._scroll_locked=false;va._executeCompletionCallbacks();wa.stopLookingBusy();va.unifyURI();if(!xa)va.restoreScrollPosition(va._current_uri);try{if(document.activeElement&&document.activeElement.nodeName==='A')document.activeElement.blur();}catch(ya){}},_executeCompletionCallbacks:function(){if(va._completion_callbacks.length>0){var xa=va._completion_callbacks;va._completion_callbacks=[];xa.forEach(function(ya){return ya();});}},registerCompletionCallback:function(xa){va._completion_callbacks.push(xa);},rewriteCurrentURI:function(xa,ya){var za=va._transition_handlers,ab=za.length||1,bb=false;va.registerHandler(function(){if(xa==va.getMostRecentURI().getUnqualifiedURI().toString()){va.transitionComplete();return true;}bb=true;},ab);va.go(ya,true);fa(za.length===ab+1&&za[ab].length===(bb?0:1));za.length=ab;},_warnBeforeLeaving:function(xa,ya){h.loadModules(["DialogX","XUIDialogTitle.react","XUIDialogBody.react","XUIDialogButton.react","XUIDialogFooter.react","XUIGrayText.react"],function(za,ab,bb,cb,db,eb){var fb=new za({width:450,addedBehaviors:[p]},u.createElement("div",null,u.createElement(ab,{showCloseButton:false},"Are You Sure You Want To Leave This Page?"),u.createElement(bb,null,u.createElement(eb,{shade:"medium",size:"medium"},xa)),u.createElement(db,null,u.createElement(cb,{action:"cancel",label:"Stay on This Page"}),u.createElement(cb,{action:"confirm",use:"confirm",label:"Leave This Page"}))));fb.subscribe('confirm',function(){fb.hide();ya();});fb.show();});},restoreScrollPosition:function(xa){var ya=na(xa);if(ya){j.scrollTo(ya,false);return true;}function za(cb){if(!cb)return null;var db="a[name='"+ca(cb)+"']";return i.scry(document.body,db)[0]||da(cb);}var ab=za(v(xa).getFragment());if(ab){var bb=x.getElementPosition(ab);bb.x=0;j.scrollTo(bb);return true;}return false;}},wa=window._BusyUIManager||{_looking_busy:false,_original_cursors:[],lookBusy:function(xa){if(xa)wa._giveProgressCursor(xa);if(wa._looking_busy)return;wa._looking_busy=true;wa._giveProgressCursor(document.documentElement);},stopLookingBusy:function(){if(!wa._looking_busy)return;wa._looking_busy=false;while(wa._original_cursors.length){var xa=wa._original_cursors.pop(),ya=xa[0],za=xa[1];if(ya.style)ya.style.cursor=za||'';}},_giveProgressCursor:function(xa){if(!w.webkit()){wa._original_cursors.push([xa,xa.style.cursor]);xa.style.cursor='progress';}}};e.exports=va;a.PageTransitions=va;},null);
__d("LayerHideOnTransition",["PageTransitions","copyProperties"],function(a,b,c,d,e,f,g,h){function i(j){"use strict";this._layer=j;}i.prototype.enable=function(){"use strict";this._enabled=true;if(!this._subscribed)setTimeout(this._subscribe.bind(this),0);};i.prototype.disable=function(){"use strict";this._enabled=false;};i.prototype._handler=function(){"use strict";if(this._enabled)this._layer.hide();this._subscribe();};i.prototype._subscribe=function(){"use strict";g.registerHandler(this._handler.bind(this));this._subscribed=true;};h(i.prototype,{_enabled:false,_subscribed:false});e.exports=i;},null);
__d("Rect",["Vector","$","copyProperties"],function(a,b,c,d,e,f,g,h,i){function j(k,l,m,n,o){"use strict";if(arguments.length===1){if(k instanceof j)return k;if(k instanceof g)return new j(k.y,k.x,k.y,k.x,k.domain);return j.getElementBounds(h(k));}i(this,{t:k,r:l,b:m,l:n,domain:o||'pure'});}j.prototype.w=function(){"use strict";return this.r-this.l;};j.prototype.h=function(){"use strict";return this.b-this.t;};j.prototype.toString=function(){"use strict";return '(('+this.l+', '+this.t+'), ('+this.r+', '+this.b+'))';};j.prototype.contains=function(k){"use strict";k=new j(k).convertTo(this.domain);var l=this;return (l.l<=k.l&&l.r>=k.r&&l.t<=k.t&&l.b>=k.b);};j.prototype.isEqualTo=function(k){"use strict";return (this.t===k.t&&this.r===k.r&&this.b===k.b&&this.l===k.l&&this.domain===k.domain);};j.prototype.add=function(k,l){"use strict";if(arguments.length==1){if(k.domain!='pure')k=k.convertTo(this.domain);return this.add(k.x,k.y);}var m=parseFloat(k),n=parseFloat(l);return new j(this.t+n,this.r+m,this.b+n,this.l+m,this.domain);};j.prototype.sub=function(k,l){"use strict";if(arguments.length==1){return this.add(k.mul(-1));}else return this.add(-k,-l);};j.prototype.rotateAroundOrigin=function(k){"use strict";var l=this.getCenter().rotate(k*Math.PI/2),m,n;if(k%2){m=this.h();n=this.w();}else{m=this.w();n=this.h();}var o=l.y-n/2,p=l.x-m/2,q=o+n,r=p+m;return new j(o,r,q,p,this.domain);};j.prototype.boundWithin=function(k){"use strict";var l=0,m=0;if(this.l<k.l){l=k.l-this.l;}else if(this.r>k.r)l=k.r-this.r;if(this.t<k.t){m=k.t-this.t;}else if(this.b>k.b)m=k.b-this.b;return this.add(l,m);};j.prototype.getCenter=function(){"use strict";return new g(this.l+this.w()/2,this.t+this.h()/2,this.domain);};j.prototype.getTop=function(){"use strict";return this.t;};j.prototype.getLeft=function(){"use strict";return this.l;};j.prototype.getPositionVector=function(){"use strict";return new g(this.l,this.t,this.domain);};j.prototype.getDimensionVector=function(){"use strict";return new g(this.w(),this.h(),'pure');};j.prototype.convertTo=function(k){"use strict";if(this.domain==k)return this;if(k=='pure')return new j(this.t,this.r,this.b,this.l,'pure');if(this.domain=='pure')return new j(0,0,0,0);var l=new g(this.l,this.t,this.domain).convertTo(k);return new j(l.y,l.x+this.w(),l.y+this.h(),l.x,k);};j.deserialize=function(k){"use strict";var l=k.split(':');return new j(parseFloat(l[1]),parseFloat(l[2]),parseFloat(l[3]),parseFloat(l[0]));};j.newFromVectors=function(k,l){"use strict";return new j(k.y,k.x+l.x,k.y+l.y,k.x,k.domain);};j.getElementBounds=function(k){"use strict";return j.newFromVectors(g.getElementPosition(k),g.getElementDimensions(k));};j.getViewportBounds=function(){"use strict";return j.newFromVectors(g.getScrollPosition(),g.getViewportDimensions());};j.getViewportWithoutScrollbarsBounds=function(){"use strict";return j.newFromVectors(g.getScrollPosition(),g.getViewportWithoutScrollbarDimensions());};j.minimumBoundingBox=function(k){"use strict";var l=new j(Math.min(),Math.max(),Math.max(),Math.min()),m;for(var n=0;n<k.length;n++){m=k[n];l.t=Math.min(l.t,m.t);l.r=Math.max(l.r,m.r);l.b=Math.max(l.b,m.b);l.l=Math.min(l.l,m.l);}return l;};e.exports=j;},null);
__d("SVGChecker",[],function(a,b,c,d,e,f){e.exports={isSVG:function(g){return !!g.ownerSVGElement||g.tagName.toLowerCase()==="svg";},isDisplayed:function(g){try{var i=g.getBBox();if(i&&(i.height===0||i.width===0))return false;}catch(h){return false;}return true;}};},null);
__d("getOverlayZIndex",["Style"],function(a,b,c,d,e,f,g){function h(i,j){j=j||document.body;var k=[];while(i&&i!==j){k.push(i);i=i.parentNode;}if(i!==j)return 0;for(var l=k.length-1;l>=0;l--){var m=k[l];if(g.get(m,'position')!='static'){var n=parseInt(g.get(m,'z-index'),10);if(!isNaN(n))return n;}}return 0;}e.exports=h;},null);
__d("ContextualLayer",["Arbiter","ARIA","ContextualThing","CSS","DataStore","DOM","Event","Layer","LayerHideOnTransition","Locale","Parent","Rect","Style","SVGChecker","Vector","arrayContains","containsNode","copyProperties","emptyFunction","getOffsetParent","getOverlayZIndex","removeFromArray","throttle"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ba,ca){function da(la){return la.getPosition()==='left'||(la.isVertical()&&la.getAlignment()==='right');}for(var ea in n)if(n.hasOwnProperty(ea))ga[ea]=n[ea];var fa=n===null?null:n.prototype;ga.prototype=Object.create(fa);ga.prototype.constructor=ga;ga.__superConstructor__=n;function ga(){"use strict";if(n!==null)n.apply(this,arguments);}ga.prototype._configure=function(la,ma){"use strict";fa._configure.call(this,la,ma);if(la.shouldSetARIAProperties===false)this._shouldSetARIAProperties=la.shouldSetARIAProperties;if(la.context){this.setContext(la.context);}else if(la.contextID){this._setContextID(la.contextID);}else if(la.contextSelector)this._setContextSelector(la.contextSelector);this.setPosition(la.position);this.setAlignment(la.alignment);this.setOffsetX(la.offsetX);this.setOffsetY(la.offsetY);this._content=ma;};ga.prototype._getDefaultBehaviors=function(){"use strict";return fa._getDefaultBehaviors.call(this).concat([o]);};ga.prototype._buildWrapper=function(la,ma){"use strict";this._contentWrapper=l.create('div',{className:'uiContextualLayer'},ma);return l.create('div',{className:'uiContextualLayerPositioner'},this._contentWrapper);};ga.prototype.getInsertParent=function(){"use strict";var la=this._insertParent;if(!la){var ma=this.getContext();if(ma)la=q.byClass(ma,'uiContextualLayerParent');}return la||fa.getInsertParent.call(this);};ga.prototype.setContent=function(la){"use strict";this._content=la;l.setContent(this._contentWrapper,this._content);this._shown&&this.updatePosition();return this;};ga.prototype.setContext=function(la){"use strict";return this.setContextWithBounds(la,null);};ga.prototype.setContextWithBounds=function(la,ma){"use strict";if(this._contextNode===la&&ma&&this._contextBounds&&ma.isEqualTo(this._contextBounds))return this;this._contextNode=la;var na=(ma&&this._contextBounds&&ma.t===this._contextBounds.t&&ma.r===this._contextBounds.r&&ma.b===this._contextBounds.b&&ma.l===this._contextBounds.l);if(na)return this;this._contextBounds=ma||null;this._contextSelector=this._contextScrollParent=null;if(this._shown){i.register(this.getRoot(),this._contextNode);this.updatePosition();}this._setParentSubscription();this.setARIAProperties();return this;};ga.prototype.shouldSetARIAProperties=function(la){"use strict";this._shouldSetARIAProperties=la;return this;};ga.prototype.setARIAProperties=function(){"use strict";if(this._shouldSetARIAProperties)h.setPopup(this.getCausalElement(),this.getRoot());return this;};ga.prototype._setContextID=function(la){"use strict";this._contextSelector='#'+la;this._contextNode=null;};ga.prototype._setContextSelector=function(la){"use strict";this._contextSelector=la;this._contextNode=null;};ga.prototype.getCausalElement=function(){"use strict";return fa.getCausalElement.call(this)||this.getContext();};ga.prototype._setParentSubscription=function(){"use strict";var la=this.getContext(),ma=null;while(la!==null){ma=k.get(la,'layer');if(ma)break;la=la.parentNode;}if(ma===this._parentLayer)return;if(this._parentLayer&&this._parentSubscription){this._parentLayer.unsubscribe(this._parentSubscription);this._parentSubscription=null;}if(ma)this._parentSubscription=ma.subscribe('hide',this.hide.bind(this));this._parentLayer=ma;};ga.prototype.setPosition=function(la){"use strict";if(this._getOrientation().setDefaultPosition(la))this._shown&&this.updatePosition();return this;};ga.prototype.setAlignment=function(la){"use strict";if(this._getOrientation().setDefaultAlignment(la))this._shown&&this.updatePosition();return this;};ga.prototype.setOffsetX=function(la){"use strict";if(this._getOrientation().setDefaultOffsetX(la))this._shown&&this.updatePosition();return this;};ga.prototype.setOffsetY=function(la){"use strict";if(this._getOrientation().setDefaultOffsetY(la))this._shown&&this.updatePosition();return this;};ga.prototype.getPosition=function(){"use strict";return this._getOrientation().getPosition();};ga.prototype._getOrientation=function(){"use strict";if(!this._orientation)this._orientation=new ka();return this._orientation;};ga.prototype.getContentRoot=function(){"use strict";return this._contentWrapper;};ga.prototype.getContent=function(){"use strict";return this._content;};ga.prototype.getContext=function(){"use strict";if(!this._contextNode)this._contextNode=l.find(document,this._contextSelector);return this._contextNode;};ga.prototype.getContextBounds=function(la){"use strict";if(this._contextBounds)return this._contextBounds.convertTo(la);var ma=this.getContext();return r.newFromVectors(u.getElementPosition(ma,la),u.getElementDimensions(ma));};ga.prototype.getContextScrollParent=function(){"use strict";if(!this._contextScrollParent){this._contextScrollParent=s.getScrollParent(this.getContext());}else if(l.isElementNode(this._contextScrollParent)&&!w(document.documentElement,this._contextScrollParent))this._contextScrollParent=s.getScrollParent(this.getContext());return this._contextScrollParent;};ga.prototype.setInsertParent=function(la){"use strict";this._insertScrollParent=null;return fa.setInsertParent.call(this,la);};ga.prototype.getInsertScrollParent=function(){"use strict";if(!this._insertScrollParent)this._insertScrollParent=s.getScrollParent(this.getInsertParent());return this._insertScrollParent;};ga.prototype.show=function(){"use strict";if(this._shown)return this;fa.show.call(this);if(this._shown){i.register(this.getRoot(),this.getContext());ha.push(this);this._resizeListener=this._resizeListener||m.listen(window,'resize',ca(this.updatePosition.bind(this)));}return this;};ga.prototype.finishHide=function(){"use strict";ba(ha,this);this._resizeListener&&this._resizeListener.remove();this._resizeListener=null;return fa.finishHide.call(this);};ga.prototype.isFixed=function(){"use strict";return (s.isFixed(this.getContext())&&!s.isFixed(this.getInsertParent()));};ga.prototype.updatePosition=function(){"use strict";var la=this.getContext();if(!la)return false;var ma=this.isFixed();if(!ma&&!(la.offsetParent||(t.isSVG(la)&&t.isDisplayed(la))))return false;var na=this.getRoot();s.set(na,'width',u.getViewportDimensions().x+'px');var oa=this._getOrientation();this.inform('adjust',oa.reset());if(!oa.isValid())return false;this._updateWrapperPosition(oa);this._updateWrapperClass(oa);j.conditionClass(na,'uiContextualLayerPositionerFixed',ma);var pa,qa,ra=ma?'viewport':'document',sa=ma?document.documentElement:z(na);if(sa===document.documentElement){pa=new u(0,0);qa=document.documentElement.clientWidth;}else if(!na.offsetParent){return false;}else{pa=u.getElementPosition(sa,ra);qa=sa.offsetWidth;if(sa!==document.body)pa=pa.sub(new u(sa.scrollLeft,sa.scrollTop));}var ta=this.getContextBounds(ra),ua=ta.l-pa.x,va=ta.t-pa.y,wa=ta.h(),xa=ta.w(),ya=p.isRTL();if(oa.getPosition()==='below')va+=wa;if((oa.getPosition()==='right'||(oa.isVertical()&&oa.getAlignment()==='right'))!=ya)ua+=xa;var za=oa.getOffsetX();if(oa.isVertical()&&oa.getAlignment()==='center')za+=(xa-this.getContentRoot().offsetWidth)/2;if(ya)za*=-1;var ab='left',bb=Math.floor(ua+za);if(da(oa)!==ya){ab='right';bb=qa-bb;}s.set(na,ab,bb+'px');s.set(na,ab==='left'?'right':'left','');var cb=this.getInsertScrollParent(),db;if(cb!==window){db=cb.clientWidth;}else db=document.documentElement.clientWidth;var eb=u.getElementPosition(na).x;if(ab==='left'&&db-eb>0){s.set(na,'width',(db-eb)+'px');}else if(ab==='right'&&eb+na.offsetWidth>0){s.set(na,'width',eb+na.offsetWidth+'px');}else s.set(na,'width','');s.set(na,'top',(va+oa.getOffsetY())+'px');var fb=aa(la,this.getInsertParent());s.set(na,'z-index',fb>200?fb:'');this.inform('reposition',oa);return true;};ga.prototype._updateWrapperPosition=function(la){"use strict";var ma=la.getPosition()==='above';s.set(this._contentWrapper,'bottom',ma?'0':null);var na=p.isRTL()?'left':'right',oa=da(la);s.set(this._contentWrapper,na,oa?'0':null);};ga.prototype._updateWrapperClass=function(la){"use strict";var ma=la.getClassName();if(ma===this._orientationClass)return;if(this._orientationClass)j.removeClass(this._contentWrapper,this._orientationClass);this._orientationClass=ma;j.addClass(this._contentWrapper,ma);};ga.prototype.simulateOrientation=function(la,ma){"use strict";var na=la.getClassName();if(na===this._orientationClass){return ma();}else{if(this._orientationClass)j.removeClass(this._contentWrapper,this._orientationClass);j.addClass(this._contentWrapper,na);var oa=ma();j.removeClass(this._contentWrapper,na);if(this._orientationClass)j.addClass(this._contentWrapper,this._orientationClass);return oa;}};ga.prototype.destroy=function(){"use strict";fa.destroy.call(this);this._contentWrapper=null;this._content=null;return this;};ga.prototype.getArrowDimensions=function(){"use strict";return this._config.arrowDimensions||{offset:0,length:0};};var ha=[];g.subscribe('reflow',function(){ha.forEach(function(la){if(la.updatePosition()===false)la.hide();});});x(ga.prototype,{_contentWrapper:null,_content:null,_contextNode:null,_contextBounds:null,_contextSelector:null,_parentLayer:null,_parentSubscription:null,_orientation:null,_orientationClass:null,_shouldSetARIAProperties:true});var ia=y.thatReturnsArgument,ja=y.thatReturnsArgument;function ka(){"use strict";this._default={_position:'above',_alignment:'left',_offsetX:0,_offsetY:0,_valid:true};this.reset();}ka.prototype.setPosition=function(la){"use strict";this._position=ia(la);return this;};ka.prototype.setAlignment=function(la){"use strict";this._alignment=ja(la);return this;};ka.prototype.getOppositePosition=function(){"use strict";return ka.OPPOSITE[this.getPosition()];};ka.prototype.invalidate=function(){"use strict";this._valid=false;return this;};ka.prototype.getPosition=function(){"use strict";return this._position||'above';};ka.prototype.getAlignment=function(){"use strict";return this._alignment||'left';};ka.prototype.getOffsetX=function(){"use strict";var la=this._offsetX||0;if(!this.isVertical()){if(this._default._position!==this._position)la*=-1;}else if(this._default._alignment!==this._alignment)la*=-1;return la;};ka.prototype.getOffsetY=function(){"use strict";var la=this._offsetY||0;if(this.isVertical()&&this._default._position!==this._position)la*=-1;return la;};ka.prototype.getClassName=function(){"use strict";var la=this.getAlignment(),ma=this.getPosition();if(ma==='below'){if(la==='left'){return 'uiContextualLayerBelowLeft';}else if(la==='right'){return 'uiContextualLayerBelowRight';}else return 'uiContextualLayerBelowCenter';}else if(ma==='above'){if(la==='left'){return 'uiContextualLayerAboveLeft';}else if(la==='right'){return 'uiContextualLayerAboveRight';}else return 'uiContextualLayerAboveCenter';}else if(ma==='left'){return 'uiContextualLayerLeft';}else return 'uiContextualLayerRight';};ka.prototype.isValid=function(){"use strict";return this._valid;};ka.prototype.isVertical=function(){"use strict";return this.getPosition()==='above'||this.getPosition()==='below';};ka.prototype.reset=function(){"use strict";x(this,this._default);return this;};ka.prototype.setDefaultPosition=function(la){"use strict";var ma=this._default._position;this._default._position=ia(la);return ma!==la;};ka.prototype.setDefaultAlignment=function(la){"use strict";var ma=this._default._alignment;this._default._alignment=ja(la);return ma!==la;};ka.prototype.setDefaultOffsetX=function(la){"use strict";var ma=this._default._offsetX;this._default._offsetX=la;return ma!==la;};ka.prototype.setDefaultOffsetY=function(la){"use strict";var ma=this._default._offsetY;this._default._offsetY=la;return ma!==la;};ka.OPPOSITE={above:'below',below:'above',left:'right',right:'left'};e.exports=ga;},null);
__d("ContextualLayerDimensions",["DOM","Locale","Rect","Vector","ViewportBounds","ge","getOverlayZIndex"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n={getViewportRect:function(o){var p=l('globalContainer'),q=o.getContext(),r=(p&&g.contains(p,q))||m(q)<300,s=i.getViewportWithoutScrollbarsBounds();if(r){s.t+=k.getTop();if(h.isRTL()){s.r-=k.getLeft();s.l+=k.getRight();}else{s.r-=k.getRight();s.l+=k.getLeft();}}return s;},getLayerRect:function(o,p){var q=o.getContextBounds('viewport'),r=o.simulateOrientation(p,function(){return j.getElementDimensions(o.getContentRoot());}),s=q.t+p.getOffsetY();if(p.getPosition()==='above'){s-=r.y;}else if(p.getPosition()==='below')s+=q.b-q.t;var t=q.l+p.getOffsetX(),u=q.r-q.l;if(p.isVertical()){var v=p.getAlignment();if(v==='center'){t+=(u-r.x)/2;}else if((v==='right')!==h.isRTL())t+=u-r.x;}else if((p.getPosition()==='right')!==h.isRTL()){t+=u;}else t-=r.x;return new i(s,t+r.x,s+r.y,t,'viewport');}};e.exports=n;},null);
__d("ContextualLayerAutoFlip",["ContextualLayerDimensions","DOM","Vector","Rect","arrayContains","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k,l){function m(o,p){p=new j(p).convertTo(o.domain);var q=Math.max(o.l,p.l),r=Math.min(o.r,p.r);return Math.max(r-q,0);}function n(o){"use strict";this._layer=o;}n.prototype.enable=function(){"use strict";this._subscription=this._layer.subscribe('adjust',this._adjustOrientation.bind(this));if(this._layer.isShown())this._layer.updatePosition();};n.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;if(this._layer.isShown())this._layer.updatePosition();};n.prototype._adjustOrientation=function(o,p){"use strict";var q=this._getValidPositions(p);if(!q.length){p.invalidate();return;}var r=g.getViewportRect(this._layer),s=this._getValidAlignments(p),t,u,v;for(t=0;t<s.length;t++){p.setAlignment(s[t]);for(u=0;u<q.length;u++){p.setPosition(q[u]);v=g.getLayerRect(this._layer,p);if(r.contains(v))return;}}p.setPosition(k(q,'below')?'below':q[0]);var w,x=0,y=0;for(t=0;t<s.length;t++){p.setAlignment(s[t]);v=g.getLayerRect(this._layer,p);w=m(r,v);if(w>y){y=w;x=t;}}p.setAlignment(s[x]);};n.prototype._getValidPositions=function(o){"use strict";var p=[o.getPosition(),o.getOppositePosition()],q=this._layer.getContextScrollParent();if(q===window||q===h.getDocumentScrollElement())return p;var r=this._layer.getContext(),s=i.getElementPosition(q,'viewport').y,t=i.getElementPosition(r,'viewport').y;if(o.isVertical()){return p.filter(function(v){if(v==='above'){return t>=s;}else{var w=s+q.offsetHeight,x=t+r.offsetHeight;return x<=w;}});}else{var u=s+q.offsetHeight;if(t>=s&&t+r.offsetHeight<=u){return p;}else return [];}};n.prototype._getValidAlignments=function(o){"use strict";var p=['left','right','center'],q=o.getAlignment(),r=p.indexOf(q);if(r>0){p.splice(r,1);p.unshift(q);}return p;};l(n.prototype,{_subscription:null});e.exports=n;},null);
__d("getInlineBoundingRect",["Rect"],function(a,b,c,d,e,f,g){function h(i,j){var k=i.getClientRects();if(!j||k.length===0)return g.getElementBounds(i);var l,m=false;for(var n=0;n<k.length;n++){var o=new g(Math.round(k[n].top),Math.round(k[n].right),Math.round(k[n].bottom),Math.round(k[n].left),'viewport').convertTo('document'),p=o.getPositionVector(),q=p.add(o.getDimensionVector());if(!l||(p.x<=l.l&&p.y>l.t)){if(m)break;l=new g(p.y,q.x,q.y,p.x,'document');}else{l.t=Math.min(l.t,p.y);l.b=Math.max(l.b,q.y);l.r=q.x;}if(o.contains(j))m=true;}if(!l)l=g.getElementBounds(i);return l;}e.exports=h;},null);
__d("Tooltip",["Event","AsyncRequest","ContextualLayer","ContextualLayerAutoFlip","CSS","DataStore","DOM","Style","URI","Vector","copyProperties","emptyFunction","getElementText","getInlineBoundingRect","setImmediate","tx"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){var w=null,x=null,y=null,z=null,aa=null,ba=[],ca=[];function da(){if(!z){aa=m.create('div',{className:'tooltipContent'});var la=m.create('i',{className:'arrow'}),ma=m.create('div',{className:'uiTooltipX'},[aa,la]);z=new i({},ma);z.shouldSetARIAProperties(false);z.enableBehavior(j);}}function ea(la){return q({content:la.getAttribute('aria-label'),position:la.getAttribute('data-tooltip-position')||'above',alignH:la.getAttribute('data-tooltip-alignh')||'left',suppress:false,overflowDisplay:la.getAttribute('data-tooltip-display')==='overflow',persistOnClick:la.getAttribute('data-pitloot-persistonclick')},l.get(la,'tooltip'));}function fa(la,ma){var na=ea(la);l.set(la,'tooltip',{content:ma.content||na.content,position:ma.position||na.position,alignH:ma.alignH||na.alignH,suppress:ma.suppress===undefined?na.suppress:ma.suppress,overflowDisplay:ma.overflowDisplay||na.overflowDisplay,persistOnClick:ma.persistOnClick||na.persistOnClick});la.setAttribute('data-hover','tooltip');}function ga(la,ma){ka.set(la,"Loading...");new h(ma).setHandler(function(na){ka.set(la,na.getPayload());}).setErrorHandler(r).send();}var ha=/(\r\n|[\r\n])/;function ia(la){return la.split(ha).map(function(ma){return ha.test(ma)?m.create('br'):ma;});}var ja;g.listen(document.documentElement,'mouseover',function(event){ja=event;u(function(){ja=null;});});var ka={process:function(la,ma){if(!m.contains(la,ma))return;if(la!==w){var na=la.getAttribute('data-tooltip-uri');if(na){la.removeAttribute('data-tooltip-uri');ga(la,na);}var oa=la.getAttribute('data-tooltip-delay');if(oa){oa=parseInt(oa,10)||1000;ka._showWithDelay(la,oa);}else ka.show(la);}},remove:function(la){l.remove(la,'tooltip');la.removeAttribute('data-hover');la.removeAttribute('data-tooltip-position');la.removeAttribute('data-tooltip-alignh');la===w&&ka.hide();},hide:function(){if(w){z.hide();w=null;while(ba.length)ba.pop().remove();}},set:function(la,ma,na,oa){if(na||oa)fa(la,{position:na,alignH:oa});if(ma instanceof o){if(la===w){ga(la,ma);}else la.setAttribute('data-tooltip-uri',ma);}else{if(m.isTextNode(ma))ma=s(ma);var pa=false;if(typeof ma!=='string'){ma=m.create('div',{},ma);la.setAttribute('aria-label',s(ma));}else{la.setAttribute('aria-label',ma);pa=ma==='';}fa(la,{content:ma,suppress:pa});la===w&&ka.show(la);}},enableDisplayOnOverflow:function(la){la.removeAttribute('data-tooltip-display');fa(la,{overflowDisplay:true});},enablePersistOnClick:function(la){la.removeAttribute('data-pitloot-persistOnClick');fa(la,{persistOnClick:true});},suppress:function(la,ma){fa(la,{suppress:ma});},show:function(la){da();ka.hide();var ma=ea(la);if(ma.suppress)return;var na=ma.content;if(ma.overflowDisplay){if(la.offsetWidth>=la.scrollWidth)return;if(!na)na=s(la);}if(!na)return;var oa=0,pa=0;if(ma.position==='left'||ma.position==='right'){pa=(la.offsetHeight-28)/2;}else if(ma.alignH!=='center'){var qa=la.offsetWidth;if(qa<32)oa=(qa-32)/2*(ma.alignH==='right'?-1:1);}z.setContextWithBounds(la,t(la,ja&&p.getEventPosition(ja))).setOffsetX(oa).setOffsetY(pa).setPosition(ma.position).setAlignment(ma.alignH);if(typeof na==='string'){k.addClass(z.getRoot(),'invisible_elem');var ra=m.create('span',{},ia(na)),sa=m.create('div',{className:'tooltipText'},ra);m.setContent(aa,sa);z.show();var ta;if(sa.getClientRects){var ua=sa.getClientRects()[0];if(ua)ta=Math.round(ua.right-ua.left);}if(!ta)ta=sa.offsetWidth;if(ta<ra.offsetWidth){k.addClass(sa,'tooltipWrap');z.updatePosition();}k.removeClass(z.getRoot(),'invisible_elem');}else{m.setContent(aa,na);z.show();}var va=function(xa){if(!m.contains(w,xa.getTarget()))ka.hide();};ba.push(g.listen(document.documentElement,'mouseover',va),g.listen(document.documentElement,'focusin',va));var wa=n.getScrollParent(la);if(wa!==window)ba.push(g.listen(wa,'scroll',ka.hide));if(!ma.persistOnClick)ba.push(g.listen(la,'click',ka.hide));w=la;},_showWithDelay:function(la,ma){if(la!==x)ka._clearDelay();if(!y){var na=function(oa){if(!m.contains(x,oa.getTarget()))ka._clearDelay();};ca.push(g.listen(document.documentElement,'mouseover',na),g.listen(document.documentElement,'focusin',na));x=la;y=setTimeout(function(){ka._clearDelay();ka.show(la);},ma);}},_clearDelay:function(){clearTimeout(y);x=null;y=null;while(ca.length)ca.pop().remove();}};g.listen(window,'scroll',ka.hide);e.exports=ka;},null);
__d("TooltipMixin",["React","Tooltip","DOM"],function(a,b,c,d,e,f,g,h,i){var j={propTypes:{tooltip:g.PropTypes.oneOfType([g.PropTypes.element,g.PropTypes.string]).isRequired,position:g.PropTypes.oneOf(['above','below','left','right']),alignH:g.PropTypes.oneOf(['left','center','right'])},componentDidMount:function(){this._setTooltip();},componentDidUpdate:function(){this._setTooltip();},_setTooltip:function(){var k=this.props.tooltip;if(typeof k!=='string'){k=i.create('div');g.render(this.props.tooltip,k);}h.set(this.getDOMNode(),k,this.props.position,this.props.alignH);}};e.exports=j;},null);
__d("TooltipLink.react",["React","TooltipMixin"],function(a,b,c,d,e,f,g,h){var i=g.createClass({displayName:'TooltipLink',mixins:[h],render:function(){return g.createElement("a",Object.assign({},this.props),this.props.children);}});e.exports=i;},null);
__d("Image.react-upstream",["React","joinClasses"],function(a,b,c,d,e,f,g,h){function i(k,l,m){var n=k[l];if(typeof n==='string')return;if(n&&typeof n==='object'){if(n.sprited&&n.spriteMapCssClass&&n.spriteCssClass)return;if(!n.sprited&&n.uri)return;}return new Error(("Provided `"+l+"` to `"+m+"`. Must be a string ")+("or `ix` call."));}var j=g.createClass({displayName:'ReactImage',propTypes:{src:i},render:function(){var k=h(this.props.className,'img'),l=this.props.src,m=null;if(this.props.alt&&typeof l!=='string'&&l.sprited)m=g.createElement("u",null,this.props.alt);if(typeof l==='string')return g.createElement("img",Object.assign({},this.props,{className:k}),m);if(l.sprited){k=h(k,l.spriteMapCssClass,l.spriteCssClass);return g.createElement("i",Object.assign({},this.props,{className:k,src:null}),m);}if(this.props.width===undefined&&this.props.height===undefined)return (g.createElement("img",Object.assign({},this.props,{className:k,width:l.width,height:l.height,src:l.uri}),m));return (g.createElement("img",Object.assign({},this.props,{className:k,src:l.uri}),m));}});j.validateImageSrcPropType=i;e.exports=j;},null);
__d("Image.react",["Image.react-upstream"],function(a,b,c,d,e,f,g){e.exports=g;},null);
__d("CloseButton.react",["React","Image.react","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j){var k=g.createClass({displayName:'CloseButton',render:function(){var l=this.props,m=l.size||'medium',n=l.appearance||'normal',o=m==='small',p=m==='huge',q=n==='dark',r=n==='inverted',s=l.ajaxify||null,t=l.rel||null,u=(("uiCloseButton")+(o?' '+"uiCloseButtonSmall":'')+(p?' '+"uiCloseButtonHuge":'')+(o&&q?' '+"uiCloseButtonSmallDark":'')+(o&&r?' '+"uiCloseButtonSmallInverted":'')+(!o&&q?' '+"uiCloseButtonDark":'')+(!o&&r?' '+"uiCloseButtonInverted":''));return (g.createElement("a",Object.assign({},this.props,{ajaxify:s,href:"#",role:"button",'aria-label':l.tooltip,'data-hover':l.tooltip&&'tooltip','data-tooltip-alignh':l.tooltip&&'center',className:j(this.props.className,u),rel:t}),g.createElement(h,{className:"uiCloseButtonHighContrast",src:"/images/chat/tab/close.png"})));}});e.exports=k;},null);
__d("LoadingIndicator.react",["React","Image.react","cx","keyMirror","ix","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m=j({white:true,blue:true,black:true}),n=j({small:true,medium:true,large:true}),o={white:{large:k('/images/loaders/indicator_blue_large.gif'),medium:k('/images/loaders/indicator_blue_medium.gif'),small:k('/images/loaders/indicator_blue_small.gif')},blue:{large:k('/images/loaders/indicator_white_large.gif'),small:k('/images/loaders/indicator_white_small.gif')},black:{large:k('/images/loaders/indicator_black.gif')}},p=g.createClass({displayName:'LoadingIndicator',render:function(){var q=this.props.color,r=this.props.size;if(!o[q])return g.createElement("span",null);if(!o[q][r])return g.createElement("span",null);var s=((this.props.showonasync?"uiLoadingIndicatorAsync":'')),t=o[q][r];return (g.createElement(h,Object.assign({},this.props,{src:t,className:l(this.props.className,s)})));}});p.SIZES=n;p.COLORS=m;e.exports=p;},null);
__d("Timestamp.react",["LiveTimer","joinClasses","React"],function(a,b,c,d,e,f,g,h,i){var j=b('React').PropTypes,k=i.createClass({displayName:'Timestamp',propTypes:{autoUpdate:j.bool},getDefaultProps:function(){return {autoUpdate:false};},componentDidMount:function(){if(this.props.autoUpdate)g.addTimeStamps(this.getDOMNode());},componentDidUpdate:function(l,m){if(this.props.autoUpdate&&this.props.time!==l.time)g.loop();},render:function(){var l=g.renderRelativeTimeToServer(this.props.time,this.props.shorten);return (i.createElement("abbr",Object.assign({},this.props,{className:h(this.props.className,"livetimestamp"),title:this.props.verbose,'data-utime':this.props.time,'data-shorten':this.props.shorten?true:null}),l.text||this.props.text));}});e.exports=k;},null);
__d("cloneWithProps",["ReactElement","ReactPropTransferer","keyOf","warning"],function(a,b,c,d,e,f,g,h,i,j){"use strict";var k=i({children:null});function l(m,n){var o=h.mergeProps(n,m.props);if(!o.hasOwnProperty(k)&&m.props.hasOwnProperty(k))o.children=m.props.children;return g.createElement(m.type,o);}e.exports=l;},null);
__d("AbstractButton.react",["Link.react","React","cloneWithProps","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k){var l=h.createClass({displayName:'AbstractButton',propTypes:{image:h.PropTypes.element,imageRight:h.PropTypes.element,depressed:h.PropTypes.bool,label:h.PropTypes.node},render:function(){var m=(("_42ft")+(this.props.disabled?' '+"_42fr":'')+(this.props.depressed?' '+"_42fs":'')),n,o=this.props.image;if(o){n={};if(this.props.label){n.alt='';n.className="_3-8_";}o=i(o,n);}var p=this.props.imageRight;if(p){n={};if(this.props.label){n.alt='';n.className="_3-99";}p=i(p,n);}var q;if(this.props.href){q=h.createElement(g,Object.assign({},this.props,{className:k(this.props.className,m),disabled:null,label:null}),o,this.props.label,p);}else if(this.props.type&&this.props.type!=='submit'){q=h.createElement("button",Object.assign({},this.props,{className:k(this.props.className,m),label:null,type:this.props.type}),o,this.props.label,p);}else q=h.createElement("button",Object.assign({},this.props,{className:k(this.props.className,m),label:null,type:"submit",value:"1"}),o,this.props.label,p);return q;}});e.exports=l;},null);
__d("XUIButton.react",["AbstractButton.react","ReactPropTypes","React","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k){var l='medium',m=i.createClass({displayName:'XUIButton',statics:{getButtonSize:function(n){return n.size||l;}},propTypes:{use:h.oneOf(['default','special','confirm']),size:h.oneOf(['small','medium','large','xlarge','xxlarge']),borderShade:h.oneOf(['light','dark']),suppressed:h.bool},getDefaultProps:function(){return {use:'default',size:l,borderShade:'light',suppressed:false};},render:function(){var n=this.props.use,o=m.getButtonSize(this.props),p=this.props.borderShade,q=this.props.suppressed,r=(("_4jy0")+(o==='small'?' '+"_517i":'')+(o==='medium'?' '+"_4jy3":'')+(o==='large'?' '+"_4jy4":'')+(o==='xlarge'?' '+"_4jy5":'')+(o==='xxlarge'?' '+"_4jy6":'')+(n==='default'?' '+"_517h":'')+(n==='confirm'?' '+"_4jy1":'')+(n==='special'?' '+"_4jy2":'')+(p==='light'?' '+"_51sy":'')+(p==='dark'?' '+"_9c6":'')+(q?' '+"_59pe":'')+(n==='confirm'||n==='special'?' '+"selected":''));return (i.createElement(g,Object.assign({},this.props,{className:k(this.props.className,r)})));}});e.exports=m;},null);
__d("XUIAbstractGlyphButton.react",["AbstractButton.react","React","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j){var k=h.createClass({displayName:'XUIAbstractGlyphButton',propTypes:{label:h.PropTypes.node},render:function(){return (h.createElement(g,Object.assign({},this.props,{className:j(this.props.className,"_5upp")})));}});e.exports=k;},null);
__d("XUICloseButton.react",["XUIAbstractGlyphButton.react","React","cx","tx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k){var l=h.createClass({displayName:'XUICloseButton',propTypes:{shade:h.PropTypes.oneOf(['light','dark']),size:h.PropTypes.oneOf(['small','medium']),type:h.PropTypes.oneOf(['submit','button','reset'])},getDefaultProps:function(){return {size:'medium',shade:'dark',type:'button'};},render:function(){var m=this.props.size,n=this.props.shade,o=(("_50zy")+(m==='small'?' '+"_50zz":'')+(m==='medium'?' '+"_50-0":'')+(n==='light'?' '+"_50z_":'')+(n==='dark'?' '+"_50z-":'')),p=this.props.label,q=this.props.title;if(!this.props.title&&!this.props.tooltip){if(!p)p="Remove";q=p;}return (h.createElement(g,Object.assign({},this.props,{label:p,title:q,type:this.props.href?null:this.props.type,'aria-label':this.props.tooltip,'data-hover':this.props.tooltip&&'tooltip','data-tooltip-alignh':this.props.tooltip&&'center',className:k(this.props.className,o)})));}});e.exports=l;},null);
__d("XUIText.react",["React","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i){var j=g.PropTypes,k=g.createClass({displayName:'XUIText',propTypes:{size:j.oneOf(['small','medium','large','xlarge','inherit']),weight:j.oneOf(['bold','inherit','normal']),display:j.oneOf(['inline','block'])},getDefaultProps:function(){return {size:'inherit',weight:'inherit',display:'inline'};},render:function(){var l=this.props.size,m=this.props.weight,n=((l==='small'?"_50f3":'')+(l==='medium'?' '+"_50f4":'')+(l==='large'?' '+"_50f5":'')+(l==='xlarge'?' '+"_50f6":'')+(m==='bold'?' '+"_50f7":'')+(m==='normal'?' '+"_5kx5":''));if(this.props.display==='block')return (g.createElement("div",Object.assign({},this.props,{className:i(this.props.className,n)}),this.props.children));return (g.createElement("span",Object.assign({},this.props,{className:i(this.props.className,n)}),this.props.children));}});e.exports=k;},null);
__d("XUIDialogBody.react",["React","cx","joinClasses","XUIText.react"],function(a,b,c,d,e,f,g,h,i,j){var k=g.createClass({displayName:'XUIDialogBody',propTypes:{useCustomPadding:g.PropTypes.bool},render:function(){var l=(("_4-i2")+(!this.props.useCustomPadding?' '+"_57_a":''));return (g.createElement(j,Object.assign({},this.props,{className:i(this.props.className,l),display:"block",size:"medium"}),this.props.children));}});e.exports=k;},null);
__d("XUISpinner.react",["BrowserSupport","ReactPropTypes","React","UserAgent_DEPRECATED","cx","tx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n=g.hasCSSAnimations()&&!j.firefox(),o=i.createClass({displayName:'XUISpinner',propTypes:{paused:h.bool,showOnAsync:h.bool,size:h.oneOf(['small','large']),background:h.oneOf(['light','dark'])},getDefaultProps:function(){return {showOnAsync:false,size:'small',background:'light'};},render:function(){var p=(("img")+(' '+"_55ym")+(this.props.size=='small'?' '+"_55yn":'')+(this.props.size=='large'?' '+"_55yq":'')+(this.props.background=='light'?' '+"_55yo":'')+(this.props.background=='dark'?' '+"_55yp":'')+(this.props.showOnAsync?' '+"_5tqs":'')+(!n?' '+"_5d9-":'')+(n&&this.props.paused?' '+"_2y32":''));return (i.createElement("span",Object.assign({},this.props,{className:m(this.props.className,p),'aria-label':"Loading...",'aria-busy':true})));}});e.exports=o;},null);
__d("BanzaiNectar",["Banzai"],function(a,b,c,d,e,f,g){function h(j){return {log:function(k,l,m){var n={e:l,a:m};g.post('nectar:'+k,n,j);}};}var i=h();i.create=h;e.exports=i;},null);
__d("concatMap",[],function(a,b,c,d,e,f){function g(h,i){var j=-1,k=i.length,l=[],m;while(++j<k){m=h(i[j],j,i);Array.isArray(m)?Array.prototype.push.apply(l,m):Array.prototype.push.call(l,m);}return l;}e.exports=g;},null);
__d("endsWith",[],function(a,b,c,d,e,f){function g(h,i){return h.indexOf(i,h.length-i.length)>-1;}e.exports=g;},null);
__d("extendArray",[],function(a,b,c,d,e,f){function g(h,i){Array.prototype.push.apply(h,i);return h;}e.exports=g;},null);
__d("htmlSpecialChars",[],function(a,b,c,d,e,f){var g=/&/g,h=/</g,i=/>/g,j=/"/g,k=/'/g;function l(m){if(typeof m=='undefined'||m===null||!m.toString)return '';if(m===false){return '0';}else if(m===true)return '1';return m.toString().replace(g,'&').replace(j,'"').replace(k,''').replace(h,'<').replace(i,'>');}e.exports=l;},null);
__d("transformTextRanges",["UnicodeUtils"],function(a,b,c,d,e,f,g){var h=function(i,j,k){if(!i||!j||!k)return i;j.sort(function(r,s){return r.offset-s.offset;});var l=0;for(var m=0;m<j.length;m++){j[m].offset+=l;var n=g.substr(i,j[m].offset,j[m].length),o=g.strlen(n),p=k(n,j[m]),q=g.strlen(p);if(n!==p){i=g.substr(i,0,j[m].offset)+p+g.substr(i,j[m].offset+j[m].length);j[m].length=q;l+=q-o;}}return i;};e.exports=h;},null);
__d("DOMContainer.react",["React","invariant","isNode"],function(a,b,c,d,e,f,g,h,i){var j=g.PropTypes,k=g.createClass({displayName:'DOMContainer',propTypes:{display:j.oneOf(['inline','block'])},getDefaultProps:function(){return {display:'inline'};},getDOMChild:function(){var l=this.props.children;h(i(l));return l;},shouldComponentUpdate:function(l,m){return l.children!==this.props.children;},componentDidMount:function(){this.getDOMNode().appendChild(this.getDOMChild());},componentDidUpdate:function(){var l=this.getDOMNode();while(l.lastChild)l.removeChild(l.lastChild);l.appendChild(this.getDOMChild());},render:function(){if(this.props.display==='block')return g.createElement("div",null);return g.createElement("span",null);}});e.exports=k;},null);
__d("LeftRight.react",["React","ReactChildren","cx","invariant","keyMirror","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m=k({left:true,right:true,both:true});function n(p){j(p&&(p.length===1||p.length===2));}var o=g.createClass({displayName:'LeftRight',render:function(){var p=[];h.forEach(this.props.children,function(x){p.push(x);},this);n(p);var q=this.props.direction||m.both,r=(q===m.both),s=r||q===m.left?"_ohe lfloat":'',t=r||q===m.right?"_ohf rfloat":'',u=g.createElement("div",{key:"left",className:s},p[0]),v=(p.length<2)?null:g.createElement("div",{key:"right",className:t},p[1]),w=(q===m.right&&v)?[v,u]:[u,v];return (g.createElement("div",Object.assign({},this.props,{className:l(this.props.className,"clearfix")}),w));}});o.DIRECTION=m;e.exports=o;},null);
__d("ImageBlock.react",["LeftRight.react","React","cloneWithProps","cx","invariant","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k,l){function m(p){k(p.children&&(p.children.length===2||p.children.length===3));}function n(p){return (("img")+(' '+"_8o")+(p==='small'?' '+"_8r":'')+(p==='medium'?' '+"_8s":'')+(p==='large'?' '+"_8t":''));}var o=h.createClass({displayName:'ImageBlock',render:function(){m(this.props);var p=this.props.children[0],q=this.props.children[1],r=this.props.children[2],s=this.props.spacing||'small';p=i(p,{className:l(n(s),this.props.imageClassName)});var t=l(this.props.contentClassName,(("_42ef")+(s==='small'?' '+"_8u":'')));if(p.type==='img'){if(p.props.alt===undefined)p.props.alt='';}else if((p.type==='a'||p.type==='link')&&p.props.tabIndex===undefined&&p.props.title===undefined&&p.props['aria-label']===undefined){p.props.tabIndex='-1';p.props['aria-hidden']='true';}var u;if(!r){u=h.createElement("div",{className:t},q);}else u=h.createElement(g,{className:t,direction:g.DIRECTION.right},q,r);return (h.createElement(g,Object.assign({},this.props,{direction:g.DIRECTION.left}),p,u));}});e.exports=o;},null);
__d("InlineBlock.react",["React","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i){var j=g.PropTypes,k={baseline:null,bottom:"_6d",middle:"_6b",top:"_6e"},l=g.createClass({displayName:'InlineBlock',propTypes:{alignv:j.oneOf(['baseline','bottom','middle','top']),height:j.number,fullWidth:j.bool},getDefaultProps:function(){return {alignv:'baseline',fullWidth:false};},render:function(){var m=k[this.props.alignv],n="_6a";if(this.props.fullWidth)n=i(n,"_5u5j");var o=i(n,m);if(this.props.height!=null){var p=g.createElement("div",{className:i("_6a",m),style:{height:this.props.height+'px'}});return (g.createElement("div",Object.assign({},this.props,{className:i(this.props.className,n),height:null}),p,g.createElement("div",{className:o},this.props.children)));}else return (g.createElement("div",Object.assign({},this.props,{className:i(this.props.className,o)}),this.props.children));}});e.exports=l;},null);
__d("PhotosMimeType",[],function(a,b,c,d,e,f){function g(h){"use strict";if(this instanceof g===false)return new g(h);this.$PhotosMimeType0=h.split('/');}g.prototype.isImage=function(){"use strict";return this.$PhotosMimeType0[0]==='image';};g.prototype.isJpeg=function(){"use strict";return this.isImage()&&(this.$PhotosMimeType0[1]==='jpeg'||this.$PhotosMimeType0[1]==='pjpeg');};e.exports=g;},null);
__d("DataTransfer",["PhotosMimeType","createArrayFrom","emptyFunction"],function(a,b,c,d,e,f,g,h,i){var j=new RegExp('\u000D\u000A','g'),k='\u000A',l={'text/rtf':1,'text/html':1};function m(o){if(o.kind=='file')return o.getAsFile();}function n(o){"use strict";this.data=o;this.types=o.types?h(o.types):[];}n.prototype.isRichText=function(){"use strict";return this.types.some(function(o){return l[o];});};n.prototype.getText=function(){"use strict";var o;if(this.data.getData)if(!this.types.length){o=this.data.getData('Text');}else if(this.types.indexOf('text/plain')!=-1)o=this.data.getData('text/plain');return o?o.replace(j,k):null;};n.prototype.getHTML=function(){"use strict";if(this.data.getData)if(!this.types.length){return this.data.getData('Text');}else if(this.types.indexOf('text/html')!=-1)return this.data.getData('text/html');};n.prototype.isLink=function(){"use strict";return this.types.some(function(o){return o.indexOf('url')!=-1||o.indexOf('text/uri-list')!=-1;});};n.prototype.isImage=function(){"use strict";var o=this.types.some(function(s){return s.indexOf('application/x-moz-file')!=-1;});if(o)return true;var p=this.getFiles();for(var q=0;q<p.length;q++){var r=p[q].type;if(!g(r).isImage())return false;}return true;};n.prototype.getCount=function(){"use strict";if(this.data.hasOwnProperty('items')){return this.data.items.length;}else if(this.data.hasOwnProperty('mozItemCount')){return this.data.mozItemCount;}else if(this.data.files)return this.data.files.length;return null;};n.prototype.getFiles=function(){"use strict";if(this.data.items){return Array.prototype.slice.call(this.data.items).map(m).filter(i.thatReturnsArgument);}else if(this.data.files){return Array.prototype.slice.call(this.data.files);}else return [];};n.prototype.hasFiles=function(){"use strict";return this.getFiles().length>0;};e.exports=n;},null);
__d("TrackingNodes",["TrackingNodeTypes"],function(a,b,c,d,e,f,g){var h={types:g,BASE_CODE_START:58,BASE_CODE_END:126,BASE_CODE_SIZE:69,PREFIX_CODE_START:42,PREFIX_CODE_END:47,PREFIX_CODE_SIZE:6,TN_URL_PARAM:'__tn__',encodeTN:function(i,j){var k=(i-1)%h.BASE_CODE_SIZE,l=parseInt((i-1)/h.BASE_CODE_SIZE,10);if(i<1||l>h.PREFIX_CODE_SIZE)throw Error('Invalid tracking node: '+i);var m="";if(l>0)m+=String.fromCharCode(l-1+h.PREFIX_CODE_START);m+=String.fromCharCode(k+h.BASE_CODE_START);if(typeof j!="undefined"&&j>0)m+=String.fromCharCode(48+Math.min(j,10)-1);return m;},decodeTN:function(i){if(i.length===0)return [0];var j=i.charCodeAt(0),k=1,l,m;if(j>=h.PREFIX_CODE_START&&j<=h.PREFIX_CODE_END){if(i.length==1)return [0];m=j-h.PREFIX_CODE_START+1;l=i.charCodeAt(1);k=2;}else{m=0;l=j;}if(l<h.BASE_CODE_START||l>h.BASE_CODE_END)return [0];var n=m*h.BASE_CODE_SIZE+(l-h.BASE_CODE_START)+1;if(i.length>k&&(i.charAt(k)>='0'&&i.charAt(k)<='9'))return [k+1,[n,parseInt(i.charAt(k),10)+1]];return [k,[n]];},parseTrackingNodeString:function(i){var j=[];while(i.length>0){var k=h.decodeTN(i);if(k.length==1)return [];j.push(k[1]);i=i.substring(k[0]);}return j;},getTrackingInfo:function(i,j){return '{"tn":"'+h.encodeTN(i,j)+'"}';},addDataAttribute:function(i,j,k){if(j===undefined)return;['data-ft','data-gt'].forEach(function(l){var m;if(i.getAttribute){m=i.getAttribute(l)||"{}";}else if(i.props){m=i.props[l]||"{}";}else return;var n=h.encodeTN(j,k);try{m=JSON.parse(m);if(m.tn&&m.tn===n)return;m.tn=n;if(i.setAttribute){i.setAttribute(l,JSON.stringify(m));}else if(i.props){i.props[l]=JSON.stringify(m);}else return;}catch(o){}});}};e.exports=h;},null);
__d("SubscriptionsHandler",["invariant"],function(a,b,c,d,e,f,g){function h(k){return k.remove||k.reset||k.unsubscribe;}function i(k){var l=h(k);l.call(k);}function j(){"use strict";this._subscriptions=[];}j.prototype.addSubscriptions=function(){"use strict";for(var k=[],l=0,m=arguments.length;l<m;l++)k.push(arguments[l]);k.forEach(function(n){var o=h(n);g(o);});if(this._subscriptions){this._subscriptions=this._subscriptions.concat(k);}else k.forEach(i);};j.prototype.engage=function(){"use strict";this._subscriptions=this._subscriptions||[];};j.prototype.release=function(){"use strict";if(this._subscriptions){this._subscriptions.forEach(i);this._subscriptions=null;}};e.exports=j;},null);
__d("ReactLayer",["React","ReactBrowserEventEmitter","SubscriptionsHandler","emptyFunction","getObjectValues","invariant","merge"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";var n={componentDidMount:function(){this._layerContainer=document.createElement('div');this._renderContentIntoContainer();this.layer=this.createLayer(this._layerContainer);l(this.layer);this.layerSubscriptions=new i();this.layerSubscribe('show',function(){this.props.onToggle&&this.props.onToggle(true);}.bind(this));this.layerSubscribe('hide',function(){this.props.onToggle&&this.props.onToggle(false);}.bind(this));this.layerSubscribe('blur',function(){this.props.onBlur&&this.props.onBlur();}.bind(this));},componentDidUpdate:function(){this._renderContentIntoContainer();this.receiveProps(this.props);},componentWillUnmount:function(){g.unmountComponentAtNode(this._layerContainer);this.layer.destroy();this.layer=null;this._layerContainer=null;this.layerSubscriptions.release();this.layerSubscriptions=null;},_renderContentIntoContainer:function(){g.render(g.createElement("div",null,this.props.children),this._layerContainer);},render:function(){return null;},enumerateBehaviors:function(p){p=this.getEffectiveBehaviors(p);return k(p).filter(j.thatReturnsArgument);},updateBehaviors:function(p){var q=this.getEffectiveBehaviors(this.props.behaviors),r=this.getEffectiveBehaviors(p),s;for(s in q)if(!r[s])this.layer.disableBehavior(q[s]);for(s in r){var t=q[s],u=r[s];if(t&&u){l(t===u);continue;}t&&this.layer.disableBehavior(t);u&&this.layer.enableBehavior(u);}},getEffectiveBehaviors:function(p){if(!this.getDefaultEnabledBehaviors)return p||{};return m(this.getDefaultEnabledBehaviors(),p);},layerSubscribe:function(p,q){var r=this.layer,s=r.subscribe||r.addListener;this.layerSubscriptions.addSubscriptions(s.call(r,p,function(t,u){h.isEnabled()&&q(t,u);}));},getNodeForOwnerRef:function(p){var q=this.getSiblingByRef(p);return q&&q.getDOMNode();}},o={createClass:function(p){return g.createClass({mixins:[n,p]});}};e.exports=o;},null);
__d("ReactLayeredComponentMixin",["ExecutionEnvironment","ReactCurrentOwner","React"],function(a,b,c,d,e,f,g,h,i){"use strict";var j={componentWillMount:function(){if(g.canUseDOM)this._layersContainer=document.createElement('div');},componentDidMount:function(){this._renderLayersIntoContainer();},componentDidUpdate:function(){this._renderLayersIntoContainer();},componentWillUnmount:function(){i.unmountComponentAtNode(this._layersContainer);},_renderLayersIntoContainer:function(){h.current=this;var k=this.renderLayers()||{};h.current=null;i.render(i.createElement("div",null,k),this._layersContainer);}};e.exports=j;},null);
__d("TokenizeUtil",["repeatString"],function(a,b,c,d,e,f,g){var h=/[ ]+/g,i=/[^ ]+/g,j=new RegExp(k(),'g');function k(){return '[.,+*?$|#{}()\'\\^\\-\\[\\]\\\\\\/!@%"~=<>_:;'+'\u30fb\u3001\u3002\u3008-\u3011\u3014-\u301f\uff1a-\uff1f\uff01-\uff0f'+'\uff3b-\uff40\uff5b-\uff65\u2E2E\u061f\u066a-\u066c\u061b\u060c\u060d'+'\uFD3e\uFD3F\u1801\u0964\u104a\u104b\u2010-\u2027\u2030-\u205e'+'\u00a1-\u00b1\u00b4-\u00b8\u00ba\u00bb\u00bf]';}var l={},m={a:"\u0430 \u00e0 \u00e1 \u00e2 \u00e3 \u00e4 \u00e5 \u0101",b:"\u0431",c:"\u0446 \u00e7 \u010d",d:"\u0434 \u00f0 \u010f \u0111",e:"\u044d \u0435 \u00e8 \u00e9 \u00ea \u00eb \u011b \u0113",f:"\u0444",g:"\u0433 \u011f \u0123",h:"\u0445 \u0127",i:"\u0438 \u00ec \u00ed \u00ee \u00ef \u0131 \u012b",j:"\u0439",k:"\u043a \u0138 \u0137",l:"\u043b \u013e \u013a \u0140 \u0142 \u013c",m:"\u043c",n:"\u043d \u00f1 \u0148 \u0149 \u014b \u0146",o:"\u043e \u00f8 \u00f6 \u00f5 \u00f4 \u00f3 \u00f2",p:"\u043f",r:"\u0440 \u0159 \u0155",s:"\u0441 \u015f \u0161 \u017f",t:"\u0442 \u0165 \u0167 \u00fe",u:"\u0443 \u044e \u00fc \u00fb \u00fa \u00f9 \u016f \u016b",v:"\u0432",y:"\u044b \u00ff \u00fd",z:"\u0437 \u017e",ae:"\u00e6",oe:"\u0153",ts:"\u0446",ch:"\u0447",ij:"\u0133",sh:"\u0448",ss:"\u00df",ya:"\u044f"};for(var n in m){var o=m[n].split(' ');for(var p=0;p<o.length;p++)l[o[p]]=n;}var q={};function r(x){return x?x.replace(j,' '):'';}function s(x){x=x.toLowerCase();var y='',z='';for(var aa=x.length;aa--;){z=x.charAt(aa);y=(l[z]||z)+y;}return y.replace(h,' ');}function t(x){var y=[],z=i.exec(x);while(z){z=z[0];y.push(z);z=i.exec(x);}return y;}function u(x,y){if(!q.hasOwnProperty(x)){var z=s(x),aa=r(z);q[x]={value:x,flatValue:z,tokens:t(aa),isPrefixQuery:aa&&aa[aa.length-1]!=' '};}if(y&&typeof q[x].sortedTokens=='undefined'){q[x].sortedTokens=q[x].tokens.slice();q[x].sortedTokens.sort(function(ba,ca){return ca.length-ba.length;});}return q[x];}function v(x,y,z){var aa=u(y,x=='prefix'),ba=x=='prefix'?aa.sortedTokens:aa.tokens,ca=u(z).tokens,da={},ea=aa.isPrefixQuery&&x=='query'?ba.length-1:null,fa=function(ga,ha){for(var ia=0;ia<ca.length;++ia){var ja=ca[ia];if(!da[ia]&&(ja==ga||((x=='query'&&ha===ea||x=='prefix')&&ja.indexOf(ga)===0)))return (da[ia]=true);}return false;};return Boolean(ba.length&&ba.every(fa));}var w={flatten:s,parse:u,getPunctuation:k,isExactMatch:v.bind(null,'exact'),isQueryMatch:v.bind(null,'query'),isPrefixMatch:v.bind(null,'prefix'),tokenize:t};e.exports=w;},null);
__d("isValidUniqueID",[],function(a,b,c,d,e,f){function g(h){return (h!==null&&h!==undefined&&h!==''&&(typeof h==='string'||typeof h==='number'));}e.exports=g;},null);
__d("SearchableEntry",["HTML","isValidUniqueID","invariant"],function(a,b,c,d,e,f,g,h,i){function j(l){switch(typeof l){case 'string':return l;case 'object':var m=g.replaceJSONWrapper(l);if(g.isHTML(m)){var n=m.getRootNode();return n.textContent||n.innerText||'';}else return '';default:return '';}}function k(l){"use strict";i(h(l.uniqueID));i(!!l.title&&typeof l.title==='string');this.$SearchableEntry0=l.uniqueID+'';this.$SearchableEntry1=l.title;this.$SearchableEntry2=l.order||0;this.$SearchableEntry3=j(l.subtitle);this.$SearchableEntry4=l.keywordString||'';this.$SearchableEntry5=l.photo||'';this.$SearchableEntry6=l.uri||'';this.$SearchableEntry7=l.type||'';this.$SearchableEntry8=l.auxiliaryData||null;}k.prototype.getUniqueID=function(){"use strict";return this.$SearchableEntry0;};k.prototype.getOrder=function(){"use strict";return this.$SearchableEntry2;};k.prototype.getTitle=function(){"use strict";return this.$SearchableEntry1;};k.prototype.getSubtitle=function(){"use strict";return this.$SearchableEntry3;};k.prototype.getKeywordString=function(){"use strict";return this.$SearchableEntry4;};k.prototype.getPhoto=function(){"use strict";return this.$SearchableEntry5;};k.prototype.getURI=function(){"use strict";return this.$SearchableEntry6;};k.prototype.getType=function(){"use strict";return this.$SearchableEntry7;};k.prototype.getAuxiliaryData=function(){"use strict";return this.$SearchableEntry8;};e.exports=k;},null);
__d("TypeaheadNavigation",[],function(a,b,c,d,e,f){var g={moveUp:function(h,i,j){var k=h.indexOf(i),l=k==-1?h.length-1:k-1;j(l==-1?null:h[l]);},moveDown:function(h,i,j){var k=h.indexOf(i)+1;j(k==h.length?null:h[k]);}};e.exports=g;},null);
__d("TypeaheadViewItem",["React","SearchableEntry"],function(a,b,c,d,e,f,g,h){var i={entry:g.PropTypes.instanceOf(h).isRequired,highlighted:g.PropTypes.bool,role:g.PropTypes.string,selected:g.PropTypes.bool,onSelect:g.PropTypes.func.isRequired,onHighlight:g.PropTypes.func,onRenderHighlight:g.PropTypes.func},j={_onSelect:function(k){this.props.onSelect(this.props.entry,k);},_onHighlight:function(k){if(this.props.onHighlight)this.props.onHighlight(this.props.entry,k);},getDefaultProps:function(){return {role:'option'};},shouldComponentUpdate:function(k){return (this.props.entry.getUniqueID()!==k.entry.getUniqueID()||this.props.highlighted!==k.highlighted||this.props.selected!==k.selected);},componentDidMount:function(){if(this.props.highlighted&&this.props.onRenderHighlight)this.props.onRenderHighlight(this.getDOMNode());},componentDidUpdate:function(){if(this.props.highlighted&&this.props.onRenderHighlight)this.props.onRenderHighlight(this.getDOMNode());}};e.exports={propTypes:i,Mixin:j};},null);
__d("UnicodeBidi",["Locale","UnicodeBidiDirection"],function(a,b,c,d,e,f,g,h){"use strict";var i={L:'A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF'+'\u200E\u2C00-\uD7FF\uE000-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF',R:'\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05F0-\u05F2\u05F3-\u05F4'+'\u07C0-\u07C9\u07CA-\u07EA\u07F4-\u07F5\u07FA\u0800-\u0815\u081A\u0824'+'\u0828\u0830-\u083E\u0840-\u0858\u085E\u200F\uFB1D\uFB1F-\uFB28'+'\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40-\uFB41\uFB43-\uFB44\uFB46-\uFB4F',AL:'\u0608\u060B\u060D\u061B\u061C\u061E-\u061F\u0620-\u063F\u0640'+'\u0641-\u064A\u066D\u066E-\u066F\u0671-\u06D3\u06D4\u06D5\u06E5-\u06E6'+'\u06EE-\u06EF\u06FA-\u06FC\u06FD-\u06FE\u06FF\u0700-\u070D\u070F\u0710'+'\u0712-\u072F\u074D-\u07A5\u07B1\u08A0\u08A2-\u08AC\uFB50-\uFBB1'+'\uFBB2-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB'+'\uFDFC\uFE70-\uFE74\uFE76-\uFEFC'},j=i.L+i.R+i.AL,k=i.R+i.AL,l=new RegExp('['+j+']'),m=new RegExp('['+k+']');function n(t){var u=l.exec(t);if(!u)return h.NEUTRAL;var v=m.exec(u[0]);return v?h.RTL:h.LTR;}function o(t,u){u=u||h.NEUTRAL;if(!t.length)return u;var v=n(t);return (v===h.NEUTRAL)?u:v;}function p(t,u){if(!u||!h.isStrong(u))u=g.getDirection();return o(t,u);}function q(t,u){return p(t,u)===h.LTR;}function r(t,u){return p(t,u)===h.RTL;}var s={firstStrongCharDir:n,resolveBlockDir:o,getDirection:p,isDirectionLTR:q,isDirectionRTL:r};e.exports=s;},null);
__d("UnicodeCJK",[],function(a,b,c,d,e,f){"use strict";var g='a-zA-Z',h='\uFF21-\uFF3A\uFF41-\uFF5A',i=g+h,j='\u3040-\u309F',k='\u30A0-\u30FF',l='\u31F0-\u31FF',m='\uFF65-\uFF9F',n=k+l+m,o=j+n,p=[12352,12447],q=[12448,12543],r=q[0]-p[0],s='\u4E00-\u9FCF',t='\u3400-\u4DBF',u=s+t,v='\uAC00-\uD7AF',w=u+o+v,x=null,y=null,z=null,aa=null;function ba(ja){y=y||new RegExp('['+o+']');return y.test(ja);}function ca(ja){x=x||new RegExp('['+u+']');return x.test(ja);}function da(ja){z=z||new RegExp('['+w+']');return z.test(ja);}function ea(ja){var ka=ja.charCodeAt(0);return String.fromCharCode((ka<p[0]||ka>p[1])?ka:ka+r);}function fa(ja){if(!ba(ja))return ja;return ja.split('').map(ea).join('');}function ga(ja){aa=aa||new RegExp('^'+'['+o+']+'+'['+i+']'+'$');return aa.test(ja);}function ha(ja){if(ga(ja))return ja.substr(0,ja.length-1);return ja;}var ia={hasKana:ba,hasIdeograph:ca,hasIdeoOrSyll:da,hiraganaToKatakana:fa,isKanaWithTrailingLatin:ga,kanaRemoveTrailingLatin:ha};e.exports=ia;},null);
__d("UnicodeHangulKorean",[],function(a,b,c,d,e,f){"use strict";var g=/[\u3130-\u318F\uAC00-\uD7AF]/;function h(aa){return g.test(aa);}var i=[4352,4353,4522,4354,4524,4525,4355,4356,4357,4528,4529,4530,4531,4532,4533,4378,4358,4359,4360,4385,4361,4362,4363,4364,4365,4366,4367,4368,4369,4370,4449,4450,4451,4452,4453,4454,4455,4456,4457,4458,4459,4460,4461,4462,4463,4464,4465,4466,4467,4468,4469,4448,4372,4373,4551,4552,4556,4558,4563,4567,4569,4380,4573,4575,4381,4382,4384,4386,4387,4391,4393,4395,4396,4397,4398,4399,4402,4406,4416,4423,4428,4593,4594,4439,4440,4441,4484,4485,4488,4497,4498,4500,4510,4513],j=12593,k=i.length,l=j+k;function m(aa){return String.fromCharCode(i[aa-j]);}var n=4352,o=4449,p=4519,q=44032,r=19,s=21,t=28,u=(s*t),v=(r*u),w=q+v;function x(aa){var ba=aa-q,ca=ba%t;return String.fromCharCode(n+ba/u)+String.fromCharCode(o+(ba%u)/t)+((ca>0)?String.fromCharCode(p+ca):'');}function y(aa){if(!h(aa))return aa;var ba=[];for(var ca=0;ca<aa.length;ca++){var da=aa.charAt(ca),ea=da.charCodeAt(0);ba.push((j<=ea&&ea<l)?m(ea):(q<=ea&&ea<w)?x(ea):da);}return ba.join('');}var z={toConjoiningJamo:y};e.exports=z;},null);
__d("UnicodeMatch",["UnicodeHangulKorean","UnicodeCJK","invariant","createObjectFrom","mapObject","startsWith"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";var m=['prefix_hangul_conjoining_jamo','prefix_kana_drop_trailing_latin','prefix_kana_hiragana_to_katakana'];function n(o){this.config=j(m,false);this.setConfigs(o||{});}n.prototype.setConfigs=function(o){k(o,function(p,q){return this.setConfig(q,p);}.bind(this),this);};n.prototype.setConfig=function(o,p){i(o in this.config);this.config[o]=p;};n.prototype.prefixMatchPrepare=function(o){if(o){if(this.config.prefix_hangul_conjoining_jamo)o=g.toConjoiningJamo(o);if(this.config.prefix_kana_drop_trailing_latin)o=h.kanaRemoveTrailingLatin(o);if(this.config.prefix_kana_hiragana_to_katakana)o=h.hiraganaToKatakana(o);}return o;};n.prototype.prefixMatch=function(o,p){o=this.prefixMatchPrepare(o);p=this.prefixMatchPrepare(p);return l(o,p);};e.exports=n;},null);
__d("NavigationMessage",[],function(a,b,c,d,e,f){var g={NAVIGATION_BEGIN:'NavigationMessage/navigationBegin',NAVIGATION_SELECT:'NavigationMessage/navigationSelect',NAVIGATION_FIRST_RESPONSE:'NavigationMessage/navigationFirstResponse',NAVIGATION_COMPLETED:'NavigationMessage/navigationCompleted',NAVIGATION_FAILED:'NavigationMessage/navigationFailed',NAVIGATION_COUNT_UPDATE:'NavigationMessage/navigationCount',NAVIGATION_FAVORITE_UPDATE:'NavigationMessage/navigationFavoriteUpdate',NAVIGATION_ITEM_REMOVED:'NavigationMessage/navigationItemRemoved',NAVIGATION_ITEM_HIDDEN:'NavigationMessage/navigationItemHidden',INTERNAL_LOADING_BEGIN:'NavigationMessage/internalLoadingBegin',INTERNAL_LOADING_COMPLETED:'NavigationMessage/internalLoadingCompleted'};e.exports=g;},null);
__d("isRTL",["UnicodeBidi","UnicodeBidiDirection"],function(a,b,c,d,e,f,g,h){function i(j){return g.getDirection(j)===h.RTL;}e.exports=i;},null);
__d("LitestandStoryInsertionStatus",["ArbiterMixin","copyProperties"],function(a,b,c,d,e,f,g,h){var i='check',j={registerBlocker:function(k){return j.subscribe(i,function(l,m){if(m.can_insert&&k())m.can_insert=false;});},canInsert:function(){var k={can_insert:true};j.inform(i,k);return k.can_insert;}};h(j,g);e.exports=j;},null);
__d("LitestandClassicRHC",["Arbiter","BigPipe","CSS","DOMQuery","NavigationMessage","Run","SubscriptionsHandler","cx"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){var o="_268y";function p(r,s){var t=new m(),u=t.release.bind(t),v=j.scry(r,'.pagelet'),w=v.length;t.addSubscriptions(s.subscribe([].map.call(v,function(x){return x.id+'_displayed';}),function(){i.removeClass(r,o);if(--w===0){g.inform('LitestandClassicRHC/loaded');u();}}),g.subscribe(k.NAVIGATION_BEGIN,u),s.subscribeOnce('pagelet_displayed_all',function(){g.inform('LitestandClassicRHC/loaded');i.removeClass(r,o);u();}));l.onLeave(u);}var q={init:function(r){var s=h.getCurrentInstance();if(s&&s.arbiter){p(r,s.arbiter);}else g.subscribeOnce('BigPipe/init',function(event,t){p(r,t.arbiter);},g.SUBSCRIBE_NEW);}};e.exports=q;},null);
__d("MercuryLoggingHelper",["merge"],function(a,b,c,d,e,f,g){var h={obfuscateAction:function(i){if(i&&i.body&&i.body.length>5)i.body=i.body.substr(0,5)+"...";return i;},obfuscateThread:function(i){if(i&&i.snippet&&i.snippet.length>5)i.snippet=i.snippet.substr(0,5)+"...";return i;},obfuscateMessage:function(i){var j=g(i);if(i&&i.body&&i.body.length>5)j.body=i.body.substr(0,5)+'...';return j;}};e.exports=h;},null);
__d("MercuryServerDispatcher",["AsyncRequest","CurrentUser","Env","FBAjaxRequest","LogHistory","MercuryLoggingHelper","areJSONRepresentationsEqual","copyProperties","debounceAcrossTransitions"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){var p={},q=k.getInstance('mercury_dispatcher'),r=false,s={IMMEDIATE:'immediate',IDEMPOTENT:'idempotent',BATCH_SUCCESSIVE:'batch-successive',BATCH_SUCCESSIVE_UNIQUE:'batch-successive-unique',BATCH_SUCCESSIVE_PIGGYBACK_ON_ERROR:'batch-successive-piggyback-retry',BATCH_DEFERRED_MULTI:'batch-deferred-multi',BATCH_CONDITIONAL:'batch-conditional',DEFAULT_ENDPOINT_ID:'mercuryServerDispatcherDefaultEndpointID',registerEndpoints:function(v){for(var w in v){var x=v[w],y=x.request_user_id||h.getID(),z=x.endpoint_id||s.DEFAULT_ENDPOINT_ID;if(!p[w])p[w]={};if(!p[w][y])p[w][y]={};p[w][y][z]=new t(w,x);}},trySend:function(v,w,x,y,z){y=y||h.getID();z=z||s.DEFAULT_ENDPOINT_ID;p[v][y][z].trySend(w,x);}};function t(v,w){var x=w.mode||s.IMMEDIATE;switch(x){case s.IMMEDIATE:case s.IDEMPOTENT:case s.BATCH_SUCCESSIVE:case s.BATCH_SUCCESSIVE_UNIQUE:case s.BATCH_SUCCESSIVE_PIGGYBACK_ON_ERROR:case s.BATCH_DEFERRED_MULTI:case s.BATCH_CONDITIONAL:break;default:throw new Error('Invalid MercuryServerDispatcher mode '+x);}this._endpoint=v;this._mode=x;this._requestUserID=w.request_user_id;this._combineData=w.batch_function;this._combineDataIf=w.batch_if;this._batchSizeLimit=w.batch_size_limit;this._batches=[];this._handler=w.handler;this._errorHandler=w.error_handler;this._transportErrorHandler=w.transport_error_handler||w.error_handler;this._connectionRetries=w.connection_retries||0;this._timeoutHandler=w.timeout_handler;this._timeout=w.timeout;this._serverDialogCancelHandler=w.server_dialog_cancel_handler||w.error_handler;this._sendAttemptLoggingHandler=w.send_attempt_logging_handler;this._deferredSend=o(this._batchSend,0,this);}n(t.prototype,{_inFlight:0,_handler:null,_errorHandler:null,_transportErrorHandler:null,_timeoutHandler:null,_timeout:null,_serverDialogCancelHandler:null,_combineData:null,_sendAttemptLoggingHandler:null,trySend:function(v,w){if(r)return;if(typeof v=='undefined')v=null;var x=w||this._mode;if(x==s.IMMEDIATE){this._send(v);}else if(x==s.IDEMPOTENT){if(!this._inFlight)this._send(v);}else if(x==s.BATCH_SUCCESSIVE||x==s.BATCH_SUCCESSIVE_UNIQUE){if(!this._inFlight){this._send(v);}else this._batchData(v);}else if(x==s.BATCH_CONDITIONAL){var y=this._batches[0]&&this._batches[0].getData();if(this._inFlight&&(this._combineDataIf(this._pendingRequestData,v)||this._combineDataIf(y,v))){this._batchData(v);}else this._send(v);}else if(x==s.BATCH_DEFERRED_MULTI){this._batchData(v);this._deferredSend();}else if(x==s.BATCH_SUCCESSIVE_PIGGYBACK_ON_ERROR){this._batchData(v);if(!this._inFlight)this._batchSend();}},_send:function(v){this._inFlight++;this._pendingRequestData=n({},v);if(this._requestUserID!=h.getID())v.request_user_id=this._requestUserID;var w=[];if(v&&v.message_batch)for(var x=0;x<v.message_batch.length;x++){var y=n({},v.message_batch[x]);l.obfuscateAction(y);w.push(y);}var z=w.length?n({},v,{message_batch:w}):v;q.log('send',{endpoint:this._endpoint,data:z,inflight_count:this._inFlight});var aa=null;if(i.worker_context){aa=new j('POST',this._endpoint,v);aa.onError=function(ba){ba.getPayload=function(){return ba.errorText;};ba.getRequest=function(){var ca=ba;ba.getData=function(){return v;};return ca;};ba.getError=function(){return ba.errorText;};ba.getErrorDescription=function(){return ba.errorText;};ba.isTransient=function(){return false;};this._handleError(ba);}.bind(this);aa.onJSON=function(ba){ba.getPayload=function(){return ba.json;};ba.getRequest=function(){return aa;};this._handleResponse(ba);}.bind(this);aa.getData=function(){return v;};aa.send();}else{aa=new g(this._endpoint).setData(v).setOption('retries',this._connectionRetries).setHandler(this._handleResponse.bind(this)).setErrorHandler(this._handleError.bind(this)).setTransportErrorHandler(this._handleTransportError.bind(this)).setServerDialogCancelHandler(this._handleServerDialogCancel.bind(this)).setAllowCrossPageTransition(true);if(this._timeout&&this._timeoutHandler)aa.setTimeoutHandler(this._timeout,this._handleTimeout.bind(this));aa.send();}if(this._sendAttemptLoggingHandler&&v&&v.message_batch)v.message_batch.map(function(ba){return this._sendAttemptLoggingHandler(ba);}.bind(this));},_batchData:function(v,w){if(this._mode==s.BATCH_SUCCESSIVE_UNIQUE&&typeof this._pendingRequestData!='undefined'&&m(v,this._pendingRequestData)){return;}else{var x=this._batches.length-1;if(x>=0&&!this._hasReachedBatchLimit(this._batches[x])){w?this._batches[x].combineWithOlder(v,this._combineData):this._batches[x].combineWith(v,this._combineData);}else this._batches.push(new u(v));q.debug('batch',{endpoint:this._endpoint,batches:this._batches,batch_limit:this._batchSizeLimit});}},_hasReachedBatchLimit:function(v){return this._batchSizeLimit&&v.getSize()>=this._batchSizeLimit;},_batchSend:function(){if(this._batches[0]){this._send(this._batches[0].getData());this._batches.shift();}},_handleResponse:function(v){this._inFlight--;q.log('response',{endpoint:this._endpoint,inflight_count:this._inFlight});var w=v.getPayload();r=w&&w.kill_chat;if(r)q.log('killswitch_enabled',{endpoint:this._endpoint,inflight_count:this._inFlight});if(w&&w.error_payload){if(this._errorHandler)this._errorHandler(v);}else this._handler&&this._handler(w,v.getRequest());if(this._mode==s.BATCH_SUCCESSIVE||this._mode==s.BATCH_SUCCESSIVE_UNIQUE||this._mode==s.BATCH_SUCCESSIVE_PIGGYBACK_ON_ERROR||this._mode==s.BATCH_CONDITIONAL)this._batchSend();delete this._pendingRequestData;},_postErrorHandler:function(){q.error('error',{endpoint:this._endpoint,inflight_count:this._inFlight-1});this._inFlight--;var v=this._mode;if(v==s.BATCH_SUCCESSIVE||v==s.BATCH_SUCCESSIVE_UNIQUE||v==s.BATCH_CONDITIONAL){this._batchSend();}else if(v==s.BATCH_SUCCESSIVE_PIGGYBACK_ON_ERROR)if(this._batches[0]){this._batchData(this._pendingRequestData,true);this._batchSend();}else this._batchData(this._pendingRequestData,true);delete this._pendingRequestData;},_handleError:function(v){this._errorHandler&&this._errorHandler(v);this._postErrorHandler();},_handleTransportError:function(v){this._transportErrorHandler&&this._transportErrorHandler(v);this._postErrorHandler();},_handleTimeout:function(v){this._timeoutHandler&&this._timeoutHandler(v);this._postErrorHandler();},_handleServerDialogCancel:function(v){this._serverDialogCancelHandler&&this._serverDialogCancelHandler(v);this._postErrorHandler();}});function u(v){this._data=v;this._size=1;}n(u.prototype,{getData:function(){return this._data;},getSize:function(){return this._size;},combineWith:function(v,w){this._data=w(this._data,v);this._size++;},combineWithOlder:function(v,w){this._data=w(v,this._data);this._size++;}});e.exports=s;},null);
__d("DataSource",["ArbiterMixin","AsyncRequest","TokenizeUtil","UnicodeMatch","copyProperties","createArrayFrom","createObjectFrom","emptyFunction","mixin"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){var p=o(g);for(var q in p)if(p.hasOwnProperty(q))s[q]=p[q];var r=p===null?null:p.prototype;s.prototype=Object.create(r);s.prototype.constructor=s;s.__superConstructor__=p;function s(t){"use strict";this._maxResults=t.maxResults||10;this.token=t.token;this.queryData=t.queryData||{};this.queryEndpoint=t.queryEndpoint||'';this.bootstrapData=t.bootstrapData||{};this.bootstrapEndpoint=t.bootstrapEndpoint||'';this._indexedFields=t.indexedFields||['text','tokens'];this._titleFields=t.titleFields||[];this._alwaysPrefixMatch=t.alwaysPrefixMatch||false;this._deduplicationKey=t.deduplicationKey||null;this._enabledLocalCache=(t.enabledLocalCache!=null)?t.enabledLocalCache:true;this._enabledQueryCache=(t.enabledQueryCache!=null)?t.enabledQueryCache:true;this._disableAllCaches=(t.disableAllCaches!=null)?t.disableAllCaches:false;this._enabledMergeUids=(t.enabledMergeUids!=null)?t.enabledMergeUids:false;this._queryExactMatch=t.queryExactMatch||false;this._acrossTransitions=t.acrossTransitions||false;this._minQueryLength=t.minQueryLength||-1;this._minExactMatchLength=4;this._filters=[];this.setExclusions(t.exclusions);this.backendUnicodeMatch=new j({prefix_kana_hiragana_to_katakana:!!t.kanaNormalization});this.cacheUnicodeMatch=new j({prefix_kana_hiragana_to_katakana:!!t.kanaNormalization});}s.prototype.init=function(){"use strict";this.init=n;this._fields=m(this._indexedFields);this._activeQueries=0;this.dirty();};s.prototype.dirty=function(){"use strict";this.value='';this._bootstrapped=false;this._bootstrapping=false;this._data={};this.localCache={};this.queryCache={};this.queryIDs={};this.inform('dirty',{});return this;};s.prototype.bootstrap=function(){"use strict";if(this._bootstrapped)return;this.bootstrapWithoutToken();this._bootstrapped=true;this._bootstrapping=true;this.inform('bootstrap',{bootstrapping:true});};s.prototype.bootstrapWithoutToken=function(){"use strict";this.fetch(this.bootstrapEndpoint,this.bootstrapData,{bootstrap:true,token:this.token});};s.prototype.bootstrapWithToken=function(){"use strict";var t=k({},this.bootstrapData);t.token=this.token;this.fetch(this.bootstrapEndpoint,t,{bootstrap:true,replaceCache:true,value:''});};s.prototype.query=function(t,u,v,w){"use strict";this.inform('beforeQuery',{value:t,local_only:u,exclusions:v,time_waited:w});if(this._disableAllCaches){this.dirty();if(!t){this.bootstrap();return true;}}else if(!this._enabledQueryCache){this.queryCache={};this.queryIDs={};}var x=this.buildUids(t,[],v),y=this.respond(t,x);this.value=t;this.inform('query',{value:t,results:y});var z=this.tokenizeBackend(t).flatValue;if(u||!z||this._isQueryTooShort(z)||!this.queryEndpoint||this.getQueryCache().hasOwnProperty(z)||!this.shouldFetchMoreResults(y))return false;this.inform('queryEndpoint',{value:t});this.fetch(this.queryEndpoint,this.getQueryData(t,x),{value:t,exclusions:v});return true;};s.prototype._isQueryTooShort=function(t){"use strict";return (t.length<this._minQueryLength);};s.prototype._tokenize=function(t,u){"use strict";return i.parse(t,u);};s.prototype.tokenizeBackend=function(t,u){"use strict";t=this.backendUnicodeMatch.prefixMatchPrepare(t);return this._tokenize(t,u);};s.prototype.tokenizeCache=function(t,u){"use strict";t=this.cacheUnicodeMatch.prefixMatchPrepare(t);return this._tokenize(t,u);};s.prototype.shouldFetchMoreResults=function(t){"use strict";return t.length<this._maxResults;};s.prototype.getQueryData=function(t,u){"use strict";var v=k({value:t},this.queryData||{});u=u||[];if(u.length)v.existing_ids=u.join(',');if(this._bootstrapping)v.bsp=true;return v;};s.prototype.setQueryData=function(t,u){"use strict";if(u)this.queryData={};k(this.queryData,t);return this;};s.prototype.setBootstrapData=function(t,u){"use strict";if(u)this.bootstrapData={};k(this.bootstrapData,t);return this;};s.prototype.getExclusions=function(){"use strict";return l(this._exclusions);};s.prototype.setExclusions=function(t){"use strict";this._exclusions=t?t.map(String):[];};s.prototype.addFilter=function(t){"use strict";var u=this._filters;u.push(t);return {remove:function(){u.splice(u.indexOf(t),1);}};};s.prototype.clearFilters=function(){"use strict";this._filters=[];};s.prototype.notify=function(t,u,v,w){"use strict";var x=this.buildData(u);this.inform('notify',{value:t,results:x,isAsync:!!v,rootid:w});return x;};s.prototype.respond=function(t,u,v){"use strict";var w=this.buildData(u);this.inform('respond',{value:t,results:w,isAsync:!!v});return w;};s.prototype.respondWithResults=function(t,u,v){"use strict";this.inform('respond',{value:t,results:u,isAsync:!!v});return u;};s.prototype.fetch=function(t,u,v){"use strict";if(!t)return;if(u.request_id===undefined){u.request_id=this._guid();v.request_id=u.request_id;}var w=new h().setURI(t).setData(u).setMethod('GET').setReadOnly(true).setAllowCrossPageTransition(this._acrossTransitions).setHandler(function(x){this.fetchHandler(x,v||{});}.bind(this));if(t===this.queryEndpoint)w.setFinallyHandler(function(){this._activeQueries--;if(!this._activeQueries)this.inform('activity',{activity:false});}.bind(this));w.setErrorHandler(this.asyncErrorHandler);this.inform('beforeFetch',{request:w,fetch_context:v});w.send();if(t===this.queryEndpoint){if(!this._activeQueries)this.inform('activity',{activity:true});this._activeQueries++;}};s.prototype.fetchHandler=function(t,u){"use strict";var v=u.value,w=u.exclusions;if(t.getPayload().requestID!==undefined)u.request_id=t.getPayload().requestID;var x=this.getQueryIDs(),y=this.tokenizeBackend(v||'').flatValue;x[y]=u.request_id;if(!v&&u.replaceCache)this.localCache={};this.inform('buildQueryCache',{});var z=t.getPayload().entries;this.addEntries(z,v);this.inform('fetchComplete',{entries:z,response:t,value:v,fetch_context:u});var aa=(!v&&this.value)?this.value:v;this.respond(aa,this.buildUids(aa,[],w),true);if(!v){if(this._bootstrapping){this._bootstrapping=false;this.inform('bootstrap',{bootstrapping:false});}if(u.token&&t.getPayload().token!==u.token)this.bootstrapWithToken();}};s.prototype.addEntries=function(t,u){"use strict";var v=this.processEntries(l(t||[]),u),w=v;if(this._enabledMergeUids)w=this.buildUids(u,v);if(u){var x=this.getQueryCache(),y=this.tokenizeBackend(u).flatValue;x[y]=w;}else this.fillCache(w);};s.prototype.processEntries=function(t,u){"use strict";return t.map(function(v,w){var x=(v.uid=v.uid+''),y=this.getEntry(x);if(!y){y=v;y.query=u;y.bootstrapped=!u;this.setEntry(x,y);}else k(y,v);y.index===undefined&&(y.index=w);return x;},this);};s.prototype.getAllEntries=function(){"use strict";return this._data||{};};s.prototype.getEntry=function(t){"use strict";return this._data[t]||null;};s.prototype.setEntry=function(t,u){"use strict";this._data[t]=u;};s.prototype.fillCache=function(t){"use strict";if(!this._enabledLocalCache)return;var u=this.localCache;t.forEach(function(v){var w=this.getEntry(v);if(!w)return;var x=this.tokenizeCache(this.getTextToIndex(w)).tokens;for(var y=0,z=x.length;y<z;++y){var aa=x[y];if(!u.hasOwnProperty(aa))u[aa]={};u[aa][v]=true;}},this);};s.prototype.getTextToIndex=function(t){"use strict";if(t.textToIndex&&!t.needs_update)return t.textToIndex;t.needs_update=false;t.textToIndex=this.getTextToIndexFromFields(t,this._indexedFields);return t.textToIndex;};s.prototype.getTextToIndexFromFields=function(t,u){"use strict";var v=[];for(var w=0;w<u.length;++w){var x=t[u[w]];if(x)v.push(x.join?x.join(' '):x);}return v.join(' ');};s.prototype.mergeUids=function(t,u,v,w){"use strict";this.inform('mergeUids',{local_uids:t,query_uids:u,new_uids:v,value:w});var x=function(y,z){var aa=this.getEntry(y),ba=this.getEntry(z);if(aa.extended_match!==ba.extended_match)return aa.extended_match?1:-1;if(aa.index!==ba.index)return aa.index-ba.index;if(aa.text.length!==ba.text.length)return aa.text.length-ba.text.length;return aa.uid<ba.uid;}.bind(this);this._checkExtendedMatch(w,t);return this.deduplicateByKey(t.sort(x).concat(u,v));};s.prototype._checkExtendedMatch=function(t,u){"use strict";var v=this._alwaysPrefixMatch?i.isPrefixMatch:i.isQueryMatch;for(var w=0;w<u.length;++w){var x=this.getEntry(u[w]);x.extended_match=x.tokens?!v(t,x.text):false;}};s.prototype.buildUids=function(t,u,v){"use strict";if(!u)u=[];if(!t)return u;if(!v)v=[];var w=this.buildCacheResults(t,this.localCache),x=this.buildQueryResults(t),y=this.mergeUids(w,x,u,t),z=m(v.concat(this._exclusions)),aa=y.filter(function(ba){if(z.hasOwnProperty(ba)||!this.getEntry(ba))return false;for(var ca=0;ca<this._filters.length;++ca)if(!this._filters[ca](this.getEntry(ba),t))return false;return (z[ba]=true);},this);return this.uidsIncludingExact(t,aa);};s.prototype.uidsIncludingExact=function(t,u){"use strict";var v=u.length;if(t.length<this._minExactMatchLength||v<=this._maxResults)return u;for(var w=0;w<v;++w){var x=this.getEntry(u[w]);x.text_lower||(x.text_lower=x.text.toLowerCase());if(x.text_lower===this.tokenizeCache(t).flatValue){if(w>=this._maxResults){var y=u.splice(w,1)[0];u.splice(this._maxResults-1,0,y);}break;}}return u;};s.prototype.buildData=function(t){"use strict";var u=[],v=Math.min(t.length,this._maxResults);for(var w=0;w<v;++w)u.push(this.getEntry(t[w]));return u;};s.prototype.findBestPreviousQuery=function(t,u){"use strict";var v=0,w=null;if(this._queryExactMatch)return u.hasOwnProperty(t)?t:null;for(var x in u)if(t.indexOf(x)===0&&x.length>v){v=x.length;w=x;}return w;};s.prototype.findQueryCache=function(t){"use strict";var u=this.findBestPreviousQuery(t,this.getQueryCache());return this.getQueryCache()[u]||[];};s.prototype.buildQueryResults=function(t){"use strict";var u=this.tokenizeBackend(t).flatValue,v=this.findQueryCache(u);if(this.getQueryCache().hasOwnProperty(u))return v;var w=this.filterQueryResults(u,v);return w;};s.prototype.filterQueryResults=function(t,u){"use strict";var v=this._alwaysPrefixMatch?i.isPrefixMatch:i.isQueryMatch;return u.filter(function(w){return v(t,this.getTextToIndex(this.getEntry(w)));},this);};s.prototype.buildCacheResults=function(t,u){"use strict";var v=this.tokenizeCache(t,this._alwaysPrefixMatch),w=this._alwaysPrefixMatch?v.sortedTokens:v.tokens,x=w.length,y=v.isPrefixQuery?x-1:null,z={},aa={},ba={},ca=[],da=false,ea={},fa=0;for(var ga=0;ga<x;++ga){var ha=w[ga];if(!ea.hasOwnProperty(ha)){fa++;ea[ha]=true;}else continue;for(var ia in u)if((!z.hasOwnProperty(ia)&&ia===ha)||((this._alwaysPrefixMatch||y===ga)&&this.cacheUnicodeMatch.prefixMatch(ia,ha))){if(ia===ha){if(aa.hasOwnProperty(ia))da=true;z[ia]=true;}else{if(z.hasOwnProperty(ia)||aa.hasOwnProperty(ia))da=true;aa[ia]=true;}for(var ja in u[ia])if(ga===0||(ba.hasOwnProperty(ja)&&ba[ja]==fa-1))ba[ja]=fa;}}for(var ka in ba)if(ba[ka]==fa)ca.push(ka);if(da||fa<x)ca=this.filterQueryResults(t,ca);if(this._titleFields&&this._titleFields.length>0)ca=this.filterNonTitleMatchQueryResults(t,ca);return ca;};s.prototype.filterNonTitleMatchQueryResults=function(t,u){"use strict";return u.filter(function(v){var w=this.tokenizeCache(t),x=w.tokens.length;if(x===0)return true;var y=this.getTitleTerms(this.getEntry(v)),z=w.tokens[0];return ((x===1)||this._alwaysPrefixMatch)?(i.isPrefixMatch(z,y)||this.cacheUnicodeMatch.prefixMatch(y,z)):i.isQueryMatch(z,y);},this);};s.prototype.getTitleTerms=function(t){"use strict";if(!t.titleToIndex)t.titleToIndex=this.getTextToIndexFromFields(t,this._titleFields);return t.titleToIndex;};s.prototype.deduplicateByKey=function(t){"use strict";if(!this._deduplicationKey)return t;var u=m(t.map(this._getDeduplicationKey.bind(this)),t);return t.filter(function(v){return u[this._getDeduplicationKey(v)]==v;}.bind(this));};s.prototype._getDeduplicationKey=function(t){"use strict";var u=this.getEntry(t);if(u[this._deduplicationKey]){return u[this._deduplicationKey]+'';}else return '__'+t+'__';};s.prototype.getQueryCache=function(){"use strict";return this.queryCache;};s.prototype.getQueryIDs=function(){"use strict";return this.queryIDs;};s.prototype.setMaxResults=function(t){"use strict";this._maxResults=t;this.value&&this.respond(this.value,this.buildUids(this.value));};s.prototype.updateToken=function(t){"use strict";this.token=t;this.dirty();return this;};s.prototype._guid=function(){"use strict";var t=Date.now(),u='xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(v){var w=Math.floor((t+Math.random()*16)%16);t=Math.floor(t/16);var x=(v=='x'?w:(w&7|8)).toString(16);return x;});return u;};k(s.prototype,{events:['bootstrap','query','respond'],asyncErrorHandler:n});e.exports=s;},null);
__d("MultiBootstrapDataSource",["DataSource"],function(a,b,c,d,e,f,g){for(var h in g)if(g.hasOwnProperty(h))j[h]=g[h];var i=g===null?null:g.prototype;j.prototype=Object.create(i);j.prototype.constructor=j;j.__superConstructor__=g;function j(k){"use strict";this._bootstrapEndpoints=k.bootstrapEndpoints;g.call(this,k);}j.prototype.bootstrapWithoutToken=function(){"use strict";for(var k=0;k<this._bootstrapEndpoints.length;k++)this.fetch(this._bootstrapEndpoints[k].endpoint,this._bootstrapEndpoints[k].data||{},{bootstrap:true});};e.exports=j;},null);
__d("TabbableElements",["Style","createArrayFrom"],function(a,b,c,d,e,f,g,h){function i(l){if(l.tabIndex>0||(l.tabIndex===0&&l.getAttribute('tabIndex')!==null))return true;switch(l.tagName){case "A":return l.href&&l.rel!="ignore";case "INPUT":return l.type!="hidden"&&l.type!="file"&&!l.disabled;case "BUTTON":case "SELECT":case "TEXTAREA":return !l.disabled;}return false;}function j(l){if(l.offsetHeight===0&&l.offsetWidth===0)return false;while(l!==document&&g.get(l,'visibility')!='hidden')l=l.parentNode;return l===document;}var k={find:function(l){var m=h(l.getElementsByTagName("*"));return m.filter(k.isTabbable);},isTabbable:function(l){return i(l)&&j(l);}};e.exports=k;},null);
__d("tidyEvent",["Run"],function(a,b,c,d,e,f,g){var h=[];function i(){while(h.length){var l=h.shift();l&&l.remove?l.remove():l.unsubscribe();}}function j(l){var m;function n(){if(!m)return;m.apply(l,arguments);m=null;l=null;}if(l.remove){m=l.remove;l.remove=n;}else{m=l.unsubscribe;l.unsubscribe=n;}return l;}function k(l){if(!h.length)g.onLeave(i);if(Array.isArray(l)){for(var m=0;m<l.length;m++)h.push(j(l[m]));}else h.push(j(l));return l;}e.exports=k;},null);
__d("Toggler",["Arbiter","ArbiterMixin","ContextualThing","CSS","DataStore","DOM","DOMQuery","Event","Focus","Keys","TabbableElements","arrayContains","copyProperties","createArrayFrom","cx","emptyFunction","ge","getContextualParent","getObjectValues","setImmediate","mixin"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa){var ba=[],ca,da=false;function ea(){if(!da){da=true;z(function(){da=false;});}}function fa(){fa=v;n.listen(document.documentElement,'click',function(event){if(da)return;var ma=event.getTarget();ba.forEach(function(na){na.clickedTarget=ma;na.active&&!na.sticky&&!i.containsIncludingLayers(na.getActive(),ma)&&!na.inTargetFlyout(ma)&&na.inActiveDialog()&&!na.isIgnoredByModalLayer(ma)&&na.hide();});},n.Priority.URGENT);}var ga=aa(h);for(var ha in ga)if(ga.hasOwnProperty(ha))ja[ha]=ga[ha];var ia=ga===null?null:ga.prototype;ja.prototype=Object.create(ia);ja.prototype.constructor=ja;ja.__superConstructor__=ga;function ja(){"use strict";this.active=null;this.togglers={};this.setSticky(false);ba.push(this);this.subscribe(['show','hide'],ja.inform.bind(ja));return fa();}ja.prototype.show=function(ma){"use strict";var na=ka(this,ma),oa=na.active;if(ma!==oa){oa&&na.hide();na.active=ma;j.addClass(ma,'openToggler');var pa=l.scry(ma,'a[rel="toggle"]');if(pa.length>0&&pa[0].getAttribute('data-target'))j.removeClass(w(pa[0].getAttribute('data-target')),'toggleTargetClosed');var qa=m.scry(ma,'.uiToggleFlyout')[0];if(qa){var ra=q.find(qa)[0]||qa;if(ra.tabIndex==-1)ra.tabIndex=0;o.setWithoutOutline(ra);}if(pa.length>0){l.appendContent(ma,na.getToggler('next'));l.prependContent(ma,na.getToggler('prev'));}n.listen(ma,'keydown',function(event){if(n.getKeyCode(event)===p.ESC)if(na.isShown()){var sa=l.scry(ma,'a[rel="toggle"]')[0];sa&&sa.focus();na.hide();}});na.inform('show',na);}};ja.prototype.hide=function(ma){"use strict";var na=ka(this,ma),oa=na.active;if(oa&&(!ma||ma===oa)){j.removeClass(oa,'openToggler');var pa=l.scry(oa,'a[rel="toggle"]');if(pa.length>0&&pa[0].getAttribute('data-target'))j.addClass(w(pa[0].getAttribute('data-target')),'toggleTargetClosed');y(na.togglers).forEach(l.remove);na.inform('hide',na);na.active=null;}};ja.prototype.toggle=function(ma){"use strict";var na=ka(this,ma);if(na.active===ma){na.hide();}else na.show(ma);ea();};ja.prototype.getActive=function(){"use strict";return ka(this).active;};ja.prototype.isShown=function(){"use strict";return ka(this).active&&j.hasClass(ka(this).active,'openToggler');};ja.prototype.inTargetFlyout=function(ma){"use strict";var na=la(this.getActive());return na&&i.containsIncludingLayers(na,ma);};ja.prototype.inActiveDialog=function(){"use strict";var ma=a.Dialog&&a.Dialog.getCurrent();return !ma||l.contains(ma.getRoot(),this.getActive());};ja.prototype.isIgnoredByModalLayer=function(ma){"use strict";var na=!!i.parentByClass(ma,"_3qw"),oa=!!i.parentByClass(this.getActive(),"_3qw");return na&&!oa;};ja.prototype.getToggler=function(ma){"use strict";var na=ka(this);if(!na.togglers[ma]){na.togglers[ma]=l.create('button',{className:'hideToggler',onfocus:function(){var oa=l.scry(na.active,'a[rel="toggle"]')[0];oa&&oa.focus();na.hide();},style:{right:ma==='next'?'0':''}});na.togglers[ma].setAttribute('type','button');}return this.togglers[ma];};ja.prototype.setSticky=function(ma){"use strict";var na=ka(this);ma=ma!==false;if(ma!==na.sticky){na.sticky=ma;if(ma){na.$Toggler0&&na.$Toggler0.unsubscribe();}else na.$Toggler0=g.subscribe('pre_page_transition',na.hide.bind(na,null));}return na;};ja.prototype.setPrePageTransitionCallback=function(ma){"use strict";var na=ka(this);na.$Toggler0&&na.$Toggler0.unsubscribe();na.$Toggler0=g.subscribe('pre_page_transition',ma);};ja.bootstrap=function(ma){"use strict";var na=ma.parentNode;ja.getInstance(na).toggle(na);};ja.createInstance=function(ma){"use strict";var na=new ja().setSticky(true);k.set(ma,'toggler',na);return na;};ja.destroyInstance=function(ma){"use strict";k.remove(ma,'toggler');};ja.getInstance=function(ma){"use strict";while(ma){var na=k.get(ma,'toggler');if(na)return na;if(j.hasClass(ma,'uiToggleContext'))return ja.createInstance(ma);ma=x(ma);}return (ca=ca||new ja());};ja.listen=function(ma,na,oa){"use strict";return ja.subscribe(t(ma),function(pa,qa){if(qa.getActive()===na)return oa(pa,qa);});};s(ja,ja.prototype);s(ja,{subscribe:(function(ma){return function(na,oa){na=t(na);if(r(na,'show'))ba.forEach(function(pa){if(pa.getActive())setTimeout(oa.bind(null,'show',pa),0);});return ma(na,oa);};})(ja.subscribe.bind(ja))});function ka(ma,na){if(ma instanceof ja)return ma;return ja.getInstance(na);}function la(ma){var na=l.scry(ma,'a[rel="toggle"]');if(na.length>0&&na[0].getAttribute('data-target'))return w(na[0].getAttribute('data-target'));}e.exports=ja;},null);
__d("XHPTemplate",["DataStore","DOM","HTML"],function(a,b,c,d,e,f,g,h,i){function j(l){"use strict";this._model=l;}j.prototype.render=function(){"use strict";if(i.isHTML(this._model))this._model=h.setContent(document.createDocumentFragment(),this._model)[0];return this._model.cloneNode(true);};j.prototype.build=function(){"use strict";return new k(this.render());};j.getNode=function(l,m){"use strict";return j.getNodes(l)[m];};j.getNodes=function(l){"use strict";var m=g.get(l,'XHPTemplate:nodes');if(!m){m={};var n=h.scry(l,'[data-jsid]');n.push(l);var o=n.length;while(o--){var p=n[o];m[p.getAttribute('data-jsid')]=p;p.removeAttribute('data-jsid');}g.set(l,'XHPTemplate:nodes',m);}return m;};function k(l){"use strict";this._root=l;this._populateNodes();}k.prototype._populateNodes=function(){"use strict";this._nodes={};this._leaves={};var l=this._root.getElementsByTagName('*');for(var m=0,n=l.length;m<n;m++){var o=l[m],p=o.getAttribute('data-jsid');if(p){o.removeAttribute('data-jsid');this._nodes[p]=o;this._leaves[p]=!o.childNodes.length;}}};k.prototype.getRoot=function(){"use strict";return this._root;};k.prototype.getNode=function(l){"use strict";return this._nodes[l];};k.prototype.setNodeProperty=function(l,m,n){"use strict";this.getNode(l)[m]=n;return this;};k.prototype.setNodeContent=function(l,m){"use strict";if(!this._leaves[l])throw new Error("Can't setContent on non-leaf node: "+l);h.setContent(this.getNode(l),m);return this;};e.exports=j;},null);
__d("onEnclosingPageletDestroy",["Arbiter","DOMQuery"],function(a,b,c,d,e,f,g,h){function i(j,k){var l=g.subscribe('pagelet/destroy',function(m,n){if(h.contains(n.root,j)){l.unsubscribe();k();}});return l;}e.exports=i;},null);
__d("FbFeedHighlight",["JSXDOM","CSS","DOM","DOMScroll","cx"],function(a,b,c,d,e,f,g,h,i,j,k){var l=1000,m=1000,n=null;function o(){return (g.div({className:"_1usz"},g.div({className:"_1us-"}),g.div({className:"_1us_"}),g.div({className:"_1ut0"}),g.div({className:"_1ut1"})));}var p={highlightAndScrollTo:function(q){p.highlight(q);p.scrollTo(q);},highlightSingle:function(q){var r=o();i.appendContent(q,r);setTimeout(function(){if(n)i.remove(n);n=r;h.addClass(q,"_1ut2");},0);setTimeout(function(){h.removeClass(q,"_1ut2");setTimeout(function(){i.remove(r);if(r==n)n=null;},l+m);},l+m);},highlight:function(q){var r=o();i.appendContent(q,r);setTimeout(h.addClass.bind(null,q,"_1ut2"),0);setTimeout(function(){h.removeClass(q,"_1ut2");setTimeout(i.remove.bind(null,r),l+l);},l+m);},scrollTo:function(q){setTimeout(j.scrollTo.bind(null,q),0);}};e.exports=p;},null);
__d("XNotificationInlineStoryInsertControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/desktop_notifications\/insert_story\/",{uri:{type:"String",required:true},uri_path:{type:"String",required:true},first_insert:{type:"Bool"},notif_id:{type:"String",required:true}});},null);
__d("InlineStoryInsert",["Animation","Arbiter","AsyncRequest","csx","DOM","DOMQuery","DOMScroll","FbFeedHighlight","ge","XNotificationInlineStoryInsertControllerURIBuilder","Toggler","$"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){var s=null,t={insertStory:function(u){q.hide(r("fbNotificationsJewel"));var v=r("pagelet_composer");g.insert(v,u,k.insertAfter);s=l.scry(r("stream_pagelet"),"._2dt8")[0];var w=l.scry(s,"._2fx2")[0],x=l.scry(u,"._2fx3")[0];h.subscribeOnce('notifStory/ufiLoaded',function(){t.scrollToHeaderandHighlightStory(w,x);}.bind(this));},prependStory:function(u){q.hide(r("fbNotificationsJewel"));s=l.scry(r("stream_pagelet"),"._2dt8")[0];var v=l.scry(s,"._2fx2")[0],w=l.scry(u,"._2fx3")[0];t.dedupe(s,"._2fx4",u);g.insert(v,u,k.insertAfter);h.subscribeOnce('notifStory/ufiLoaded',function(){t.scrollToHeaderandHighlightStory(v,w);}.bind(this));},scrollToHeaderandHighlightStory:function(u,v){n.highlight(v);m.scrollTo(u);h.inform('inlineStory/insertLoaded');},gotoPermalink:function(u){window.open(u,'_self');},stopLoadingAndFallback:function(u){window.open(u,'_self');h.inform('inlineStory/insertLoaded');},requestStory:function(u,v,w,x){h.subscribeOnce('notifStory/ufiLoaded',function(){t.setCommentFocus();}.bind(this));var y=new p().setString('uri',u).setString('uri_path',v).setBool('first_insert',w).setString('notif_id',x).getURI();new i().setURI(y).send();},setCommentFocus:function(){var u=k.scry(s,'textarea');if(u.length>0)u[0].focus();},dedupe:function(u,v,w){var x=l.scry(u,v);for(var y=0;y<x.length;y++)if(x[y].id===w.id){k.remove(x[y]);return;}},_insert:function(u,v,w){var x=l.scry(r("stream_pagelet"),"._2fx4").length===0;t.requestStory(u,v,x,w);},_isInFeed:function(){if(!o("pagelet_composer"))return false;return true;},_notifStoryUFI:function(u){if(!t._isInFeed())return false;var v=null,w=null;v=l.scry(r("stream_pagelet"),"._2dt8");if(v.length>0){w=v[0];if(l.contains(w,u))return true;}return false;}};e.exports=t;},null);
__d("SnowflakePermalinkUtils",["URI"],function(a,b,c,d,e,f,g){var h=/\/[^/]+\/(albums\/([^/]+)|posts\/([a-zA-Z]+[^/]+))\/([^/]+\/)?/,i=/\/[^/]+\/(albums|posts)\/([^/]+)\/([^/]+\/)?/,j={isPermalinkURI:function(k){k=g(k);return h.test(k.getPath());},parseURI:function(k){if(!this.isPermalinkURI(k))return {};k=g(k);var l=k.getPath().match(i);return {setToken:l[2],entIdentifierToken:l[3],photoID:k.getQueryData().photo_id};}};e.exports=j;},null);
__d("Sticker.react",["Arbiter","React","StickerConfig","StickerConstants","emptyFunction","getElementPosition","getObjectValues"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){'use strict';var n=83,o=5000,p=10,q={CLICK:'click',HOVER:'hover',LOAD_AND_HOVER:'load_and_hover'},r=h.createClass({displayName:'Sticker',propTypes:{animationTrigger:h.PropTypes.oneOf(m(q)),frameCount:h.PropTypes.number.isRequired,frameRate:h.PropTypes.number,framesPerCol:h.PropTypes.number.isRequired,framesPerRow:h.PropTypes.number.isRequired,onStickerClick:h.PropTypes.func,packID:h.PropTypes.string,sourceURI:h.PropTypes.string.isRequired,sourceWidth:h.PropTypes.number.isRequired,sourceHeight:h.PropTypes.number.isRequired,spriteURI:h.PropTypes.string,stickerID:h.PropTypes.string,subscribedThreadID:h.PropTypes.string},getInitialState:function(){return {index:0,hasAnimated:false,unsubscribeID:null};},getDefaultProps:function(){return {frameRate:n,onStickerClick:k,packID:null,shown:false};},componentDidMount:function(){this._stopIntervalID=0;if(this.props.animationTrigger===q.LOAD_AND_HOVER&&this.props.frameCount>1&&this.props.spriteURI)this.startAnimation();if(this.props.subscribedThreadID&&this.props.frameCount>1){var s=g.subscribe(this.props.subscribedThreadID,function(t,u){this.isScrolledIntoView(u.scrollTop,u.viewHeight,u.top);}.bind(this));this.setState({unsubscribeID:s});}},componentDidUpdate:function(s){if(i.AutoAnimateStickerTray&&!s.shown&&this.props.shown)this.startAnimation();},componentWillUnmount:function(){if(this.state.unsubscribeID)g.unsubscribe(this.state.unsubscribeID);if(this.isAnimating())clearInterval(this._stopIntervalID);},isAnimating:function(){return !!this._stopIntervalID;},getWidth:function(){return Math.floor(this.props.sourceWidth);},getHeight:function(){return Math.floor(this.props.sourceHeight);},preloadSprite:function(){var s=new Image();s.onload=function(){if(this.isMounted()&&!this.state.hasAnimated){this.setState({hasAnimated:true});this._stopIntervalID=setInterval(this.incrementFrameIndex,this.props.frameRate);}}.bind(this);if(i.ChatPaddedAnimatedStickerGK&&this.props.paddedSpriteURI){s.src=this.props.paddedSpriteURI;}else s.src=this.props.spriteURI;},isScrolledIntoView:function(s,t,u){var v=l(this.getDOMNode()),w=s+v.y-u,x=s+t,y=w+v.height;if(this.props.frameCount>1&&!this.state.hasAnimated&&y-p<=x&&w+p>=s)this.startAnimation();},startAnimation:function(){if(!this.state.hasAnimated&&this.props.spriteURI){this.preloadSprite();}else if(!this.isAnimating()){this.setState({hasAnimated:true});this._stopIntervalID=setInterval(this.incrementFrameIndex,this.props.frameRate);}},stopAnimation:function(){this.setState({index:0});clearInterval(this._stopIntervalID);this._stopIntervalID=0;},toggleAnimation:function(){if(this.isAnimating()){this.stopAnimation();}else this.startAnimation();},shouldStopAnimating:function(){var s=this.state.index%this.props.frameCount;if(!(s===0&&this.state.index*this.props.frameRate>o))return false;if(this.props.animationTrigger===q.CLICK)return true;return !this.state.isHovered;},incrementFrameIndex:function(){if(this.shouldStopAnimating()){this.stopAnimation();}else this.setState({index:this.state.index+1});},getStyle:function(){var s=0,t=this.props.spriteURI;if(i.ChatPaddedAnimatedStickerGK&&this.props.paddedSpriteURI){t=this.props.paddedSpriteURI;var u=240/Math.min(this.getHeight(),this.getWidth());s=Math.floor(j.SPRITE_PADDING/u);}var v=this.state.index%this.props.frameCount,w=(v%this.props.framesPerRow)*(this.getWidth()+s*2)+s,x=Math.floor(v/this.props.framesPerRow)*(this.getHeight()+s*2)+s,y=(this.props.frameCount>1&&this.props.animationTrigger===q.CLICK)||this._isStickerClickable(this.props.packID),z;if(this.props.style&&this.props.style.cursor){z=this.props.style.cursor;}else z=y?'pointer':'default';if(!this.state.hasAnimated||!this.props.spriteURI){return {backgroundImage:'url('+this.props.sourceURI+')',backgroundRepeat:'no-repeat',backgroundSize:this.getWidth()+'px '+this.getHeight()+'px',cursor:z,height:this.getHeight(),width:this.getWidth()};}else return {backgroundImage:'url('+t+')',backgroundPosition:(-w)+'px '+(-x)+'px',backgroundSize:(this.getWidth()+s*2)*this.props.framesPerRow+'px '+(this.getHeight()+s*2)*this.props.framesPerCol+'px',cursor:z,height:this.getHeight(),width:this.getWidth()};},_isStickerClickable:function(s){return s&&s!=j.MOBILE_LIKE_STICKER_PACK_ID&&s!=j.GRAVEYARD_PACK_ID;},onStickerClick:function(){if(!this._isStickerClickable(this.props.packID))return;if(this.props.onStickerClick)this.props.onStickerClick(this.props.packID,this.props.stickerID);},mouseLeft:function(){this.setState({isHovered:false});},mouseEntered:function(){this.setState({isHovered:true});if(!this.isAnimating())this.startAnimation();},render:function(){var s,t;if(this.props.animationTrigger===q.CLICK&&this.props.frameCount>1&&this.props.spriteURI){s=true;}else if((this.props.animationTrigger===q.HOVER||this.props.animationTrigger===q.LOAD_AND_HOVER)&&this.props.frameCount>1&&this.props.spriteURI)t=true;var u=s?this.toggleAnimation:null;if(this.props.packID)u=this.onStickerClick;return (h.createElement("div",Object.assign({},this.props,{style:Object.assign({},(this.props.style||{}),this.getStyle()),onClick:u,onMouseEnter:t?this.mouseEntered:null,onMouseLeave:t?this.mouseLeft:null})));}});e.exports=r;},null);
__d("TabIsolation",["DOMQuery","Event","Focus","Keys","TabbableElements"],function(a,b,c,d,e,f,g,h,i,j,k){var l=[],m=0;function n(o){"use strict";this._root=o;this._eventHandler=null;this._identifier=m++;}n.prototype.enable=function(){"use strict";l.unshift(this._identifier);this._eventHandler=h.listen(window,'keydown',function(o){if(l[0]===this._identifier)this._tabHandler(o);}.bind(this),h.Priority.URGENT);};n.prototype.disable=function(){"use strict";var o;if(this._eventHandler){o=l.indexOf(this._identifier);if(o>-1)l.splice(o,1);this._eventHandler.remove();this._eventHandler=null;}};n.prototype._tabHandler=function(o){"use strict";if(h.getKeyCode(o)!==j.TAB)return;var p=o.getTarget();if(!p)return;var q=k.find(this._root),r=q[0],s=q[q.length-1],t=o.getModifiers().shift;if(t&&p===r){o.preventDefault();i.set(s);}else if((!t&&p===s)||!g.contains(this._root,p)){o.preventDefault();i.set(r);}};e.exports=n;},null);
__d("legacy:Tooltip",["Tooltip"],function(a,b,c,d){a.Tooltip=b('Tooltip');},3);
__d("BadgeHelper",["DOM","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i){var j={xsmall:"_5dzz",small:"_5dz-",medium:"_5dz_",large:"_5d-0",xlarge:"_5d-1"};function k(m,n){var o=j[m];switch(n){case 'verified':return i(o,"_56_f _5dzy");case 'topcommenter':return i(o,"_59t2 _5dzy");case 'work':return i(o,"_5d62 _5dzy");}}function l(m,n){var o=k(m,n);if(o)return g.create('span',{className:o});}e.exports={getClasses:k,renderBadge:l,sizes:Object.keys(j)};},null);
__d("Badge.react",["BadgeHelper","React"],function(a,b,c,d,e,f,g,h){var i=h.createClass({displayName:'Badge',propTypes:{size:h.PropTypes.oneOf(g.sizes),type:h.PropTypes.oneOf(['verified','topcommenter','work'])},getDefaultProps:function(){return {size:'xsmall',type:'verified'};},render:function(){return (h.createElement("span",{className:g.getClasses(this.props.size,this.props.type)}));}});e.exports=i;},null);
__d("AccessibleLayer",["DOM","Event","Focus","tx"],function(a,b,c,d,e,f,g,h,i,j){function k(l){"use strict";this._layer=l;}k.prototype.enable=function(){"use strict";this._afterShowSubscription=this._layer.subscribe('aftershow',this._onAfterShow.bind(this));};k.prototype.disable=function(){"use strict";this._listener&&this._listener.remove();this._afterShowSubscription.unsubscribe();this._listener=this._afterShowSubscription=null;};k.prototype._closeListener=function(event){"use strict";var l=this._layer.getCausalElement();if(l)if(l.tabIndex==-1){l.tabIndex=0;i.setWithoutOutline(l);}else i.set(l);this._layer.hide();};k.prototype._onAfterShow=function(){"use strict";var l=this._layer.getContentRoot();if(g.scry(l,'.layer_close_elem')[0])return;var m=g.create('a',{className:'accessible_elem layer_close_elem',href:'#'},["Close popup and return"]);g.appendContent(l,m);this._listener=h.listen(m,'click',this._closeListener.bind(this));};e.exports=k;},null);
__d("ContextualLayerHideOnScroll",["Event","copyProperties"],function(a,b,c,d,e,f,g,h){function i(j){"use strict";this._layer=j;}i.prototype.enable=function(){"use strict";this._subscriptions=[this._layer.subscribe('contextchange',this._handleContextChange.bind(this)),this._layer.subscribe('show',this.attach.bind(this)),this._layer.subscribe('hide',this.detach.bind(this))];};i.prototype.disable=function(){"use strict";while(this._subscriptions.length)this._subscriptions.pop().unsubscribe();this.detach();};i.prototype.attach=function(){"use strict";if(this._listener)return;var j=this._layer.getContextScrollParent();if(j===window)return;this._listener=g.listen(j,'scroll',this._layer.hide.bind(this._layer));};i.prototype.detach=function(){"use strict";this._listener&&this._listener.remove();this._listener=null;};i.prototype._handleContextChange=function(){"use strict";this.detach();if(this._layer.isShown())this.attach();};h(i.prototype,{_subscriptions:[]});e.exports=i;},null);
__d("LayerAutoFocus",["DOMQuery","Focus","TabbableElements","copyProperties"],function(a,b,c,d,e,f,g,h,i,j){function k(l){"use strict";this._layer=l;}k.prototype.enable=function(){"use strict";this._subscription=this._layer.subscribe('aftershow',this._focus.bind(this));};k.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;};k.prototype._focus=function(){"use strict";var l=this._layer.getRoot(),m=g.scry(l,'.autofocus')[0],n=true;if(!m){var o=document.activeElement;if(g.isNodeOfType(o,['input','textarea']))return;var p=i.find(l);for(var q=0;q<p.length;q++)if(p[q].tagName!='A'){m=p[q];n=false;break;}}else if(m.tabIndex!==0)n=false;if(m){n?h.set(m):h.setWithoutOutline(m);}else if(!l.offsetWidth){l.tabIndex=0;h.setWithoutOutline(l);}};j(k.prototype,{_subscription:null});e.exports=k;},null);
__d("LayerButtons",["Event","Parent","copyProperties"],function(a,b,c,d,e,f,g,h,i){function j(k){"use strict";this._layer=k;}j.prototype.enable=function(){"use strict";this._listener=g.listen(this._layer.getRoot(),'click',this._handle.bind(this));};j.prototype.disable=function(){"use strict";this._listener.remove();this._listener=null;};j.prototype._handle=function(k){"use strict";var l=k.getTarget(),m=h.byClass(l,'layerConfirm');if(m){if(this._layer.inform('confirm',m)===false)k.prevent();return;}var n=h.byClass(l,'layerCancel');if(n){if(this._layer.inform('cancel',n)!==false)this._layer.hide();k.prevent();return;}var o=h.byClass(l,'layerButton');if(o)if(this._layer.inform('button',o)===false)k.prevent();};i(j.prototype,{_listener:null});e.exports=j;},null);
__d("LayerFadeOnHide",["Animation","Layer","Style","UserAgent_DEPRECATED","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k){function l(m){"use strict";this._layer=m;}l.prototype.enable=function(){"use strict";if(j.ie()<9)return;this._subscription=this._layer.subscribe('starthide',this._handleStartHide.bind(this));};l.prototype.disable=function(){"use strict";if(this._subscription){this._subscription.unsubscribe();this._subscription=null;}};l.prototype._handleStartHide=function(){"use strict";var m=true,n=h.subscribe('show',function(){n.unsubscribe();m=false;});setTimeout((function(){n.unsubscribe();n=null;var o=function(){this._layer.finishHide();}.bind(this);if(m){this._animate(o);}else o();}).bind(this),0);return false;};l.prototype._animate=function(m){"use strict";var n=this._layer.getRoot();new g(n).from('opacity',1).to('opacity',0).duration(150).ondone(function(){i.set(n,'opacity','');m();}).go();};k(l.prototype,{_subscription:null});e.exports=l;},null);
__d("LayerFadeOnShow",["Animation","Style","UserAgent_DEPRECATED","copyProperties","emptyFunction"],function(a,b,c,d,e,f,g,h,i,j,k){function l(m){"use strict";this._layer=m;}l.prototype.enable=function(){"use strict";if(i.ie()<9)return;this._subscriptions=[this._layer.subscribe('beforeshow',function(){h.set(this._layer.getRoot(),'opacity',0);}.bind(this)),this._layer.subscribe('show',this._animate.bind(this))];};l.prototype.disable=function(){"use strict";if(this._subscriptions){while(this._subscriptions.length)this._subscriptions.pop().unsubscribe();this._subscriptions=null;}};l.prototype._getDuration=function(){"use strict";return 100;};l.prototype._animate=function(){"use strict";var m=this._layer.getRoot();new g(m).from('opacity',0).to('opacity',1).duration(this._getDuration()).ondone(h.set.bind(null,m,'opacity','')).go();};l.forDuration=function(m){"use strict";for(var n in l)if(l.hasOwnProperty(n))p[n]=l[n];var o=l===null?null:l.prototype;p.prototype=Object.create(o);p.prototype.constructor=p;p.__superConstructor__=l;function p(){if(l!==null)l.apply(this,arguments);}p.prototype._getDuration=k.thatReturns(m);return p;};j(l.prototype,{_subscriptions:null});e.exports=l;},null);
__d("LayerFormHooks",["Event","copyProperties"],function(a,b,c,d,e,f,g,h){function i(j){"use strict";this._layer=j;}i.prototype.enable=function(){"use strict";var j=this._layer.getRoot();this._subscriptions=[g.listen(j,'submit',this._onSubmit.bind(this)),g.listen(j,'success',this._onSuccess.bind(this)),g.listen(j,'error',this._onError.bind(this))];};i.prototype.disable=function(){"use strict";this._subscriptions.forEach(function(j){j.remove();});this._subscriptions=null;};i.prototype._onSubmit=function(event){"use strict";if(this._layer.inform('submit',event)===false)event.kill();};i.prototype._onSuccess=function(event){"use strict";if(this._layer.inform('success',event)===false)event.kill();};i.prototype._onError=function(event){"use strict";var j=event.getData();if(this._layer.inform('error',{response:j.response})===false)event.kill();};h(i.prototype,{_subscriptions:null});e.exports=i;},null);
__d("LayerMouseHooks",["Arbiter","ContextualThing","Event","Layer","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k){var l=new g();function m(n){"use strict";this._layer=n;this._subscriptions=[];this._currentlyActive=false;}m.prototype.enable=function(){"use strict";this._subscriptions=[l.subscribe('mouseenter',this._handleActive.bind(this)),l.subscribe('mouseleave',this._handleInactive.bind(this)),this._layer.subscribe('hide',function(){this._currentlyActive=false;}.bind(this))];};m.prototype.disable=function(){"use strict";while(this._subscriptions.length)this._subscriptions.pop().unsubscribe();this._subscriptions=[];this._currentlyActive=false;};m.prototype._handleActive=function(n,o){"use strict";if(!this._currentlyActive&&this._isNodeWithinStack(o)){this._layer.inform('mouseenter');this._currentlyActive=true;}};m.prototype._handleInactive=function(n,o){"use strict";if(this._currentlyActive)if(!o||!this._isNodeWithinStack(o)){this._layer.inform('mouseleave');this._currentlyActive=false;}};m.prototype._isNodeWithinStack=function(n){"use strict";return h.containsIncludingLayers(this._layer.getContentRoot(),n);};j.subscribe('show',function(n,o){var p=o.getContentRoot(),q=[i.listen(p,'mouseenter',function(){l.inform('mouseenter',p);}),i.listen(p,'mouseleave',function(s){l.inform('mouseleave',s.getRelatedTarget());})],r=o.subscribe('hide',function(){while(q.length)q.pop().remove();r.unsubscribe();q=r=null;});});e.exports=m;},null);
__d("LayerRefocusOnHide",["ContextualThing","DOM","DOMQuery","Focus","Parent","copyProperties"],function(a,b,c,d,e,f,g,h,i,j,k,l){function m(n){"use strict";this._layer=n;}m.prototype.enable=function(){"use strict";this._subscription=this._layer.subscribe('hide',this._handle.bind(this));};m.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;};m.prototype._handle=function(n,event){"use strict";if(document.activeElement===document.body||i.contains(this._layer.getRoot(),document.activeElement)){var o=this._layer.getCausalElement();while(o&&(!o.offsetWidth)){var p=k.byClass(o,'uiToggle');if(p&&p.offsetWidth){o=h.scry(p,'[rel="toggle"]')[0];}else{var q=g.getContext(o);if(q){o=q;}else o=o.parentNode;}}if(o)if(o.tabIndex!=-1)j.setWithoutOutline(o);}};l(m.prototype,{_subscription:null});e.exports=m;},null);
__d("LayerRemoveOnHide",["DOM","copyProperties"],function(a,b,c,d,e,f,g,h){function i(j){"use strict";this._layer=j;}i.prototype.enable=function(){"use strict";this._subscription=this._layer.subscribe('hide',g.remove.bind(null,this._layer.getRoot()));};i.prototype.disable=function(){"use strict";if(this._subscription){this._subscription.unsubscribe();this._subscription=null;}};h(i.prototype,{_subscription:null});e.exports=i;},null);
__d("LayerTabIsolation",["TabIsolation","copyProperties"],function(a,b,c,d,e,f,g,h){function i(j){"use strict";this._layer=j;this._tabIsolation=null;}i.prototype.enable=function(){"use strict";this._tabIsolation=new g(this._layer.getRoot());this._subscriptions=[this._layer.subscribe('show',this._tabIsolation.enable.bind(this._tabIsolation)),this._layer.subscribe('hide',this._tabIsolation.disable.bind(this._tabIsolation))];};i.prototype.disable=function(){"use strict";while(this._subscriptions.length)this._subscriptions.pop().unsubscribe();this._tabIsolation.disable();this._tabIsolation=null;};h(i.prototype,{_subscriptions:[]});e.exports=i;},null);
__d("ContextualDialogArrow",["CSS","DOM","JSXDOM","Locale","Style","Vector","copyProperties","cx"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){var o={bottom:"_53ik",top:"_53il",right:"_53im",left:"_53in"},p={above:'bottom',below:'top',left:'right',right:'left'};function q(r){"use strict";this._layer=r;}q.prototype.enable=function(){"use strict";this._subscription=this._layer.subscribe(['adjust','reposition'],this._handle.bind(this));g.addClass(this._layer.getContentRoot(),"_5v-0");};q.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;g.removeClass(this._layer.getContentRoot(),"_5v-0");};q.prototype._handle=function(r,s){"use strict";if(r==='adjust'){this._repositionArrow(s);}else this._repositionRoot(s);};q.prototype._repositionRoot=function(r){"use strict";var s=r.getAlignment();if(s=='center')return;var t=this._layer.getRoot(),u=this._layer.getContext(),v=r.isVertical(),w=this._layer.getArrowDimensions(),x=w.offset,y=w.length,z=l.getElementDimensions(u),aa=v?z.x:z.y;if(aa>=y+(x*2))return;var ba=(y/2)+x,ca=aa/2,da=parseInt(ba-ca,10);if(v){if(s=='left'){var ea=parseInt(k.get(t,'left'),10);k.set(t,'left',(ea-da)+'px');}else{var fa=parseInt(k.get(t,'right'),10);k.set(t,'right',(fa-da)+'px');}}else{var ga=parseInt(k.get(t,'top'),10);k.set(t,'top',(ga-da)+'px');}};q.prototype._repositionArrow=function(r){"use strict";var s=this._layer.getContentRoot(),t=r.getPosition(),u=p[t];for(var v in o)g.conditionClass(s,o[v],u===v);if(t=='none')return;if(!this._arrow)this._arrow=i.i({className:"_53io"});if(!h.contains(s,this._arrow))h.appendContent(s,this._arrow);k.set(this._arrow,'top','');k.set(this._arrow,'left','');k.set(this._arrow,'right','');k.set(this._arrow,'margin','');var w=q.getOffsetPercent(r),x=q.getOffset(r,w,this._layer),y=q.getOffsetSide(r);k.set(this._arrow,y,w+'%');k.set(this._arrow,'margin-'+y,x+'px');};q.getOffsetPercent=function(r){"use strict";var s=r.getAlignment(),t=r.getPosition();if(t=='above'||t=='below')if(s=='center'){return 50;}else if(s=='right')return 100;return 0;};q.getOffsetSide=function(r){"use strict";var s=r.isVertical();return s?(j.isRTL()?'right':'left'):'top';};q.getOffset=function(r,s,t){"use strict";var u=t.getArrowDimensions(),v=u.offset,w=u.length,x=r.getAlignment(),y=(x=='center')?0:v;y+=w*s/100;if(x!='left')y*=-1;return y;};m(q.prototype,{_subscription:null,_arrow:null});e.exports=q;},null);
__d("ContextualDialogDefaultTheme",["cx"],function(a,b,c,d,e,f,g){var h={wrapperClassName:"_53ip",arrowDimensions:{offset:15,length:16}};e.exports=h;},null);
__d("ContextualDialogKeepInViewport",["ContextualLayerDimensions","Event","Style","Vector","throttle"],function(a,b,c,d,e,f,g,h,i,j,k){function l(m){"use strict";this._layer=m;this._listeners=[];this._subscription=null;this._minimumTop=null;}l.prototype.enable=function(){"use strict";var m=this._layer.getArrowDimensions();this._arrowOffset=m.offset;var n=m.length;this._arrowBuffer=this._arrowOffset+n;this._subscription=this._layer.subscribe(['show','hide','reposition'],function(o,p){if(this._layer.isFixed())return;if(o=='reposition'){this._calculateMinimumTop(p);}else if(o=='show'){this._attachScroll();this._adjustForScroll();}else this._detachScroll();}.bind(this));if(this._layer.isShown())this._attachScroll();};l.prototype.disable=function(){"use strict";if(this._layer.isShown())this._detachScroll();this._subscription.unsubscribe();this._subscription=null;};l.prototype._attachScroll=function(){"use strict";var m=k(this._adjustForScroll.bind(this)),n=this._layer.getContextScrollParent()||window;this._listeners=[h.listen(n,'scroll',m),h.listen(window,'resize',m)];};l.prototype._detachScroll=function(){"use strict";while(this._listeners.length)this._listeners.pop().remove();this._listeners=[];};l.prototype._getContentHeight=function(){"use strict";if(!this._layer._contentWrapper)return 0;return j.getElementDimensions(this._layer._contentWrapper).y;};l.prototype._getContextY=function(){"use strict";return j.getElementPosition(this._layer.getContext()).y;};l.prototype._calculateMinimumTop=function(m){"use strict";if(m.isVertical())return;this._minimumTop=(this._getContextY()-(this._getContentHeight()-this._arrowBuffer)+m.getOffsetY());};l.prototype._adjustForScroll=function(){"use strict";var m=this._layer._getOrientation();if(m.isVertical())return;var n=g.getViewportRect(this._layer),o=n.b-this._minimumTop;if(o<0)return;var p=this._getContentHeight(),q=p-(this._arrowBuffer+this._arrowOffset),r=Math.max(0,Math.min(q,q-(o-p)));i.set(this._layer.getContent(),'top',-r+'px');};e.exports=l;},null);
__d("ContextualDialogFitInViewport_PUSHSAFE",["Style","Vector"],function(a,b,c,d,e,f,g,h){var i=50,j=10;function k(l){"use strict";this._layer=l;this._contentHeight=null;this._contextY=null;}k.prototype.enable=function(){"use strict";var l=this._layer.getArrowDimensions();this._arrowOffset=l.offset;var m=l.length;this._arrowBuffer=this._arrowOffset+m;this._subscription=this._layer.subscribe(['reposition'],function(n,o){if(!this._layer.isFixed()||o.isVertical())return;this._adjustPosition();}.bind(this));};k.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;};k.prototype._getContentHeight=function(){"use strict";return h.getElementDimensions(this._layer._contentWrapper).y;};k.prototype._getContextY=function(){"use strict";return h.getElementPosition(this._layer.getContext(),'viewport').y;};k.prototype._adjustPosition=function(){"use strict";var l=this._getContextY(),m=this._getContentHeight();if(l===this._contextY&&m===this._contentHeight)return;this._contextY=l;this._contentHeight=m;var n=h.getViewportDimensions().y,o=Math.min(Math.max(0,l+m+j-n),Math.max(0,l-i),m-this._arrowOffset-this._arrowBuffer);g.set(this._layer.getContent(),'top',-o+'px');};e.exports=k;},null);
__d("ContextualDialog",["AccessibleLayer","ContextualDialogArrow","ContextualDialogDefaultTheme","ContextualDialogKeepInViewport","ContextualDialogFitInViewport_PUSHSAFE","ContextualLayer","CSS","DOM","Event","JSXDOM","LayerButtons","LayerFormHooks","LayerRefocusOnHide","LayerHideOnTransition","LayerMouseHooks","Style","copyProperties","csx","cx","invariant","removeFromArray","shield"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa,ba){var ca=0,da=300;for(var ea in l)if(l.hasOwnProperty(ea))ga[ea]=l[ea];var fa=l===null?null:l.prototype;ga.prototype=Object.create(fa);ga.prototype.constructor=ga;ga.__superConstructor__=l;function ga(ha,ia){"use strict";fa.constructor.call(this,ha,ia);this._footer=null;}ga.prototype._configure=function(ha,ia){"use strict";w(ha,ha.theme||i);var ja=ha.arrowBehavior||h;ha.addedBehaviors=ha.addedBehaviors||[];ha.addedBehaviors.push(ja);fa._configure.call(this,ha,ia);this._footer=n.scry(ia,"div._572u")[0];if(this._footer)if(this._footer.children.length===1&&this._footer.children[0].nodeName==='DIV'&&this._footer.children[0].children.length===0){this._footer.parentNode.removeChild(this._footer);}else m.addClass(this.getContentRoot(),"_kc");if(ha.hoverContext)this._registerHoverHandlers(ha.hoverContext,ha.hoverShowDelay,ha.hoverHideDelay);};ga.prototype._registerHoverHandlers=function(ha,ia,ja){"use strict";if(ia==null)ia=ca;if(ja==null)ja=da;var ka,la,ma=function(event){clearTimeout(la);ka=setTimeout(ba(this.show,this),ia);}.bind(this),na=function(event){if(this._isHoverLocked())return;clearTimeout(ka);la=setTimeout(this.hide.bind(this),ja);}.bind(this),oa=o.listen(ha,'mouseenter',ma),pa=o.listen(ha,'mouseleave',na),qa=this.subscribe('mouseenter',ma),ra=this.subscribe('mouseleave',na);this.subscribe('destroy',function(){clearTimeout(la);oa.remove();pa.remove();qa.unsubscribe();ra.unsubscribe();});};ga.prototype._getDefaultBehaviors=function(){"use strict";var ha=fa._getDefaultBehaviors.call(this);aa(ha,t);return ha.concat([g,s,j,k,q,r,u]);};ga.prototype._buildWrapper=function(ha,ia){"use strict";this._innerWrapper=p.div(null,ia);var ja=fa._buildWrapper.call(this,ha,this._innerWrapper);m.addClass(ja,ha.wrapperClassName);this.replaceEntireLayerContents(ia);z(this.getContent()===ia);this.setWidth(ha.width);return ja;};ga.prototype.getContentRoot=function(){"use strict";z(!!this._innerWrapper);return this._innerWrapper;};ga.prototype.setContent=function(ha){"use strict";z(false);};ga.prototype.replaceEntireLayerContents=function(ha){"use strict";this._content=null;n.empty(this.getContentRoot());this.setInnerContent(ha);};ga.prototype.setInnerContent=function(ha){"use strict";m.addClass(ha,"_53ij");if(this.getContent()){n.replace(this.getContent(),ha);}else n.appendContent(this.getContentRoot(),ha);this._content=ha;this.isShown()&&this.updatePosition();};ga.prototype.setWidth=function(ha){"use strict";v.set(this.getContentRoot(),'width',ha?Math.floor(ha)+'px':'');return this;};ga.prototype.getFooter=function(){"use strict";return this._footer;};ga.prototype.lockHover=function(){"use strict";this._hoverLocked=true;return this;};ga.prototype.unlockHover=function(){"use strict";this._hoverLocked=false;return this;};ga.prototype._isHoverLocked=function(){"use strict";return !!this._hoverLocked;};ga.setContext=function(ha,ia){"use strict";ha.setContext(ia);};e.exports=ga;},null);
__d("ContextualDialogXUITheme",["cx"],function(a,b,c,d,e,f,g){var h={wrapperClassName:"_53ii",arrowDimensions:{offset:12,length:16}};e.exports=h;},null);
|
frontend/test/routes/MapView/ImportDialogBox.spec.js
|
metamaps/metamaps
|
/* global describe, it */
import React from 'react'
import ImportDialogBox from '../../../src/routes/MapView/ImportDialogBox.js'
import Dropzone from 'react-dropzone'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import sinon from 'sinon'
describe('ImportDialogBox', function() {
const csvExport = sinon.spy()
const jsonExport = sinon.spy()
const onExport = format => () => {
if (format === 'csv') {
csvExport()
} else if (format === 'json') {
jsonExport()
}
}
const testExportButton = ({ description, cssClass, exporter }) => {
it(description, () => {
const wrapper = shallow(<ImportDialogBox onExport={onExport} />)
const button = wrapper.find(cssClass)
expect(button).to.exist
button.simulate('click')
expect(exporter).to.have.property('callCount', 1)
})
}
testExportButton({
description: 'has an Export CSV button',
cssClass: '.export-csv',
exporter: csvExport
})
testExportButton({
description: 'has an Export JSON button',
cssClass: '.export-json',
exporter: jsonExport
})
it('has a Download screenshot button', () => {
const downloadScreenshot = sinon.spy()
const wrapper = shallow(<ImportDialogBox onExport={() => null} downloadScreenshot={downloadScreenshot} />)
const button = wrapper.find('.download-screenshot')
expect(button).to.exist
button.simulate('click')
expect(downloadScreenshot).to.have.property('callCount', 1)
})
it('has a file uploader', () => {
const uploadedFile = {}
const onFileAdded = sinon.spy()
const wrapper = shallow(<ImportDialogBox onExport={() => null} onFileAdded={onFileAdded} />)
const dropzone = wrapper.find(Dropzone)
dropzone.props().onDropAccepted([uploadedFile], { preventDefault: () => {} })
expect(onFileAdded).to.have.property('callCount', 1)
expect(onFileAdded.calledWith(uploadedFile)).to.equal(true)
})
})
|
client/modules/App/components/Footer/Footer.js
|
thanhdatvo/tuoihoctro.react
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
// Import Style
import styles from './Footer.css';
// Import Images
import bg from '../../header-bk.png';
export function Footer() {
return (
<div className={styles.footer} style={{ background: `#FFF url(${bg}) center` }}>
<div >
<p>About Us | Privacy Policy | Terms of Use | DMCA | Rss Feeds | Contact Us</p>
<p>© 2017 <FormattedMessage id="twitterMessage" /></p>
</div>
</div>
);
}
export default Footer;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/action/spellcheck.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSpellcheck = (props) => (
<SvgIcon {...props}>
<path d="M12.45 16h2.09L9.43 3H7.57L2.46 16h2.09l1.12-3h5.64l1.14 3zm-6.02-5L8.5 5.48 10.57 11H6.43zm15.16.59l-8.09 8.09L9.83 16l-1.41 1.41 5.09 5.09L23 13l-1.41-1.41z"/>
</SvgIcon>
);
ActionSpellcheck.displayName = 'ActionSpellcheck';
ActionSpellcheck.muiName = 'SvgIcon';
export default ActionSpellcheck;
|
app/components/ListTitle/index.js
|
brentvatne/react-conf-app
|
// @flow
import React from 'react';
import { PixelRatio, Text, View } from 'react-native';
import theme from '../../theme';
type Props = {
bordered?: boolean,
text: string,
};
export default function ListTitle({ bordered, text }: Props) {
const styles = {
text: {
color: theme.color.text,
fontSize: theme.fontSize.xsmall,
fontWeight: '500',
lineHeight: theme.fontSize.large,
},
view: {
backgroundColor: theme.color.sceneBg,
borderBottomColor: theme.color.gray20,
borderBottomWidth: 1 / PixelRatio.get(),
paddingHorizontal: theme.fontSize.default + 5,
height: theme.listheader.height,
justifyContent: 'flex-end',
},
view__bordered: {
shadowColor: theme.color.gray20,
shadowOffset: { height: (-1) / PixelRatio.get(), width: 0 },
shadowOpacity: 1,
shadowRadius: 0,
},
};
return (
<View style={[styles.view, bordered && styles.view__bordered]}>
<Text style={styles.text}>{text.toUpperCase()}</Text>
</View>
);
}
|
src/components/fuel/FuelSavingsResults.spec.js
|
Opelvectra/hello.react.redux
|
import React from 'react';
import {shallow} from 'enzyme';
import FuelSavingsResults from './FuelSavingsResults';
describe('<FuelSavingsResults />', () => {
it('should display savings when savings exist', () => {
const savings = {
monthly: '10',
annual: '120',
threeYear: '360'
};
const wrapper = shallow(<FuelSavingsResults savings={savings}/>);
// console.log(wrapper.debug()); // View shallowly rendered component
const actual = wrapper.find('.fuel-savings-label').text();
const expected = 'Savings';
expect(actual).toEqual(expected);
});
it('should give values a \'savings\' class when savings exist', () => {
const savings = {
monthly: '10',
annual: '120',
threeYear: '360'
};
const wrapper = shallow(<FuelSavingsResults savings={savings}/>);
const actual = wrapper.find('.savings').length;
const expected = 3;
expect(actual).toEqual(expected);
});
it('should display loss when savings don\'t exist', () => {
const savings = {
monthly: '-10',
annual: '-120',
threeYear: '-360'
};
const wrapper = shallow(<FuelSavingsResults savings={savings}/>);
const actual = wrapper.find('.fuel-savings-label').text();
const expected = 'Loss';
expect(actual).toEqual(expected);
});
it('should give values a \'loss\' class when savings don\'t exist', () => {
const savings = {
monthly: '-10',
annual: '-120',
threeYear: '-360'
};
const wrapper = shallow(<FuelSavingsResults savings={savings}/>);
const actual = wrapper.find('.loss').length;
const expected = 3;
expect(actual).toEqual(expected);
});
});
|
packages/material-ui-icons/legacy/SignalWifi1BarSharp.js
|
lgollut/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z" /><path d="M6.67 14.86L12 21.49v.01l.01-.01 5.33-6.63C17.06 14.65 15.03 13 12 13s-5.06 1.65-5.33 1.86z" /></React.Fragment>
, 'SignalWifi1BarSharp');
|
src/screens/authorized/Setting.js
|
anhtuank7c/simple-chat
|
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { DrawerButton } from '../../components';
class Setting extends Component {
static navigationOptions = {
title: 'Setting',
header: (navigation) => ({
visible: true,
left: <DrawerButton navigation={navigation} />
})
}
render() {
return (
<View style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text>Setting</Text>
</View>
);
}
}
export default Setting;
|
ChatsUP/src/components/registerForm.js
|
michelmarcondes/ReactNativeStudies
|
import React, { Component } from 'react';
import {
View,
Text,
TextInput,
TouchableHighlight,
StyleSheet,
ImageBackground,
StatusBar,
ActivityIndicator,
KeyboardAvoidingView
} from 'react-native';
import { connect } from 'react-redux';
import {
changeEmail,
changePassword,
changeName,
registerUser
} from '../actions/authActions';
const bgImage = require('../assets/bg.png');
class RegisterForm extends Component {
_registerUser() {
//destructuring assignment!!!
const { name, email, password } = this.props;
this.props.registerUser({ name, email, password });
}
renderRegisterButton() {
if (this.props.loadingRegister) {
return (
<ActivityIndicator size='large' />
);
}
return (
<TouchableHighlight onPress={() => this._registerUser()}>
<Text style={styles.btnStyle}>Criar Conta</Text>
</TouchableHighlight>
);
}
render() {
return (
<ImageBackground source={bgImage} style={styles.bgImage}>
<KeyboardAvoidingView style={styles.container} behavior='padding'>
<StatusBar barStyle="light-content" />
<View style={styles.formContainer}>
<TextInput
value={this.props.name}
style={styles.formControl}
placeholder='Nome'
onChangeText={value => this.props.changeName(value)}
/>
<TextInput
value={this.props.email}
style={styles.formControl}
placeholder='E-mail'
onChangeText={value => this.props.changeEmail(value)}
keyboardType='email-address'
autoCapitalize='none'
/>
<TextInput
value={this.props.password}
style={styles.formControl}
placeholder='Senha'
onChangeText={value => this.props.changePassword(value)}
secureTextEntry
autoCapitalize='none'
/>
{
this.props.registerError
? <Text style={styles.txtError}>{this.props.registerError}</Text>
: null
}
</View>
<View style={styles.btnContainer}>
{ this.renderRegisterButton() }
</View>
</KeyboardAvoidingView>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'stretch',
backgroundColor: 'transparent',
padding: 10
},
formContainer: {
flex: 5,
justifyContent: 'center'
},
btnContainer: {
flex: 1,
alignItems: 'stretch',
justifyContent: 'center',
},
btnStyle: {
backgroundColor: '#115e54',
padding: 10,
color: '#fff',
textAlign: 'center',
fontSize: 16
},
formControl: {
fontSize: 20,
height: 45,
backgroundColor: '#fff',
paddingLeft: 10,
marginBottom: 8
},
bgImage: {
flex: 1,
width: null
},
txtError: {
color: 'red',
textAlign: 'center',
padding: 5,
backgroundColor: '#ffb6c1',
}
});
const mapStateToProps = (state) => (
{
email: state.AuthReducer.email,
password: state.AuthReducer.password,
name: state.AuthReducer.name,
registerError: state.AuthReducer.registerError,
loadingRegister: state.AuthReducer.loadingRegister
}
);
export default connect(
mapStateToProps,
{ changeEmail, changeName, changePassword, registerUser }
)(RegisterForm);
|
public/html/vendors/jstree/libs/jquery.js
|
K0rINf/rltzf2
|
/*! 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/Sidebar/AccountLocked/index.js
|
kleros/kleros-front
|
import React from 'react'
import FontAwesome from 'react-fontawesome'
import './AccountLocked.css'
const AccountLocked = () => (
<div className='account-locked-container'>
<span> MetaMask Account Locked </span>
<br />
<FontAwesome
name='lock'
size='3x'
style={{marginTop: '20px'}}
/>
</div>
)
export default AccountLocked
|
ajax/libs/rxjs/2.2.28/rx.all.compat.js
|
joeylakay/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: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// 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); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) ||
'_es6shim_iterator_';
// Firefox ships a partial implementation using the name @@iterator.
// https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14
// So use that name if we detect it.
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `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,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
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' || false;
}
// 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) {
// 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 == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// 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 || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
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 initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
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) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// 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;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, 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;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
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 () {
/**
* @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.
* @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 = schedulerProto['catch'] = 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.
* @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 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;
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;
}());
/**
* 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 runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
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) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} 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 scheduleMethod, clearMethod = noop;
(function () {
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;
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;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = 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 (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);
})();
/** @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();
}
});
});
};
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;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.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;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.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 (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* 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());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* 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.
* @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.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
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));
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();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
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();
}));
}
};
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 () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* 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 = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* 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;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* 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 or Promise.
* @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);
}
isPromise(result) && (result = observableFromPromise(result));
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, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* Converts an iterable into an Observable sequence
*
* @example
* var res = Rx.Observable.fromIterable(new Map());
* var res = Rx.Observable.fromIterable(new Set(), 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 generator sequence.
*/
Observable.fromIterable = function (iterable, scheduler) {
scheduler || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var iterator;
try {
iterator = iterable[$iterator$]();
} catch (e) {
observer.onError(e);
return;
}
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = iterator.next();
} catch (err) {
observer.onError(err);
return;
}
if (next.done) {
observer.onCompleted();
} else {
observer.onNext(next.value);
self();
}
});
});
};
/**
* 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();
}
});
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* 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 'just', and '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 = Observable.just = 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);
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
*
* @example
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @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 or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @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();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
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 or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @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;
}
isPromise(result) && (result = observableFromPromise(result));
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) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
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 or Promises 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 or Promises 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) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(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);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
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);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
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.
* @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]);
* @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++];
isPromise(current) && (current = observableFromPromise(current));
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.
* @param {Observable | Promise} other The observable sequence or Promise 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) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
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);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
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 | Promise} other Observable sequence or Promise 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) {
isPromise(other) && (other = observableFromPromise(other));
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; });
function next(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) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(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);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @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 (typeof skip !== 'number') {
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.
* @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;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
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 zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @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 (arguments.length === 1) {
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;
});
};
function concatMap(selector) {
return this.map(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
function concatMapObserver(onNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
observer.onNext(onNext(x, index++));
},
function (err) {
observer.onNext(onError(err));
observer.completed();
},
function () {
observer.onNext(onCompleted());
observer.onCompleted();
});
}).concatAll();
}
/**
* 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 which could be either an observable or Promise.
* @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.selectConcat = observableProto.concatMap = function (selector, resultSelector) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
if (typeof selector === 'function') {
return concatMap.call(this, selector);
}
return concatMap.call(this, function () {
return selector;
});
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = 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
* var res = 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(); });
* @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
* var res = 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(); });
* @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
* var res = 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(); });
* @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, 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);
var 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.
* @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));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function selectMany(selector) {
return this.select(function (x, i) {
var result = selector(x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).mergeObservable();
}
function selectManyObserver(onNext, onError, onCompleted) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
observer.onNext(onNext(x, index++));
},
function (err) {
observer.onNext(onError(err));
observer.completed();
},
function () {
observer.onNext(onCompleted());
observer.onCompleted();
});
}).mergeAll();
}
/**
* 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 which could be either an observable or Promise.
* @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, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.select(function (y) {
return resultSelector(x, y, i);
});
});
}
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 = observableProto.switchMap = 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));
});
};
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();
}
});
});
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (observer) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
observer.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
observer.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) {
list.push(x);
}
}, observer.onError.bind(observer), function () {
observer.onNext(list);
observer.onCompleted();
});
});
}
function firstOnly(x) {
if (x.length === 0) {
throw new Error(sequenceContainsNoElements);
}
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.aggregate(function (acc, x) { return acc + x; });
* 2 - res = source.aggregate(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 a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var seed, hasSeed, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
hasSeed = true;
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.reduce(function (acc, x) { return acc + x; });
* 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0);
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var seed, hasSeed;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @example
* var result = source.any();
* var result = source.any(function (x) { return x > 3; });
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = observableProto.any = function (predicate, thisArg) {
var source = this;
return predicate ?
source.where(predicate, thisArg).any() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
observer.onNext(false);
observer.onCompleted();
});
});
};
/**
* Determines whether an observable sequence is empty.
*
* @memberOf Observable#
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().select(function (b) { return !b; });
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
*
* 1 - res = source.all(function (value) { return value.length > 3; });
* @memberOf Observable#
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = observableProto.all = function (predicate, thisArg) {
return this.where(function (v) {
return !predicate(v);
}, thisArg).any().select(function (b) {
return !b;
});
};
/**
* Determines whether an observable sequence contains a specified element with an optional equality comparer.
* @example
* 1 - res = source.contains(42);
* 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; });
* @param value The value to locate in the source sequence.
* @param {Function} [comparer] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value.
*/
observableProto.contains = function (value, comparer) {
comparer || (comparer = defaultComparer);
return this.where(function (v) {
return comparer(v, value);
}).any();
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).count() :
this.aggregate(0, function (count) {
return count + 1;
});
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @example
* var res = source.sum();
* var res = source.sum(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).sum() :
this.aggregate(0, function (prev, curr) {
return prev + curr;
});
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) {
return comparer(x, y) * -1;
});
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @example
* var res = res = source.average();
* var res = res = source.average(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).average() :
this.scan({
sum: 0,
count: 0
}, function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}).finalValue().select(function (s) {
if (s.count === 0) {
throw new Error('The input sequence was empty');
}
return s.sum / s.count;
});
};
function sequenceEqualArray(first, second, comparer) {
return new AnonymousObservable(function (observer) {
var count = 0, len = second.length;
return first.subscribe(function (value) {
var equal = false;
try {
if (count < len) {
equal = comparer(value, second[count++]);
}
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
}, observer.onError.bind(observer), function () {
observer.onNext(count === len);
observer.onCompleted();
});
});
}
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
if (Array.isArray(second)) {
return sequenceEqualArray(first, second, comparer);
}
return new AnonymousObservable(function (observer) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (doner) {
observer.onNext(false);
observer.onCompleted();
} else {
ql.push(x);
}
}, observer.onError.bind(observer), function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (doner) {
observer.onNext(true);
observer.onCompleted();
}
}
});
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal, v;
if (ql.length > 0) {
v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
observer.onError(exception);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (donel) {
observer.onNext(false);
observer.onCompleted();
} else {
qr.push(x);
}
}, observer.onError.bind(observer), function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (donel) {
observer.onNext(true);
observer.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
});
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var i = index;
return source.subscribe(function (x) {
if (i === 0) {
observer.onNext(x);
observer.onCompleted();
}
i--;
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(argumentOutOfRange));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
observer.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @example
* var res = res = source.single();
* var res = res = source.single(function (x) { return x === 42; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate?
this.where(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue)
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
observer.onNext(x);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = res = source.firstOrDefault();
* var res = res = source.firstOrDefault(function (x) { return x > 3; });
* var res = source.firstOrDefault(function (x) { return x > 3; }, 0);
* var res = source.firstOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @example
* var res = source.last();
* var res = source.last(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = source.lastOrDefault();
* var res = source.lastOrDefault(function (x) { return x > 3; });
* var res = source.lastOrDefault(function (x) { return x > 3; }, 0);
* var res = source.lastOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
return new AnonymousObservable(function (observer) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, x, i, source);
} catch(e) {
observer.onError(e);
return;
}
if (shouldRun) {
observer.onNext(yieldIndex ? i : x);
observer.onCompleted();
} else {
i++;
}
}, observer.onError.bind(observer), function () {
observer.onNext(yieldIndex ? -1 : undefined);
observer.onCompleted();
});
});
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var 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, context)();
};
/**
* 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
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param {Function} 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 = arguments,
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();
};
};
/**
* 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 = immediateScheduler);
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 = immediateScheduler);
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 = root.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);
});
}
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);
});
}
// 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 (typeof el.item === 'function' && typeof el.length === 'number') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
/**
* 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) {
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
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
*/
var fromEventPattern = 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();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.subject.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
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) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previous = true;
var subscription =
combineLatestSource(
this.source,
this.subject.distinctUntilChanged(),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (results.shouldFire && previous) {
observer.onNext(results.data);
}
if (results.shouldFire && !previous) {
while (q.length > 0) {
observer.onNext(q.shift());
}
previous = true;
} else if (!results.shouldFire && !previous) {
q.push(results.data);
} else if (!results.shouldFire && previous) {
previous = false;
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
this.subject.onNext(false);
return subscription;
}
function PausableBufferedObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/**
* 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 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 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));
/** @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));
// Real Dictionary
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647];
var noSuchkey = "no such key";
var duplicatekey = "duplicate key";
function isPrime(candidate) {
if (candidate & 1 === 0) {
return candidate === 2;
}
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) {
return false;
}
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) {
return num;
}
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) {
return candidate;
}
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) {
return hash;
}
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) {
throw new Error(noSuchkey);
}
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') {
return stringHashFn(obj);
}
if (typeof obj === 'number') {
return numberHashFn(obj);
}
if (typeof obj === 'boolean') {
return obj === true ? 1 : 0;
}
if (obj instanceof Date) {
return obj.getTime();
}
if (obj.getHashCode) {
return obj.getHashCode();
}
var id = 17 * uniqueIdCounter++;
obj.getHashCode = function () { return id; };
return id;
};
} ());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
// Dictionary implementation
var Dictionary = function (capacity, comparer) {
if (capacity < 0) {
throw new Error('out of range')
}
if (capacity > 0) {
this._initialize(capacity);
}
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
};
Dictionary.prototype._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
Dictionary.prototype.count = function () {
return this.size;
};
Dictionary.prototype.add = function (key, value) {
return this._insert(key, value, true);
};
Dictionary.prototype._insert = function (key, value, add) {
if (!this.buckets) {
this._initialize(0);
}
var index3;
var num = getHashCode(key) & 2147483647;
var index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) {
throw new Error(duplicatekey);
}
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
Dictionary.prototype._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) {
numArray[index] = -1;
}
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) {
entryArray[index] = this.entries[index];
}
for (var index = this.size; index < prime; ++index) {
entryArray[index] = newEntry();
}
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
Dictionary.prototype.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
var index1 = num % this.buckets.length;
var index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
Dictionary.prototype.clear = function () {
var index, len;
if (this.size <= 0) {
return;
}
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
Dictionary.prototype._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
Dictionary.prototype.count = function () {
return this.size - this.freeCount;
};
Dictionary.prototype.tryGetValue = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) {
return this.entries[entry].value;
}
return undefined;
};
Dictionary.prototype.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
Dictionary.prototype.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) {
return this.entries[entry].value;
}
throw new Error(noSuchkey);
};
Dictionary.prototype.set = function (key, value) {
this._insert(key, value, false);
};
Dictionary.prototype.containskey = function (key) {
return this._findEntry(key) >= 0;
};
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable(),
leftDone = false,
leftId = 0,
leftMap = new Dictionary(),
rightDone = false,
rightId = 0,
rightMap = new Dictionary();
group.add(left.subscribe(function (value) {
var duration,
expire,
id = leftId++,
md = new SingleAssignmentDisposable(),
result,
values;
leftMap.add(id, value);
group.add(md);
expire = function () {
if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) {
observer.onCompleted();
}
return group.remove(md);
};
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); }));
values = rightMap.getValues();
for (var i = 0; i < values.length; i++) {
try {
result = resultSelector(value, values[i]);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}
}, observer.onError.bind(observer), function () {
leftDone = true;
if (rightDone || leftMap.count() === 0) {
observer.onCompleted();
}
}));
group.add(right.subscribe(function (value) {
var duration,
expire,
id = rightId++,
md = new SingleAssignmentDisposable(),
result,
values;
rightMap.add(id, value);
group.add(md);
expire = function () {
if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) {
observer.onCompleted();
}
return group.remove(md);
};
try {
duration = rightDurationSelector(value);
} catch (exception) {
observer.onError(exception);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); }));
values = leftMap.getValues();
for (var i = 0; i < values.length; i++) {
try {
result = resultSelector(values[i], value);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}
}, observer.onError.bind(observer), function () {
rightDone = true;
if (leftDone || rightMap.count() === 0) {
observer.onCompleted();
}
}));
return group;
});
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var nothing = function () {};
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary();
var rightMap = new Dictionary();
var leftID = 0;
var rightID = 0;
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftID++;
leftMap.add(id, s);
var i, len, leftValues, rightValues;
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
return;
}
observer.onNext(result);
rightValues = rightMap.getValues();
for (i = 0, len = rightValues.length; i < len; i++) {
s.onNext(rightValues[i]);
}
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
if (leftMap.remove(id)) {
s.onCompleted();
}
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftMap.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
nothing,
function (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
},
expire)
);
},
function (e) {
var leftValues = leftMap.getValues();
for (var i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
},
observer.onCompleted.bind(observer)));
group.add(right.subscribe(
function (value) {
var leftValues, i, len;
var id = rightID++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftMap.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
nothing,
function (e) {
leftValues = leftMap.getValues();
for (i = 0, len = leftMap.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
},
expire)
);
leftValues = leftMap.getValues();
for (i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onNext(value);
}
},
function (e) {
var leftValues = leftMap.getValues();
for (var i = 0, len = leftValues.length; i < len; i++) {
leftValues[i].onError(e);
}
observer.onError(e);
}));
return r;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, function () {
return observableEmpty();
}, function (_, window) {
return window;
});
}
function observableWindowWithBounaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var window = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
d.add(windowBoundaries.subscribe(function (w) {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
return r;
});
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var createWindowClose,
m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
window = new Subject();
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
createWindowClose = function () {
var m1, windowClose;
try {
windowClose = windowClosingSelector();
} catch (exception) {
observer.onError(exception);
return;
}
m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
createWindowClose();
}));
};
createWindowClose();
return r;
});
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var published = this.publish().refCount();
return [
published.filter(predicate, thisArg),
published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector) {
return enumerableFor(sources, resultSelector).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
scheduler || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
});
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
scheduler || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.select(
function (x) {
var curr = new ChainObservable(x);
if (chain) {
chain.onNext(x);
}
chain = curr;
return curr;
})
.doAction(
noop,
function (e) {
if (chain) {
chain.onError(e);
}
},
function () {
if (chain) {
chain.onCompleted();
}
})
.observeOn(scheduler)
.select(function (x, i, o) { return selector(x, i, o); });
});
};
var ChainObservable = (function (_super) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeObservable().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, _super);
function ChainObservable(head) {
_super.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwException(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = (function () {
/**
* @constructor
* @private
*/
function Map() {
this.keys = [];
this.values = [];
}
/**
* @private
* @memberOf Map#
*/
Map.prototype['delete'] = function (key) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.keys.splice(i, 1);
this.values.splice(i, 1);
}
return i !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.get = function (key, fallback) {
var i = this.keys.indexOf(key);
return i !== -1 ? this.values[i] : fallback;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.set = function (key, value) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.values[i] = value;
}
this.values[this.keys.push(key) - 1] = value;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.size = function () { return this.keys.length; };
/**
* @private
* @memberOf Map#
*/
Map.prototype.has = function (key) {
return this.keys.indexOf(key) !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.getKeys = function () { return this.keys.slice(0); };
/**
* @private
* @memberOf Map#
*/
Map.prototype.getValues = function () { return this.values.slice(0); };
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
*
* @param other Observable sequence to match in addition to the current pattern.
* @return Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
var patterns = this.patterns.slice(0);
patterns.push(other);
return new Pattern(patterns);
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
*
* @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.then = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
// Active Plan
function ActivePlan(joinObserverArray, onNext, onCompleted) {
var i, joinObserver;
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (i = 0; i < this.joinObserverArray.length; i++) {
joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
var values = this.joinObservers.getValues();
for (var i = 0, len = values.length; i < len; i++) {
values[i].queue.shift();
}
};
ActivePlan.prototype.match = function () {
var firstValues, i, len, isCompleted, values, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
firstValues = [];
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
if (this.joinObserverArray[i].queue[0].kind === 'C') {
isCompleted = true;
}
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
values = [];
for (i = 0; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
/** @private */
var JoinObserver = (function (_super) {
inherits(JoinObserver, _super);
/**
* @constructor
* @private
*/
function JoinObserver(source, onError) {
_super.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
this.onError(notification.exception);
return;
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.error = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.completed = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.removeActivePlan = function (activePlan) {
var idx = this.activePlans.indexOf(activePlan);
this.activePlans.splice(idx, 1);
if (this.activePlans.length === 0) {
this.dispose();
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.then = function (selector) {
return new Pattern([this]).then(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var plans = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var activePlans = [],
externalSubscriptions = new Map(),
group,
i, len,
joinObserver,
joinValues,
outObserver;
outObserver = observerCreate(observer.onNext.bind(observer), function (exception) {
var values = externalSubscriptions.getValues();
for (var j = 0, jlen = values.length; j < jlen; j++) {
values[j].onError(exception);
}
observer.onError(exception);
}, observer.onCompleted.bind(observer));
try {
for (i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
if (activePlans.length === 0) {
outObserver.onCompleted();
}
}));
}
} catch (e) {
observableThrow(e).subscribe(observer);
}
group = new CompositeDisposable();
joinValues = externalSubscriptions.getValues();
for (i = 0, len = joinValues.length; i < len; i++) {
joinObserver = joinValues[i];
joinObserver.subscribe();
group.add(joinObserver);
}
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
var p = normalizeTime(period);
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime;
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
var now;
if (p > 0) {
now = scheduler.now();
d = d + p;
if (d <= now) {
d = now + p;
}
}
observer.onNext(count++);
self(d);
});
});
}
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
* 1 - res = Rx.Observable.timer(new Date());
* 2 - res = Rx.Observable.timer(new Date(), 1000);
* 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout);
*
* 5 - res = Rx.Observable.timer(5000);
* 6 - res = Rx.Observable.timer(5000, 1000);
* 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Absolute (specified as a Date object) or 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 (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
if (period === undefined) {
return observableTimerTimeSpan(dueTime, scheduler);
}
return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(dueTime, scheduler) {
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);
});
}
function observableDelayDate(dueTime, scheduler) {
var self = this;
return observableDefer(function () {
var timeSpan = dueTime - scheduler.now();
return observableDelayTimeSpan.call(self, timeSpan, scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - 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);
return dueTime instanceof Date ?
observableDelayDate.call(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan.call(this, dueTime, scheduler);
};
/**
* 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); })
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
*
* @example
* 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
if (timeShiftOrScheduler === undefined) {
timeShift = timeSpan;
}
if (scheduler === undefined) {
scheduler = timeoutScheduler;
}
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (typeof timeShiftOrScheduler === 'object') {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
var s;
if (isShift) {
s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
if (isSpan) {
s = q.shift();
s.onCompleted();
}
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(function (x) {
var i, s;
for (i = 0; i < q.length; i++) {
s = q[i];
s.onNext(x);
}
}, function (e) {
var i, s;
for (i = 0; i < q.length; i++) {
s = q[i];
s.onError(e);
}
observer.onError(e);
}, function () {
var i, s;
for (i = 0; i < q.length; i++) {
s = q[i];
s.onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @example
* 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items
* 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items
*
* @memberOf Observable#
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
scheduler || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var createTimer,
groupDisposable,
n = 0,
refCountDisposable,
s,
timerD = new SerialDisposable(),
windowId = 0;
groupDisposable = new CompositeDisposable(timerD);
refCountDisposable = new RefCountDisposable(groupDisposable);
createTimer = function (id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
var newId;
if (id !== windowId) {
return;
}
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
};
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
n++;
if (n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
if (newWindow) {
createTimer(newId);
}
}, function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* 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) {
other || (other = observableThrow(new Error('Timeout')));
scheduler || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
var createTimer = function () {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
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.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @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 Date values.
* @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.generateWithAbsoluteTime = 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.scheduleRecursiveWithAbsolute(scheduler.now(), 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();
}
});
});
};
/**
* 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.generateWithRelativeTime = 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]);
* 2 - res = source.skipUntilWithTime(5000, [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, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && observer.onNext(x); },
observer.onError.bind(observer),
observer.onCompleted.bind(observer)));
});
};
/**
* 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]);
* 2 - res = source.takeUntilWithTime(5000, [optional scheduler]);
* @param {Number | Date} 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, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (_super) {
function notImplemented() {
throw new Error('Not implemented');
}
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;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @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.
* @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.
* @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.
*/
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.
*/
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.
* @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;
}
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @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.
* @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.
* @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.
* @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.
* @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
*/
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 AnonymousObservable = Rx.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 setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
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 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));
/**
* 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) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
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));
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));
|
src/routes/dashboard/components/recentSales.js
|
yunqiangwu/kmadmin
|
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/tab.js
|
knledg/react-blur-admin
|
import React from 'react';
export const Tab = ({ title, onClick }) => {
return (
<a href='#' onClick={onClick}>{title}</a>
);
};
Tab.propTypes = {
title: React.PropTypes.string,
onClick: React.PropTypes.func,
name: React.PropTypes.string,
};
|
src/App.js
|
amir5000/react-native-manager-app
|
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import firebase from 'firebase';
import ReduxThunk from 'redux-thunk';
import reducers from './reducers';
import Router from './Router';
class App extends Component {
componentWillMount() {
const config = {
apiKey: "AIzaSyCmLAUJ10AR7VSQT6gRKpRTt_3Pjz6WP10",
authDomain: "manager-64de4.firebaseapp.com",
databaseURL: "https://manager-64de4.firebaseio.com",
storageBucket: "manager-64de4.appspot.com",
messagingSenderId: "239110067634"
};
firebase.initializeApp(config);
}
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<Router />
</Provider>
);
}
}
export default App;
|
Example/src/MinimalExample.android.js
|
Artirigo/react-native-kontaktio
|
import React, { Component } from 'react';
import { View, DeviceEventEmitter } from 'react-native';
import Kontakt from 'react-native-kontaktio';
const { connect, startScanning } = Kontakt;
export default class MinimalExample extends Component {
componentDidMount() {
connect()
.then(() => startScanning())
.catch(error => console.log('error', error));
DeviceEventEmitter.addListener(
'beaconsDidUpdate',
({ beacons, region }) => {
console.log('beaconsDidUpdate', beacons, region);
}
);
}
render() {
return <View />;
}
}
|
src/components/components/QuillEditor/SimpleEditor.js
|
anztrax/try-quill-editor
|
import React from 'react';
export default class SimpleEditor extends React.Component{
constructor(props){
super(props);
}
componentDidMount(){
const editor = new Quill(this.props.editorID,{theme: 'snow'});
}
render(){
return (
<div id={this.props.editorID}>
{this.props.children}
</div>
)
}
}
|
src/collections/Message/MessageItem.js
|
shengnian/shengnian-ui-react
|
import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A message list can contain an item.
*/
function MessageItem(props) {
const { children, className, content } = props
const classes = cx('content', className)
const rest = getUnhandledProps(MessageItem, props)
const ElementType = getElementType(MessageItem, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
MessageItem._meta = {
name: 'MessageItem',
parent: 'Message',
type: META.TYPES.COLLECTION,
}
MessageItem.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
MessageItem.defaultProps = {
as: 'li',
}
MessageItem.create = createShorthandFactory(MessageItem, content => ({ content }))
export default MessageItem
|
img/program_files/5cGM7SIftt_.js
|
wecodeharvard/wecodeharvard.github.io
|
/*!CK:1898010989!*//*1418624704,*/
if (self.CavalryLogger) { CavalryLogger.start_js(["S1Vjf"]); }
__d("ChatOptions",["Arbiter","ChannelConstants","JSLogger","PresenceUtil","copyProperties","ChatOptionsInitialData"],function(a,b,c,d,e,f,g,h,i,j,k){var l=i.create('chat_options'),m={};(function(){var o=b('ChatOptionsInitialData');for(var p in o){var q=o[p];m[p]=!!q;}})();var n=k(new g(),{getSetting:function(o){return m[o];},setSetting:function(o,p,q){if(this.getSetting(o)==p)return;if(q){q='from_'+q;l.log(q,{name:o,new_value:p,old_value:this.getSetting(o)});}m[o]=!!p;g.inform('chat/option-changed',{name:o,value:p});}});g.subscribe(h.getArbiterType('setting'),function(o,p){var q=p.obj;if(q.window_id===j.getSessionID())return;n.setSetting(q.setting,!!q.value,'channel');});g.subscribe(i.DUMP_EVENT,function(o,p){p.chat_options=m;});e.exports=n;},null);
__d("SyncRequestTitle.react",["React","fbt","cx"],function(a,b,c,d,e,f,g,h,i){var j=g.createClass({displayName:"SyncRequestTitle",propTypes:{appName:g.PropTypes.string.isRequired,isSender:g.PropTypes.bool.isRequired,receiverName:g.PropTypes.string.isRequired,senderName:g.PropTypes.string.isRequired},render:function(){if(this.props.isSender){return (g.createElement("div",null,h._("Waiting for {receiver} to accept your invite to play {app_name}.",[h.param("receiver",g.createElement("span",{className:"_dg4"},this.props.receiverName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}else return (g.createElement("div",null,h._("{sender} wants to play {app_name} with you, right now.",[h.param("sender",g.createElement("span",{className:"_dg4"},this.props.senderName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}});e.exports=j;},null);
__d("SyncRequestAcceptedMessage.react",["React","fbt","cx"],function(a,b,c,d,e,f,g,h,i){var j=g.createClass({displayName:"SyncRequestAcceptedMessage",propTypes:{appName:g.PropTypes.string.isRequired,isSender:g.PropTypes.bool.isRequired,receiverName:g.PropTypes.string.isRequired,senderName:g.PropTypes.string.isRequired},render:function(){if(this.props.isSender){return (g.createElement("div",null,h._("{receiver} accepted your invite to play {app_name}.",[h.param("receiver",g.createElement("span",{className:"_dg4"},this.props.receiverName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}else return (g.createElement("div",null,h._("You accepted an invite from {sender} to play {app_name}.",[h.param("sender",g.createElement("span",{className:"_dg4"},this.props.senderName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}});e.exports=j;},null);
__d("SyncRequestRejectedMessage.react",["React","fbt","Link.react","cx","URI","AsyncRequest"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m=g.createClass({displayName:"SyncRequestRejectedMessage",propTypes:{requestId:g.PropTypes.string.isRequired,app:g.PropTypes.object.isRequired,isSender:g.PropTypes.bool.isRequired,receiver:g.PropTypes.object.isRequired,sender:g.PropTypes.object.isRequired},render:function(){if(this.props.isSender){return (g.createElement("div",null,h._("{receiver} declined your invite to play {app_name}.",[h.param("receiver",g.createElement("span",{className:"_dg4"},this.props.receiver.name)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.app.name))])));}else return (g.createElement("div",null,h._("You declined an invite from {sender} to play {app_name}.",[h.param("sender",g.createElement("span",{className:"_dg4"},this.props.sender.name)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.app.name))]),g.createElement("div",{className:"_13n7"},g.createElement("div",null,g.createElement(i,{onClick:this._submitBlockApp},h._("Block {app}",[h.param("app",this.props.app.name)]))),g.createElement("div",null,g.createElement(i,{onClick:this._submitBlockUser},h._("Block requests from {sender}",[h.param("sender",this.props.sender.name)]))))));},_submitBlockApp:function(){var n=new k('/games/block_app/'),o=new l().setURI(n);o.setData({app_id:this.props.app.id,source:'sync_request'});o.send();},_submitBlockUser:function(){var n=new k('/games/block_user/'),o=new l().setURI(n);o.setData({app_id:this.props.app.id,blockee_uid:this.props.sender.id});o.send();}});e.exports=m;},null);
__d("SyncRequestExpiredMessage.react",["React","fbt","cx"],function(a,b,c,d,e,f,g,h,i){var j=g.createClass({displayName:"SyncRequestExpiredMessage",propTypes:{appName:g.PropTypes.string.isRequired,isSender:g.PropTypes.bool.isRequired,receiverName:g.PropTypes.string.isRequired,senderName:g.PropTypes.string.isRequired},render:function(){if(this.props.isSender){return (g.createElement("div",null,h._("{receiver} missed your invite to play {app_name}.",[h.param("receiver",g.createElement("span",{className:"_dg4"},this.props.receiverName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}else return (g.createElement("div",null,h._("You missed an invite from {sender} to play {app_name}.",[h.param("sender",g.createElement("span",{className:"_dg4"},this.props.senderName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}});e.exports=j;},null);
__d("SyncRequestCanceledMessage.react",["React","fbt","cx"],function(a,b,c,d,e,f,g,h,i){var j=g.createClass({displayName:"SyncRequestCanceledMessage",propTypes:{appName:g.PropTypes.string.isRequired,isSender:g.PropTypes.bool.isRequired,receiverName:g.PropTypes.string.isRequired,senderName:g.PropTypes.string.isRequired},render:function(){if(this.props.isSender){return (g.createElement("div",null,h._("You canceled an invite to {receiver} to play {app_name}.",[h.param("receiver",g.createElement("span",{className:"_dg4"},this.props.receiverName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}else return (g.createElement("div",null,h._("{sender} canceled an invitation to play {app_name}.",[h.param("sender",g.createElement("span",{className:"_dg4"},this.props.senderName)),h.param("app_name",g.createElement("span",{className:"_dg5"},this.props.appName))])));}});e.exports=j;},null);
__d("SyncRequestTimer.react",["React","fbt"],function(a,b,c,d,e,f,g,h){function i(k){if(k){k=Math.ceil(k);var l=k%60;if(l<10)l='0'+l;var m=Math.floor(k/60);return m+':'+l;}else return "0:00";}var j=g.createClass({displayName:"SyncRequestTimer",propTypes:{timeRemaining:g.PropTypes.number.isRequired,isSender:g.PropTypes.bool.isRequired,receiverName:g.PropTypes.string.isRequired},render:function(){if(this.props.isSender){return (g.createElement("div",null,h._("({time_remaining} remaining)",[h.param("time_remaining",i(this.props.timeRemaining))])));}else return (g.createElement("div",null,h._("You have {time_remaining} to accept.",[h.param("time_remaining",i(this.props.timeRemaining))])));}});e.exports=j;},null);
__d("XSyncRequestSubmitControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/platform\/games\/sync_requests\/submit\/",{request_id:{type:"Int",required:true},sender:{type:"Int",required:true},action:{type:"Int",required:true}});},null);
__d("SyncRequest.react",["Arbiter","AsyncRequest","ChannelConstants","React","SyncRequestStatusEnum","SyncRequestTitle.react","SyncRequestAcceptedMessage.react","SyncRequestRejectedMessage.react","SyncRequestExpiredMessage.react","SyncRequestCanceledMessage.react","SyncRequestTimer.react","XUIButton.react","XSyncRequestSubmitControllerURIBuilder","cx","fbt","getObjectValues"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v){var w=j.createClass({displayName:"SyncRequest",propTypes:{app:j.PropTypes.object.isRequired,creationTime:j.PropTypes.number.isRequired,requestId:j.PropTypes.string.isRequired,receiver:j.PropTypes.object.isRequired,sender:j.PropTypes.object.isRequired,status:j.PropTypes.oneOf(v(k)).isRequired,timeout:j.PropTypes.number.isRequired,timeRemaining:j.PropTypes.number.isRequired,viewerId:j.PropTypes.number.isRequired,onStatusUpdate:j.PropTypes.func},componentWillMount:function(){if(this.props.status===k.PENDING){var x=g.subscribe(i.getArbiterType('sync_request_updated'),function(aa,ba){ba=ba.obj;if(ba.id.toString()!==this.props.requestId)return;this.setState({status:ba.status});}.bind(this));this.setState({statusEvent:x});}var y=null;if(this.props.status===k.PENDING){var z=function(){this.setState({time_remaining:(this.state.time_remaining-1)});if(this.state.time_remaining<=0){clearInterval(this.state.counter);var aa={counter:null,time_remaining:0};if(this.state.status===k.PENDING)aa.status=k.EXPIRED;this.setState(aa);}};y=setInterval(z.bind(this),1000);}this.setState({time_remaining:this.props.timeRemaining,counter:y});},componentWillUnmount:function(){if(this.state.counter)clearInterval(this.state.counter);g.unsubscribe(this.state.statusEvent);},getInitialState:function(){return {buttonsDisabled:false,time:Date.now(),status:this.props.status,viewerIsSender:this.props.viewerId===this.props.sender.id};},componentDidUpdate:function(x,y){if(this.props.status!=k.PENDING)this.state.status=this.props.status;if(this.props.onStatusUpdate)this.props.onStatusUpdate(this.state.status,y.status);},render:function(){var x;switch(this.state.status){case k.PENDING:var y;if(!this.state.viewerIsSender){y=[j.createElement(r,{use:"confirm",onClick:this._handleAccept,disabled:this.state.buttonsDisabled,label:"Accept"}),j.createElement(r,{use:"default",onClick:this._handleReject,disabled:this.state.buttonsDisabled,label:"Decline"})];}else y=j.createElement(r,{use:"default",onClick:this._handleCancel,disabled:this.state.buttonsDisabled,label:"Cancel"});x=(j.createElement("div",null,j.createElement("div",{className:"_372m"},j.createElement(l,{appName:this.props.app.name,isSender:this.state.viewerIsSender,receiverName:this.props.receiver.name,senderName:this.props.sender.name})),j.createElement("div",{className:"_372n"},j.createElement(q,{isSender:this.state.viewerIsSender,timeRemaining:this.state.time_remaining,receiverName:this.props.receiver.name})),j.createElement("div",{className:"_372o"},y)));break;case k.ACCEPTED:x=j.createElement("div",{className:"_372p mvs"},j.createElement(m,{appName:this.props.app.name,isSender:this.state.viewerIsSender,receiverName:this.props.receiver.name,senderName:this.props.sender.name}));break;case k.REJECTED:x=j.createElement("div",{className:"_372p mvs"},j.createElement(n,{requestId:this.props.requestId,app:this.props.app,isSender:this.state.viewerIsSender,receiver:this.props.receiver,sender:this.props.sender}));break;case k.EXPIRED:x=j.createElement("div",{className:"_372p mvs"},j.createElement(o,{appName:this.props.app.name,isSender:this.state.viewerIsSender,receiverName:this.props.receiver.name,senderName:this.props.sender.name}));break;case k.CANCELED:x=j.createElement("div",{className:"_372p mvs"},j.createElement(p,{appName:this.props.app.name,isSender:this.state.viewerIsSender,receiverName:this.props.receiver.name,senderName:this.props.sender.name}));break;default:throw new Error('The request status `%s` is unknown.',this.state.status);}return (j.createElement("div",{className:"_372q"},x));},_handleAccept:function(){this._handleStatusUpdate(k.ACCEPTED);var x=window.open(this.props.app.uri);if(x)x.focus();},_handleReject:function(){this._handleStatusUpdate(k.REJECTED);},_handleCancel:function(){this._handleStatusUpdate(k.CANCELED);},_handleStatusUpdate:function(x){this.setState({status:x,buttonsDisabled:true});var y=new s().setInt('request_id',this.props.requestId).setInt('sender',this.props.sender.id).setInt('action',x).getURI();new h().setURI(y).setHandler(function(z){this.setState({status:x});}.bind(this)).setErrorHandler(function(z){this.setState({buttonsDisabled:false});}.bind(this)).send();}});e.exports=w;},null);
__d("AbstractDialog.react",["DialogX","LayerHideOnBlur","ReactPropTypes","copyProperties","merge"],function(a,b,c,d,e,f,g,h,i,j,k){var l={createSpec:function(m){return {displayName:m.displayName,propTypes:{behaviors:i.object,className:i.string,modal:i.bool,autohide:i.number,width:i.number,titleID:i.string,causalElement:i.object,causalElementRef:i.string,shown:i.bool,layerHideOnBlur:i.bool,fixedTopPosition:i.number},createLayer:function(n){var o=this.props.className,p=j({width:this.props.width,xui:true,autohide:this.props.autohide,classNames:o?o.split(' '):null,titleID:this.props.titleID,causalElement:this._getCausalElement(),fixedTopPosition:this.props.fixedTopPosition},m||{}),q=k(m.addedBehaviors,this.props.behaviors);if(this.props.layerHideOnBlur!==false)q.LayerHideOnBlur=h;p.addedBehaviors=this.enumerateBehaviors(q);var r=new g(p,n);r.conditionShow(this.props.shown);return r;},receiveProps:function(n){this.updateBehaviors(n.behaviors);if(this.layer){this.layer.setCausalElement(this._getCausalElement());this.layer.conditionShow(n.shown);this.layer.setWidth(n.width);n.shown&&this.layer.updatePosition();}},_getCausalElement:function(){var n;if(this.props.causalElementRef){n=this.getNodeForOwnerRef(this.props.causalElementRef);}else n=this.props.causalElement;return n;}};}};e.exports=l;},null);
__d("XUIBadge.react",["React","cx","invariant","joinClasses"],function(a,b,c,d,e,f,g,h,i,j){function k(m){return parseInt(m,10)===m;}var l=g.createClass({displayName:"XUIBadge",propTypes:{type:g.PropTypes.oneOf(['regular','special']),count:g.PropTypes.number.isRequired,maxcount:g.PropTypes.number},getDefaultProps:function(){return {type:'regular',maxcount:20};},render:function(){var m=this.props.type,n=this.props.count,o=this.props.maxcount;i(k(n));i(k(o));var p=(("_5ugh")+(n>o?' '+"_5ugi":'')+(m==='regular'?' '+"_5ugf":'')+(m==='special'?' '+"_5ugg":'')+(n===0?' '+"hidden_elem":''));return (g.createElement("span",g.__spread({},this.props,{className:j(this.props.className,p),type:null}),n>o?o+'+':n));}});e.exports=l;},null);
__d("XUIDialog.react",["AbstractDialog.react","LayerFadeOnShow","ReactLayer"],function(a,b,c,d,e,f,g,h,i){var j=i.createClass(g.createSpec({displayName:'XUIDialog',addedBehaviors:{LayerFadeOnShow:h}}));e.exports=j;},null);
__d("AbstractTextFieldMixin.react",["React","Keys","cx","invariant","joinClasses","cloneWithProps"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m={propTypes:{value:g.PropTypes.string,placeholder:g.PropTypes.string,tabIndex:g.PropTypes.string,maxLength:g.PropTypes.number,autoComplete:g.PropTypes.string,onBackspace:g.PropTypes.func,onBackTab:g.PropTypes.func,onBlur:g.PropTypes.func,onChange:g.PropTypes.func,onDownArrow:g.PropTypes.func,onEnter:g.PropTypes.func,onEscape:g.PropTypes.func,onFocus:g.PropTypes.func,onKeyDown:g.PropTypes.func,onLeftArrow:g.PropTypes.func,onNoShiftEnter:g.PropTypes.func,onRightArrow:g.PropTypes.func,onShiftEnter:g.PropTypes.func,onShiftDownArrow:g.PropTypes.func,onShiftUpArrow:g.PropTypes.func,onTab:g.PropTypes.func,onUpArrow:g.PropTypes.func,type:g.PropTypes.string,autoCapitalize:g.PropTypes.string,autoCorrect:g.PropTypes.string},getInitialState:function(){return {focused:false,value:this.props.defaultValue||''};},getValue:function(){return this.props.value!=null?this.props.value:this.state.value;},onInputKeyDown:function(n){var o=this.props,p=n.keyCode,q=n.shiftKey;if(p===h.BACKSPACE&&!q&&o.onBackspace){o.onBackspace(n);}else if(p===h.TAB&&!q&&o.onTab){o.onTab(n);}else if(p===h.TAB&&q&&o.onBackTab){o.onBackTab(n);}else if(p===h.UP){if(q){if(o.onShiftUpArrow)o.onShiftUpArrowAttempt(n);}else if(o.onUpArrow)o.onUpArrow(n);}else if(p===h.DOWN&&o.onDownArrow){if(q){if(o.onShiftDownArrow)o.onShiftDownArrow(n);}else if(o.onDownArrow)o.onDownArrow(n);}else if(p===h.LEFT&&o.onLeftArrow){o.onLeftArrow(n);}else if(p===h.RIGHT&&o.onRightArrow){o.onRightArrow(n);}else if(p===h.RETURN){if(o.onEnter)o.onEnter(n);if(q){if(o.onShiftEnter)o.onShiftEnter(n);}else if(o.onNoShiftEnter)o.onNoShiftEnter(n);}else if(p===h.ESC&&o.onEscape)o.onEscape(n);if(o.onKeyDown)o.onKeyDown(n);},onInputChange:function(n){if(this.props.onChange)this.props.onChange(n);if(this.props.value==null)this.setState({value:n.target.value});},focusInput:function(){this.getTextFieldDOM().focus();},blurInput:function(){this.getTextFieldDOM().blur();},onInputBlur:function(event){if(this.props.onBlur)this.props.onBlur(event);if(!event.isDefaultPrevented())this.setState({focused:false});},onInputFocus:function(event){if(this.props.onFocus)this.props.onFocus(event);if(!event.isDefaultPrevented())this.setState({focused:true});},getTextFieldDOM:function(){return this.refs[this.getTextFieldRef()].getDOMNode();},getTextFieldRef:function(){return 'textField';},setTextFieldPropsOn:function(n){return l(n,{'aria-activedescendant':this.props['aria-activedescendant'],'aria-autocomplete':this.props['aria-autocomplete'],'aria-owns':this.props['aria-owns'],'data-testid':this.props['data-testid'],ref:this.getTextFieldRef(),role:this.props.role,autoCapitalize:this.props.autoCapitalize,autoComplete:this.props.autoComplete,autoCorrect:this.props.autoCorrect,onKeyDown:this.onInputKeyDown,onBlur:this.onInputBlur,onFocus:this.onInputFocus,onChange:this.onInputChange,disabled:this.props.disabled,defaultValue:this.props.defaultValue,name:this.props.name,value:this.getValue(),id:this.props.id,maxLength:this.props.maxLength,min:this.props.min,max:this.props.max,title:this.props.title,type:this.props.type||n.props.type});},render:function(){var n=null;if(!this.getValue()){var o=(("_58ai")+(this.state.focused?' '+"_58aj":''));n=g.createElement("span",{className:o},this.props.placeholder);}var p=k(this.props.className,"_58ak");j(this.renderTextField);return (g.createElement("label",{className:p},{placeholder:n,textField:this.renderTextField()}));}};e.exports=m;},null);
__d("AbstractTextInput.react",["AbstractTextFieldMixin.react","React","cx"],function(a,b,c,d,e,f,g,h,i){var j=h.createClass({displayName:"AbstractTextInput",mixins:[g],renderTextField:function(){return this.setTextFieldPropsOn(h.createElement("input",{type:"text",className:"_58al",size:this.props.size,tabIndex:this.props.tabIndex,onClick:this.props.onClick,onKeyUp:this.props.onKeyUp,onPaste:this.props.onPaste}));}});e.exports=j;},null);
__d("filterObject",[],function(a,b,c,d,e,f){'use strict';var g=Object.prototype.hasOwnProperty;function h(i,j,k){if(!i)return null;var l={};for(var m in i)if(g.call(i,m)&&j.call(k,i[m],m,i))l[m]=i[m];return l;}e.exports=h;},null);
__d("XUIError",["ARIA","Bootloader","CSS","DataStore","DOM","Event","JSXDOM","Parent","Promise","cx","filterObject","getActiveElement","getElementText","invariant","isNode","memoize","merge","nl2br"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){'use strict';var y='data-xui-error-alignh',z='XUIError',aa='data-xui-error',ba="_1tp7",ca='data-xui-error-position';l.listen(document.documentElement,'mouseover',function(event){if(n.byClass(r(),ba))return;var qa=n.byClass(event.getTarget(),ba);if(qa){ma(qa);}else na();});l.listen(document.documentElement,'focusin',function(event){var qa=n.byClass(event.getTarget(),ba);if(qa){ma(qa);}else na();});l.listen(document.documentElement,'focusout',function(event){na();});var da=v(function(){return new o(function(qa,ra){h.loadModules(["ContextualDialog","ContextualLayerAutoFlip","ContextualLayerUpdateOnScroll","LayerRefocusOnHide","React"],function(sa,ta,ua,va,wa){var xa={ContextualDialog:sa,ContextualLayerAutoFlip:ta,ContextualLayerUpdateOnScroll:ua,LayerRefocusOnHide:va,React:wa};qa(w(xa,ea(xa)));});});});function ea(qa){var ra=qa.ContextualDialog,sa=qa.ContextualLayerAutoFlip,ta=qa.ContextualLayerUpdateOnScroll,ua=qa.LayerRefocusOnHide,va=m.div({className:"_1tp8"}),wa=(m.div({className:"_53ij _1tp9"},m.div({className:"_1tpa"}),va)),xa=new ra({addedBehaviors:[ta,sa],theme:{wrapperClassName:"_1tpb",arrowDimensions:{offset:12,length:16}}},wa);xa.disableBehavior(ua);xa.shouldSetARIAProperties(false);return {dialog:xa,dialogBodyNode:wa,dialogMessageNode:va};}var fa=null;function ga(qa){return w({message:qa.getAttribute(aa),position:qa.getAttribute(ca),alignh:qa.getAttribute(y)},j.get(qa,z));}function ha(qa,ra){j.set(qa,z,ra);}function ia(qa,ra){j.set(qa,z,w(j.get(qa,z),ra));}function ja(qa){j.remove(qa,z);}var ka=false,la=false;function ma(qa){da().done(function(ra){var sa=ra.React,ta=ra.dialog,ua=ra.dialogMessageNode,va=ga(qa),wa=va.message,xa=sa.isValidElement(wa);if(ka&&!xa)sa.unmountComponentAtNode(ua);if(xa){sa.render(wa,ua);}else{t(typeof wa==='string'||u(wa));if(typeof wa==='string')wa=x(wa);k.setContent(ua,wa);}ka=xa;ta.setContext(qa).setPosition(va.position||'right').setAlignment(va.alignh||(va.position==='above'||va.position==='below'?'right':null)).show();g.notify(s(ua));fa=qa;});la=true;}function na(){if(!la)return;da().done(function(qa){var ra=qa.React,sa=qa.dialog,ta=qa.dialogMessageNode;if(!fa)return;if(ka){ra.unmountComponentAtNode(ta);ka=false;}sa.hide();fa=null;});}function oa(qa){if(k.contains(qa,r()))ma(qa);}var pa={set:function(qa){var ra=qa.target,sa=qa.message,ta=qa.position,ua=qa.alignh;t(sa!==null);i.addClass(ra,ba);ia(ra,q({message:sa,position:ta,alignh:ua},function(va){return va!==(void 0);}));oa(ra);},clear:function(qa){i.removeClass(qa,ba);qa.removeAttribute(aa);ja(qa);if(qa===fa)na();},updatePosition:function(){if(!la)return;da().done(function(qa){var ra=qa.dialog;if(fa)ra.updatePosition();});},__setReactError:function(qa,ra){var sa=ra.message,ta=ra.position,ua=ra.alignh;t(sa!==null);ha(qa,{message:sa,position:ta,alignh:ua});oa(qa);},__clearReactError:function(qa){ja(qa);if(qa===fa)na();}};e.exports=pa;},null);
__d("XUIError.react",["React","ReactElement","XUIError","cx","joinClasses","merge","onlyChild"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){'use strict';var n="_1tp7",o=g.createClass({displayName:"ReactXUIError",propTypes:{xuiError:g.PropTypes.any,xuiErrorPosition:g.PropTypes.oneOf(['above','below','left','right']),xuiErrorAlignh:g.PropTypes.oneOf(['left','center','right'])},componentDidMount:function(){if(this.props.xuiError!=null)i.__setReactError(this.getDOMNode(),{message:this.props.xuiError,position:this.props.xuiErrorPosition,alignh:this.props.xuiErrorAlignh});},componentDidUpdate:function(){if(this.props.xuiError==null){i.__clearReactError(this.getDOMNode());}else i.__setReactError(this.getDOMNode(),{message:this.props.xuiError,position:this.props.xuiErrorPosition,alignh:this.props.xuiErrorAlignh});},componentWillUnmount:function(){i.__clearReactError(this.getDOMNode());},render:function(){var p=m(this.props.children);if(this.props.xuiError!=null)p=h.cloneAndReplaceProps(p,l(p.props,{className:k(p.props.className,n)}));return p;}});e.exports=o;},null);
__d("XUITextInput.react",["AbstractTextInput.react","React","XUIError.react","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j,k){var l=h.createClass({displayName:"XUITextInput",propTypes:Object.assign({},g.propTypes,i.propTypes),render:function(){var m=(("_55r1")+(this.props.height=='tall'?' '+"_55r2":'')),n=(h.createElement(g,h.__spread({},this.props,{ref:"textInput",className:k(this.props.className,m)})));return (h.createElement(i,h.__spread({},this.props),n));},focusInput:function(){this.refs.textInput.focusInput();}});e.exports=l;},null);
__d("md5",["str2rstr"],function(a,b,c,d,e,f,g){function h(u,v){var w=u[0],x=u[1],y=u[2],z=u[3];w=j(w,x,y,z,v[0],7,-680876936);z=j(z,w,x,y,v[1],12,-389564586);y=j(y,z,w,x,v[2],17,606105819);x=j(x,y,z,w,v[3],22,-1044525330);w=j(w,x,y,z,v[4],7,-176418897);z=j(z,w,x,y,v[5],12,1200080426);y=j(y,z,w,x,v[6],17,-1473231341);x=j(x,y,z,w,v[7],22,-45705983);w=j(w,x,y,z,v[8],7,1770035416);z=j(z,w,x,y,v[9],12,-1958414417);y=j(y,z,w,x,v[10],17,-42063);x=j(x,y,z,w,v[11],22,-1990404162);w=j(w,x,y,z,v[12],7,1804603682);z=j(z,w,x,y,v[13],12,-40341101);y=j(y,z,w,x,v[14],17,-1502002290);x=j(x,y,z,w,v[15],22,1236535329);w=k(w,x,y,z,v[1],5,-165796510);z=k(z,w,x,y,v[6],9,-1069501632);y=k(y,z,w,x,v[11],14,643717713);x=k(x,y,z,w,v[0],20,-373897302);w=k(w,x,y,z,v[5],5,-701558691);z=k(z,w,x,y,v[10],9,38016083);y=k(y,z,w,x,v[15],14,-660478335);x=k(x,y,z,w,v[4],20,-405537848);w=k(w,x,y,z,v[9],5,568446438);z=k(z,w,x,y,v[14],9,-1019803690);y=k(y,z,w,x,v[3],14,-187363961);x=k(x,y,z,w,v[8],20,1163531501);w=k(w,x,y,z,v[13],5,-1444681467);z=k(z,w,x,y,v[2],9,-51403784);y=k(y,z,w,x,v[7],14,1735328473);x=k(x,y,z,w,v[12],20,-1926607734);w=l(w,x,y,z,v[5],4,-378558);z=l(z,w,x,y,v[8],11,-2022574463);y=l(y,z,w,x,v[11],16,1839030562);x=l(x,y,z,w,v[14],23,-35309556);w=l(w,x,y,z,v[1],4,-1530992060);z=l(z,w,x,y,v[4],11,1272893353);y=l(y,z,w,x,v[7],16,-155497632);x=l(x,y,z,w,v[10],23,-1094730640);w=l(w,x,y,z,v[13],4,681279174);z=l(z,w,x,y,v[0],11,-358537222);y=l(y,z,w,x,v[3],16,-722521979);x=l(x,y,z,w,v[6],23,76029189);w=l(w,x,y,z,v[9],4,-640364487);z=l(z,w,x,y,v[12],11,-421815835);y=l(y,z,w,x,v[15],16,530742520);x=l(x,y,z,w,v[2],23,-995338651);w=m(w,x,y,z,v[0],6,-198630844);z=m(z,w,x,y,v[7],10,1126891415);y=m(y,z,w,x,v[14],15,-1416354905);x=m(x,y,z,w,v[5],21,-57434055);w=m(w,x,y,z,v[12],6,1700485571);z=m(z,w,x,y,v[3],10,-1894986606);y=m(y,z,w,x,v[10],15,-1051523);x=m(x,y,z,w,v[1],21,-2054922799);w=m(w,x,y,z,v[8],6,1873313359);z=m(z,w,x,y,v[15],10,-30611744);y=m(y,z,w,x,v[6],15,-1560198380);x=m(x,y,z,w,v[13],21,1309151649);w=m(w,x,y,z,v[4],6,-145523070);z=m(z,w,x,y,v[11],10,-1120210379);y=m(y,z,w,x,v[2],15,718787259);x=m(x,y,z,w,v[9],21,-343485551);u[0]=s(w,u[0]);u[1]=s(x,u[1]);u[2]=s(y,u[2]);u[3]=s(z,u[3]);}function i(u,v,w,x,y,z){v=s(s(v,u),s(x,z));return s((v<<y)|(v>>>(32-y)),w);}function j(u,v,w,x,y,z,aa){return i((v&w)|((~v)&x),u,v,y,z,aa);}function k(u,v,w,x,y,z,aa){return i((v&x)|(w&(~x)),u,v,y,z,aa);}function l(u,v,w,x,y,z,aa){return i(v^w^x,u,v,y,z,aa);}function m(u,v,w,x,y,z,aa){return i(w^(v|(~x)),u,v,y,z,aa);}function n(u){var v=u.length,w=[1732584193,-271733879,-1732584194,271733878],x;for(x=64;x<=u.length;x+=64)h(w,o(u.substring(x-64,x)));u=u.substring(x-64);var y=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(x=0;x<u.length;x++)y[x>>2]|=u.charCodeAt(x)<<((x&3)<<3);y[x>>2]|=128<<((x&3)<<3);if(x>55){h(w,y);for(x=0;x<16;x++)y[x]=0;}y[14]=v*8;h(w,y);return w;}function o(u){var v=[],w=0;while(w<64)v[w>>2]=u.charCodeAt(w++)|(u.charCodeAt(w++)<<8)|(u.charCodeAt(w++)<<16)|(u.charCodeAt(w++)<<24);return v;}var p='0123456789abcdef'.split('');function q(u){var v='',w=0;for(;w<4;w++)v+=p[(u>>((w<<3)+4))&15]+p[(u>>(w<<3))&15];return v;}function r(u){for(var v=0;v<u.length;v++)u[v]=q(u[v]);return u.join('');}var s=function(u,v){return (u+v)&4294967295;};function t(u){if(null===u||(void 0)===u){return null;}else{for(var v=0;v<u.length;v++)if(u[v]>"\u007F"){u=g(u);break;}return r(n(u));}}if(t('hello')!='5d41402abc4b2a76b9719d911017c592')s=function(u,v){var w=(u&65535)+(v&65535),x=(u>>16)+(v>>16)+(w>>16);return (x<<16)|(w&65535);};e.exports=t;},null);
__d("destroyOnUnload",["Run"],function(a,b,c,d,e,f,g){function h(i){g.onLeave(i);}e.exports=h;},null);
__d("BlobFactory",["emptyFunction"],function(a,b,c,d,e,f,g){var h,i=a.BlobBuilder||a.WebKitBlobBuilder||a.MozBlobBuilder||a.MSBlobBuilder;if(a.Blob){var j;try{new a.Blob();j=true;}catch(k){j=false;}h={getBlob:function(l,m){l=l||[];m=m||{};if(j){return new a.Blob(l,m);}else{var n=new i();for(var o=0;o<l.length;o++)n.append(l[o]);return n.getBlob(m.type);}},isSupported:g.thatReturnsTrue};}else h={getBlob:function(){},isSupported:g.thatReturnsFalse};e.exports=h;},null);
__d("Grid.react",["React","ReactChildren","cx","joinClasses"],function(a,b,c,d,e,f,g,h,i,j){var k=g.PropTypes,l=g.createClass({displayName:"Grid",propTypes:{cols:k.number.isRequired,fixed:k.bool,alignv:k.oneOf(['top','middle','bottom']),alignh:k.oneOf(['left','center','right']),spacing:k.string},render:function(){var o=h.count(this.props.children),p=[],q=[],r=0;h.forEach(this.props.children,function(s,t){if(s===null||s===(void 0))return;if(s.type!==m.type)s=g.createElement(m,null,s);s.props.alignv=s.props.alignv||this.props.alignv;s.props.alignh=s.props.alignh||this.props.alignh;if(this.props.spacing)n(s,this.props.spacing);q.push(s);r+=Math.max(s.props.colSpan||0,1);if(r%this.props.cols===0||t+1===o){if(this.props.fixed&&r<this.props.cols){for(var u=r;u<this.props.cols;u++)q.push(g.createElement(m,null));r=this.props.cols;}if(r===this.props.cols)n(q[q.length-1],"_51mw");p.push(g.createElement("tr",{className:"_51mx",key:t},q));q=[];r=0;}}.bind(this));return (g.createElement("table",g.__spread({},this.props,{className:j(this.props.className,(("uiGrid")+(' '+"_51mz")+(this.props.fixed?' '+"_5f0n":''))),cellSpacing:"0",cellPadding:"0"}),g.createElement("tbody",null,p)));}}),m=g.createClass({displayName:"GridItem",propTypes:{alignv:k.oneOf(['top','middle','bottom']),alignh:k.oneOf(['left','center','right'])},render:function(){var o=j(this.props.className,(("_51m-")+(this.props.alignv==='top'?' '+"vTop":'')+(this.props.alignv==='middle'?' '+"vMid":'')+(this.props.alignv==='bottom'?' '+"vBot":'')+(this.props.alignh==='left'?' '+"hLeft":'')+(this.props.alignh==='center'?' '+"hCent":'')+(this.props.alignh==='right'?' '+"hRght":'')));return (g.createElement("td",g.__spread({},this.props,{className:o})));}}),n=function(o,p){o.props.className=j(o.props.className,p);};l.GridItem=m;e.exports=l;},null);
__d("swfobject",["AsyncRequest","Bootloader","CSS","copyProperties","htmlSpecialChars"],function(a,b,c,d,e,f,g,h,i,j,k){if(typeof l=="undefined")var l={};if(typeof l.util=="undefined")l.util={};if(typeof l.SWFObjectUtil=="undefined")l.SWFObjectUtil={};l.SWFObject=function(n,o,p,q,r,s,t,u,v,w){if(!document.getElementById)return;this.DETECT_KEY=w?w:'detectflash';this.skipDetect=l.util.getRequestParameter(this.DETECT_KEY);this.params={};this.variables={};this.attributes=[];this.fallback_html='';this.fallback_js_fcn=function(){};if(n)this.setAttribute('swf',n);if(o)this.setAttribute('id',o);if(p)this.setAttribute('width',p);if(q)this.setAttribute('height',q);this.installedVer=l.SWFObjectUtil.getPlayerVersion();if(r){if(!(r instanceof Array))r=[r];var x;r.forEach(function(aa){x=new l.PlayerVersion(aa.toString().split('.'));if(x.major==this.installedVer.major){this.setAttribute('version',x);return;}else if(!this.getAttribute('version')||x.major<this.getAttribute('version').major)this.setAttribute('version',x);}.bind(this));}if(!window.opera&&document.all&&this.installedVer.major>7)if(!l.unloadSet){l.SWFObjectUtil.prepUnload=function(){var aa=function(){},ba=function(){};window.attachEvent("onunload",l.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",l.SWFObjectUtil.prepUnload);l.unloadSet=true;}if(s)this.addParam('bgcolor',s);var y=t?t:'high';this.addParam('quality',y);this.setAttribute('useExpressInstall',false);this.setAttribute('doExpressInstall',false);var z=(u)?u:window.location;this.setAttribute('xiRedirectUrl',z);this.setAttribute('redirectUrl','');if(v)this.setAttribute('redirectUrl',v);};l.SWFObject.ieWorkaroundApplied=false;l.SWFObject.ensureIEWorkaroundAttached=function(){if(!l.SWFObject.ieWorkaroundApplied&&document.attachEvent){l.SWFObject.ieWorkaroundApplied=true;document.attachEvent('onpropertychange',l.SWFObject.onDocumentPropertyChange);}};l.SWFObject.onDocumentPropertyChange=function(event){if(event.propertyName=="title"){var n=document.title;if(n!=null&&n.indexOf('#!')!=-1){n=n.substring(0,n.indexOf('#!'));document.title=n;}}};j(l.SWFObject.prototype,{useExpressInstall:function(n){this.xiSWFPath=!n?"/swf/expressinstall.swf":n;this.setAttribute('useExpressInstall',true);},setAttribute:function(n,o){this.attributes[n]=o;},getAttribute:function(n){return this.attributes[n]||"";},addParam:function(n,o){this.params[n]=o;},getParams:function(){return this.params;},addVariable:function(n,o){this.variables[n]=o;},getVariable:function(n){return this.variables[n]||"";},getVariables:function(){return this.variables;},getVariablePairs:function(){var n=[],o,p=this.getVariables();for(o in p)n[n.length]=o+"="+p[o];return n.join('&');},getSWFHTML:function(){var n,o,p;if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute('swf',this.xiSWFPath);}o={type:'application/x-shockwave-flash',src:this.getAttribute('swf'),width:this.getAttribute('width'),height:this.getAttribute('height'),style:this.getAttribute('style')||'display: block;',id:this.getAttribute('id'),name:this.getAttribute('id')};var q=this.getParams();for(var r in q)o[r]=q[r];p=this.getVariablePairs();if(p)o.flashvars=p;n=m('embed',o,null);}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute('swf',this.xiSWFPath);}o={id:this.getAttribute('id'),classid:'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000',width:this.getAttribute('width'),height:this.getAttribute('height'),style:this.getAttribute('style')||'display: block;'};var s=m('param',{name:'movie',value:this.getAttribute('swf')},null),q=this.getParams();for(var r in q)s+=m('param',{name:r,value:q[r]},null);p=this.getVariablePairs();if(p)s+=m('param',{name:'flashvars',value:p},null);n=m('object',o,s);}return n;},write:function(n){if(this.getAttribute('useExpressInstall')){var o=new l.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(o)&&!this.installedVer.versionIsValid(this.getAttribute('version'))){this.setAttribute('doExpressInstall',true);this.addVariable("MMredirectURL",escape(this.getAttribute('xiRedirectUrl')));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}var p=(typeof n=='string')?document.getElementById(n):n;if(!p)return false;i.addClass(p,'swfObject');p.setAttribute('data-swfid',this.getAttribute('id'));if(this.skipDetect||this.getAttribute('doExpressInstall')||this.installedVer.versionIsValid(this.getAttribute('version'))){l.SWFObject.ensureIEWorkaroundAttached();p.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute('redirectUrl')!="")document.location.replace(this.getAttribute('redirectUrl'));var q=this.getAttribute('version').major+'.'+this.getAttribute('version').minor+'.'+this.getAttribute('version').release+'.'+this.getAttribute('version').build,r=this.installedVer.major+'.'+this.installedVer.minor+'.'+this.installedVer.release+'.'+this.installedVer.build;this.fallback_js_fcn(r,q);p.innerHTML=this.fallback_html;}return false;}});l.SWFObjectUtil.getPlayerVersion=function(){var n=new l.PlayerVersion([0,0,0,0]),o;if(navigator.plugins&&navigator.mimeTypes.length){for(var p=0;p<navigator.plugins.length;p++)try{var r=navigator.plugins[p];if(r.name=='Shockwave Flash'){o=new l.PlayerVersion(r.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+(r|d)|\s+b[0-9]+)/,".").split("."));if(typeof n=='undefined'||o.major>n.major||(o.major==n.major&&(o.minor>n.minor||(o.minor==n.minor&&(o.release>n.release||(o.release==n.release&&o.build>n.build))))))n=o;}}catch(q){}}else if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var s=1,t=3;while(s)try{t++;s=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+t);n=new l.PlayerVersion([t,0,0]);}catch(u){s=null;}}else{try{var s=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(v){try{var s=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");n=new l.PlayerVersion([6,0,21]);s.AllowScriptAccess="always";}catch(w){if(n.major==6)return n;}try{s=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(x){}}if(s!=null)n=new l.PlayerVersion(s.GetVariable("$version").split(" ")[1].split(","));}return n;};l.PlayerVersion=function(n){this.major=n[0]!=null?parseInt(n[0],10):0;this.minor=n[1]!=null?parseInt(n[1],10):0;this.release=n[2]!=null?parseInt(n[2],10):0;this.build=n[3]!=null?parseInt(n[3],10):0;};l.PlayerVersion.prototype.versionIsValid=function(n){if(this.major<n.major)return false;if(this.major>n.major)return true;if(this.minor<n.minor)return false;if(this.minor>n.minor)return true;if(this.release<n.release)return false;if(this.release>n.release)return true;if(this.build<n.build)return false;return true;};l.util={getRequestParameter:function(n){var o=document.location.search||document.location.hash;if(n==null)return o;if(o){var p=o.substring(1).split("&");for(var q=0;q<p.length;q++)if(p[q].substring(0,p[q].indexOf("="))==n)return p[q].substring((p[q].indexOf("=")+1));}return "";}};l.SWFObjectUtil.cleanupSWFs=function(){var n=document.getElementsByTagName("OBJECT");for(var o=n.length-1;o>=0;o--){n[o].style.display='none';for(var p in n[o])if(typeof n[o][p]=='function')n[o][p]=function(){};}};if(!document.getElementById&&document.all)document.getElementById=function(n){return document.all[n];};l.spawn_flash_update_dialog=function(){new g().setURI('/ajax/flash_update_dialog.php').setMethod('GET').setReadOnly(true).send();};l.showFlashErrorDialog=function(n,o){h.loadModules(["ErrorDialog"],function(p){p.show(n,o);});};function m(n,o,p){var q=/^[A-Za-z0-9\-]+$/;if(!n.match(q))throw new Error('Invalid tag '+n);var r='<'+n;for(var s in o){if(!s.match(q))throw new Error('Invalid attr '+s);r+=' '+s+'="'+k(o[s])+'"';}if(p===null){return r+'/>';}else return r+'>'+p+'</'+n+'>';}e.exports=a.deconcept||l;},null);
__d("SoundPlayer",["Arbiter","URI","createArrayFromMixed","swfobject"],function(a,b,c,d,e,f,g,h,i){var j=b('swfobject').SWFObject,k={},l=null,m=false,n='so_sound_player',o='/swf/SoundPlayer.swf?v=1',p='10.0.22.87',q=null;function r(z){var aa=h(z);if(!aa.getDomain())return h().setPath(aa.getPath()).toString();return z;}function s(z){var aa=h(z).getPath();if(/\.mp3$/.test(aa))return 'audio/mpeg';if(/\.og[ga]$/.test(aa))return 'audio/ogg';return '';}function t(){if(!q){var z=document.createElement('audio');if(!z||!z.canPlayType)return null;z.setAttribute('preload','auto');document.body.appendChild(z);q=z;}return q;}function u(){var z=document[n]||window[n];if(z)if(!z.playSound&&z.length)z=z[0];return (z&&z.playSound&&z.loopSound)?z:null;}function v(){return m;}function w(z,aa,ba){l={path:z,sync:aa,loop:ba};}function x(){m=true;if(l){var z=u();if(l.loop){z.loopSound(l.path,l.sync);}else z.playSound(l.path,l.sync);}}var y={init:function(z){z=i(z);var aa;for(var ba=0;ba<z.length;++ba){aa=z[ba];if(k[aa])return;}var ca=t();for(ba=0;ca&&ba<z.length;++ba){aa=z[ba];if(ca.canPlayType(aa)){k[aa]=true;return;}}k['audio/mpeg']=true;if(u())return;try{g.registerCallback(x,['sound/player_ready','sound/ready']);var ea=document.createElement('div');ea.id='sound_player_holder';document.body.appendChild(ea);var fa=new j(o,n,'1px','1px',[p],'#ffffff');fa.addParam('allowscriptaccess','always');fa.addParam('wmode','transparent');fa.addVariable('swf_id',n);fa.fallback_html=' ';fa.write(ea.id);window[n]=fa;g.inform('sound/player_ready');}catch(da){}},play:function(z,aa){z=i(z);var ba=t(),ca,da;for(var ea=0;ba&&ea<z.length;++ea){ca=z[ea];da=s(ca);if(!ba.canPlayType(da))continue;y.init([da]);ba.src=r(ca);if(aa){ba.setAttribute('loop','');}else ba.removeAttribute('loop');ba.play();return;}for(ea=0;ea<z.length;++ea){ca=r(z[ea]);da=s(ca);if(da!='audio/mpeg')continue;y.init([da]);var fa=u();if(!v()){w(ca,true,aa);return;}else if(fa){if(aa){fa.loopSound(ca,true);}else fa.playSound(ca,true);return;}}},stop:function(z){z=i(z);for(var aa=0;aa<z.length;++aa){var ba=r(z[aa]),ca=t(),da=u();if(ca&&ca.src==ba){ca.pause();ca.src=(void 0);}else da&&da.stopSound(ba);}}};e.exports=y;},null);
__d("SoundSynchronizer",["SoundPlayer","WebStorage","createArrayFromMixed"],function(a,b,c,d,e,f,g,h,i){var j='fb_sounds_playing3';function k(){var o=h.getLocalStorage();if(o)try{var q=o[j];if(q){q=JSON.parse(q);if(Array.isArray(q))return q;}}catch(p){}return [];}function l(o){var p=h.getLocalStorage();if(p){var q=k();q.push(o);while(q.length>5)q.shift();try{p[j]=JSON.stringify(q);}catch(r){}}}function m(o){return k().some(function(p){return p===o;});}var n={play:function(o,p,q){o=i(o);p=p||(o[0]+Math.floor(Date.now()/1000));if(m(p))return;g.play(o,q);l(p);},isSupported:function(){return !!h.getLocalStorage();}};e.exports=n;},null);
__d("SoundRPC",["Event","SoundSynchronizer"],function(a,b,c,d,e,f,g,h){function i(k,l,m){h.play(k,l,m);}var j={playLocal:i,playRemote:function(k,l,m,n){var o={paths:l,sync:m,loop:n};k.postMessage(JSON.stringify(o),'*');},supportsRPC:function(){return !!window.postMessage;},_listen:function(){g.listen(window,'message',function(k){if(!/\.facebook.com$/.test(k.origin))return;var l=JSON.parse(k.data||'{}');i(l.paths,l.sync,l.loop);});}};e.exports=j;},null);
__d("Sound",["SoundInitialData","SoundPlayer","SoundRPC","SoundSynchronizer","URI","UserAgent_DEPRECATED","isFacebookURI"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n=null,o={init:function(s){if(!n)h.init(s);},play:function(s,t,u){if(n){i.playRemote(n.contentWindow,s,t,false);}else i.playLocal(s,t,u);},stop:function(s){if(!n)h.stop(s);}},p=new k(location.href);if(p.getSubdomain()&&p.getSubdomain()!=='www')p.setSubdomain('www');var q=p.getDomain();function r(){if(l.ie()<9)return false;if(g.RPC_DISABLED)return false;return j.isSupported()&&i.supportsRPC();}if(m(p)&&location.host!==q&&r()){n=document.createElement('iframe');n.setAttribute('src','//'+q+'/sound_iframe.php');n.style.display='none';document.body.appendChild(n);}e.exports=o;},null);
__d("MercuryBrowserAlerts",["ArbiterMixin","ChatActivity","ChatConfig","ChatOptions","ChatTitleBarBlinker","MercuryThreadMuter","MercuryViewer","MessagingTag","Sound","copyProperties","MercuryThreads"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){var q=b('MercuryThreads').get();o.init(['audio/ogg','audio/mpeg']);function r(t){if(j.getSetting('sound'))o.play([i.get('sound.notif_ogg_url'),i.get('sound.notif_mp3_url')],t,false);}var s={messageReceived:function(t){if(m.isViewer(t.author)||!t.is_unread||(t.folder!=n.INBOX&&t.folder!=n.ARCHIVED))return;var u=t.thread_id,v=h.isActive();if(v){var w=false;s.inform('before-alert',{threadID:u,cancelAlert:function(){w=true;}});}q.getThreadMeta(u,function(x){var y=l.isThreadMuted(x);if(y)return;var z=t.timestamp;if(v){!w&&r(z);}else{k.blink(u,z);r(z);}k.blinkingElsewhere();}.bind(this));}};e.exports=p(s,g);},null);
__d("VideoCallRecordMessageDialog",["AsyncDialog","AsyncRequest","Dialog","URI","fbt"],function(a,b,c,d,e,f,g,h,i,j,k){var l={get:function(m,n){var o="Would you like to leave a message?",p="New Message";return new i().setTitle(k._("{firstname} is Unavailable",[k.param("firstname",n)])).setBody(o).setButtons([{name:'record-message',label:p},i.CANCEL]).setHandler(function(){var q=j('/ajax/messaging/composer.php').setQueryData({ids:[m],autoloadvideo:true}).toString();g.send(new h(q));});}};e.exports=l;},null);
__d("XBrowserNotSupportedDialogControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/videocall\/browser_not_supported\/",{user_id:{type:"Int"},warning:{type:"Bool"},__asyncDialog:{type:"Int"}});},null);
__d("FBRTCUnsupportedBrowserMessage",["AsyncDialog","AsyncRequest","XBrowserNotSupportedDialogControllerURIBuilder","FBRTCSoundController"],function(a,b,c,d,e,f,g,h,i,j){var k={_dialog:null,warnForOutgoingCall:function(l){var m=new i().setBool('warning',true).getURI();this._presentDialog(m,l);},showForOutgoingCall:function(){var l=new i().getURI();this._presentDialog(l);},showForIncomingCall:function(l,m){j.playIncomingRingtone(l,m,false);var n=new i().setInt('user_id',m).getURI();this._presentDialog(n);},dismiss:function(){if(this._dialog)this._dialog.hide();},_presentDialog:function(l,m){if(this._dialog)return;var n=new h(l);g.send(n,function(o){this._dialog=o;o.subscribe('hide',function(){this._dialog=null;if(m)m();}.bind(this));}.bind(this));}};e.exports=k;},null);
__d("ChatBehavior",["Arbiter","AvailableList","AvailableListConstants","copyProperties","MercuryConstants"],function(a,b,c,d,e,f,g,h,i,j){var k=b('MercuryConstants').ChatNotificationConstants,l=false,m=h.getWebChatNotification(),n=l,o=true,p=j(new g(),{ON_CHANGED:'changed',notifiesUserMessages:function(){return m!==k.NO_USER_MESSAGE_NOTIFICATION;},ignoresRemoteTabRaise:function(){return n;},showsTabUnreadUI:function(){return o;}});function q(){p.inform(p.ON_CHANGED);}h.subscribe(i.ON_CHAT_NOTIFICATION_CHANGED,function(){var r=m,s=h.getWebChatNotification();m=s;if(r!=s)q();});g.subscribe('chat/set_does_page_occlude_tabs',function(r,s){n=!!s;q();});g.subscribe('chat/set_show_tab_unread_ui',function(r,s){o=!!s;q();});e.exports=p;},null);
__d("MercuryShareAttachment.react",["Map","MercuryShareAttachmentReactShape","MercuryShareAttachmentRenderLocations","React","StoryAttachmentStyle","MercuryFallbackShareAttachment.react"],function(a,b,c,d,e,f,g,h,i,j,k){'use strict';var l=new g();l.set(k.FALLBACK,b('MercuryFallbackShareAttachment.react'));var m=j.createClass({displayName:"MercuryShareAttachment",propTypes:{attachment:h(),location:j.PropTypes.oneOf(i.getValues())},render:function(){var n=this.props.attachment;if(!n.style_list)return null;var o=null;for(var p=0;p<n.style_list.length;p++){o=l.get(n.style_list[p]);if(o)break;}if(!o)return null;return (j.createElement(o,{attachment:n,location:this.props.location}));}});e.exports=m;},null);
__d("WebMessengerEvents",["Arbiter","copyProperties"],function(a,b,c,d,e,f,g,h){var i=h(new g(),{MASTER_DOM_CHANGED:'master-dom-changed',DETAIL_DOM_CHANGED:'detail-dom-changed',FOCUS_COMPOSER:'focus-composer',FOCUS_SEARCH:'focus-search',FOCUS_AND_SELECT_SEARCH:'focus-and-select-search',STICKER_CLICKED:'sticker-clicked',SUBMIT_REPLY:'submit-reply',UPDATE_SELECTION:'update-selection',masterDOMChanged:function(){this.inform(i.MASTER_DOM_CHANGED);},detailDOMChanged:function(){this.inform(i.DETAIL_DOM_CHANGED);},focusComposer:function(){this.inform(i.FOCUS_COMPOSER);},focusSearch:function(){this.inform(i.FOCUS_SEARCH);},focusAndSelectSearch:function(){this.inform(i.FOCUS_AND_SELECT_SEARCH);},updateSelection:function(j){this.inform(i.UPDATE_SELECTION,j);},stickerClicked:function(j,k){this.inform(i.STICKER_CLICKED,{packID:j,stickerID:k});},submitReply:function(){this.inform(i.SUBMIT_REPLY);}});e.exports=i;},null);
__d("WebMessengerSubscriptionsHandler",["SubscriptionsHandler"],function(a,b,c,d,e,f,g){var h=new g('webmessenger');e.exports=h;},null);
__d("isWebMessengerURI",[],function(a,b,c,d,e,f){function g(h){return (/^(\/messages)/).test(h.getPath());}e.exports=g;},null);
__d("WebMessengerWidthControl",["Arbiter","CSS","CSSClassTransition","DOM","DOMDimensions","Event","Style","URI","ViewportBounds","WebMessengerEvents","WebMessengerSubscriptionsHandler","$","cx","csx","isWebMessengerURI","requestAnimationFrame","setTimeoutAcrossTransitions","shield","throttle"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y){var z=205,aa=981,ba=257,ca=18,da=848,ea=724,fa=.57,ga=56,ha,ia,ja;function ka(pa,qa,ra){this.masterChanged=pa;this.detailChaned=qa;q.addSubscriptions(l.listen(window,'resize',y(x(la,this,this),100)),g.subscribe(['sidebar/initialized','sidebar/show','sidebar/hide','minisidebar/show'],x(la,this,this),g.SUBSCRIBE_NEW));var sa=oa()?ga:0;if(ra)sa=z;this._width=oa()?0:da;ja=true;la(this,sa);}function la(pa,qa){var ra=o.getRight()+o.getLeft();ra=ra||qa||0;var sa=k.getViewportWithoutScrollbarDimensions().width-ra,ta=Math.round(Math.max(0,sa/2-aa/2));sa=aa+ta-ba;sa-=ca;sa=Math.max(ea,Math.min(da,sa));if(!isNaN(sa)&&pa._width!==sa){pa._width=sa;var ua=Math.round(sa/(1+fa)),va=sa-ua;pa.masterChanged(va);pa.detailChaned(ua);if(oa()){var wa=sa+ba;ma(function(){if(ia){document.body.className=ia;ia='';}na(wa+'px');h.removeClass(document.body,"_5uj5");ja&&p.detailDOMChanged();ja=false;},ia);}}}function ma(pa,qa){qa&&h.addClass(document.documentElement,"_5uj6");v(pa);qa&&w(h.removeClass.bind(null,document.documentElement,"_5uj6"),1000);}function na(pa){m.set(j.find(document,"div._uaw"),'width',pa);m.set(r('globalContainer'),'width',pa);}function oa(){if(!ha)ha=h.hasClass(document.body,"_6nw");return ha;}i.registerHandler(function(pa,qa,ra,sa){function ta(ua){return oa()&&u(n(ua));}if(ta(sa)){ia=qa;return true;}else if(ta(ra)){ma(function(){pa.className=qa;na('');},true);return true;}});e.exports=ka;},null);
__d("MercuryErrorInfo",["MercuryActionStatus","MercuryErrorType","fbt"],function(a,b,c,d,e,f,g,h,i){var j={getMessage:function(k){var l='';if(j.isConnectionError(k)){l="This message didn't send.";if(j.isTransient(k))l=i._("{message} Check your internet connection and click to try again.",[i.param("message",l)]);}else{if(k&&k.description){l=k.description;}else l="This message failed to send.";if(j.isTransient(k))l=i._("{message} Click to send again.",[i.param("message",l)]);}return l;},isConnectionError:function(k){if(k&&k.type==h.TRANSPORT)return k.code===1001||k.code===1004||k.code===1006;return false;},isTransient:function(k){return k&&k.is_transient;},isPermanent:function(k){return k?!this.isTransient(k):false;},hasErrorStatus:function(k){return k.status===g.FAILED_UNKNOWN_REASON||k.status===g.UNABLE_TO_CONFIRM||k.status===g.ERROR;}};e.exports=j;},null);
__d("MercuryThreadMetadataRawRenderer",["Event","CSS","DOM","MercuryActionStatus","MercuryErrorInfo","MercuryStatusTemplates","Tooltip","cx","fbt"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){var p={renderParticipantListWithNoThreadName:function(q,r,s,t,u,v){var w={callback:true,check_length:true,show_unread_count:true};v=v||{};var x={};for(var y in v)if(w[y]){x[y]=v[y];delete v[y];}var z=s.map(function(ea){return t[ea];}),aa=this.renderRawParticipantList(q,z,s.length,v);aa=this.renderRawTitleWithUnreadCount(aa,x.show_unread_count?r.unread_count:0);var ba=v.abbr_mode,ca={};for(var da in v)ca[da]=v[da];ca.abbr_mode=true;u.forEach(function(ea){var fa=u.length>1?this._cloneIfDOMElement(aa):aa;i.setContent(ea,fa);if(x.check_length&&!ba&&ea.scrollWidth>ea.clientWidth){var ga=this.renderRawParticipantList(q,z,s.length,ca),ha=this.renderRawTitleWithUnreadCount(ga,x.show_unread_count?r.unread_count:0);i.setContent(ea,ha);}}.bind(this));x.callback&&x.callback(aa);},renderRawParticipantList:function(q,r,s,t){var u={abbr_mode:true,last_separator_uses_and:true,names_renderer:true};t=t||{};var v=null;if(t.names_renderer){v=t.names_renderer(r);}else v=r.map(function(x){return x.name;});var w=null;if(v.length===0){if(!q){w="New Message";}else w="No Participants";}else if(v.length==1){w=v[0];}else if(v.length==2){if(t.last_separator_uses_and){w=o._("{participant1} and {participant2}",[o.param("participant1",v[0]),o.param("participant2",v[1])]);}else w=o._("{participant1}, {participant2}",[o.param("participant1",v[0]),o.param("participant2",v[1])]);}else if(t.last_separator_uses_and){if(t.abbr_mode){w=o._("{participant1} and {others_link}",[o.param("participant1",v[0]),o.param("others_link",this.renderRawParticipantCount({render_subset:true,count:s-1}))]);}else if(v.length==3){w=o._("{participant1}, {participant2} and {participant3}",[o.param("participant1",v[0]),o.param("participant2",v[1]),o.param("participant3",v[2])]);}else w=o._("{participant1}, {participant2} and {others_link}",[o.param("participant1",v[0]),o.param("participant2",v[1]),o.param("others_link",this.renderRawParticipantCount({render_subset:true,count:s-2}))]);}else if(v.length==3){w=o._("{participant1}, {participant2}, {participant3}",[o.param("participant1",v[0]),o.param("participant2",v[1]),o.param("participant3",v[2])]);}else w=o._("{participant1}, {participant2}, {participant3}, {others_link}",[o.param("participant1",v[0]),o.param("participant2",v[1]),o.param("participant3",v[2]),o.param("others_link",this.renderRawParticipantCount({render_subset:true,count:s-3}))]);if(Array.isArray(w))w=i.create('span',{},w);return w;},renderRawTitleWithUnreadCount:function(q,r){var s=q;if(r&&r>1)s=i.create('span',{},o._("{conversation_title} ({unread_count})",[o.param("conversation_title",q),o.param("unread_count",r)]));return s;},renderRawParticipantCount:function(q){var r=q.render_subset,s;if(!r){s=q.count>1?o._("{num} people",[o.param("num",q.count)]):"1 person";}else s=q.count>1?o._("{others_count} others",[o.param("others_count",q.count)]):"1 other";return s;},renderShortNames:function(q){if(q.length==1)return [q[0].name];return q.map(function(r){return r.short_name;});},renderStatusIndicator:function(q,r,s){var t;if(q==j.RESENDING){t=this.renderResendIndicator();}else if(q!==(void 0)&&q!=j.UNSENT&&q!=j.UNCONFIRMED&&q!=j.SUCCESS)t=this.renderErrorIndicator(r,s);return t;},renderResendIndicator:function(){return l[':fb:mercury:resend-indicator'].render();},renderErrorIndicator:function(q,r){if(!q)return null;var s=l[':fb:mercury:error-indicator'].render(),t=q.is_transient,u=k.getMessage(q);if(t)if(k.isConnectionError(q)){u=o._("{message} Check your internet connection and click to try again.",[o.param("message",u)]);}else u=o._("{message} Click to send again.",[o.param("message",u)]);m.set(s,u,'above','center');if(r&&t){g.listen(s,'click',r);s.setAttribute('tabindex','0');h.addClass(s,"_55q-");}return s;},_cloneIfDOMElement:function(q){if(q&&q.cloneNode){return q.cloneNode();}else return q;}};e.exports=p;},null);
__d("DOMClone",[],function(a,b,c,d,e,f){var g={shallowClone:function(i){return h(i,false);},deepClone:function(i){return h(i,true);}};function h(i,j){var k=i.cloneNode(j);if(typeof k.__FB_TOKEN!=='undefined')delete k.__FB_TOKEN;return k;}e.exports=g;},null);
__d("FileFormResetOnSubmit",["DOMQuery","Event","emptyFunction"],function(a,b,c,d,e,f,g,h,i){function j(l,m){var n=h.listen(l,'change',i.thatReturnsFalse,h.Priority.URGENT);try{m();}catch(o){throw o;}finally{n.remove();}}function k(l){"use strict";this._form=l;}k.prototype.enable=function(){"use strict";var l=this._reset.bind(this);this._subscription=this._form.subscribe('submit',function(){setTimeout(l,0);});};k.prototype.disable=function(){"use strict";this._subscription.unsubscribe();this._subscription=null;};k.prototype._reset=function(){"use strict";var l=this._form.getRoot();j(l,function(){var m=g.scry(l,'input[type="file"]');m.forEach(function(n){n.value='';});});};e.exports=k;},null);
__d("FileInput",["ArbiterMixin","DOM","DOMClone","Event","Focus","Keys","UserAgent_DEPRECATED","cx","mixin"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){var p=m.ie(),q=o(g);for(var r in q)if(q.hasOwnProperty(r))t[r]=q[r];var s=q===null?null:q.prototype;t.prototype=Object.create(s);t.prototype.constructor=t;t.__superConstructor__=q;function t(u,v,w){"use strict";this.container=u;this.control=v;var x=h.scry(this.container,'a')[0];x&&x.removeAttribute('href');var y=h.create('div',{className:"_3jk"},w);h.appendContent(this.control,y);this._boundHandleChange=this._handleChange.bind(this);if(p)this._boundHandleIEKeyDown=this._handleIEKeyDown.bind(this);this._setInputElement(w);}t.prototype.getValue=function(){"use strict";return this.input.value;};t.prototype.getInput=function(){"use strict";return this.input;};t.prototype.getContainer=function(){"use strict";return this.container;};t.prototype.getControl=function(){"use strict";return this.control;};t.prototype.clear=function(){"use strict";if(p){var u=i.deepClone(this.input);h.replace(this.input,u);this._setInputElement(u);}else this.input.value='';};t.prototype.destroy=function(){"use strict";this._listener.remove();this._listener=null;if(p){this._IEKeyDownListener.remove();this._IEKeyDownListener=null;}this.container=null;this.control=null;this.input=null;};t.prototype._setInputElement=function(u){"use strict";this.input=u;k.relocate(u,this.control);this._listener&&this._listener.remove();this._listener=j.listen(u,'change',this._boundHandleChange);if(p){this._IEKeyDownListener&&this._IEKeyDownListener.remove();this._IEKeyDownListener=j.listen(u,'keydown',this._boundHandleIEKeyDown);}};t.prototype._handleChange=function(event){"use strict";this.inform('change',event);var u=this.input.form;if(u&&p<9)j.fire(u,'change',event);};t.prototype._handleIEKeyDown=function(event){"use strict";if(event.keyCode===l.RETURN){event.preventDefault();var u=document.createEvent('MouseEvents');u.initEvent('click',true,true);this.input.dispatchEvent(u);}};e.exports=t;},null);
__d("DOMWrapper",[],function(a,b,c,d,e,f){var g,h,i={setRoot:function(j){g=j;},getRoot:function(){return g||document.body;},setWindow:function(j){h=j;},getWindow:function(){return h||self;}};e.exports=i;},null);
__d("Flash",["DOMEventListener","DOMWrapper","QueryString","UserAgent_DEPRECATED","copyProperties","guid","htmlSpecialChars"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){var n={},o,p=h.getWindow().document;function q(v){var w=p.getElementById(v);if(w)w.parentNode.removeChild(w);delete n[v];}function r(){for(var v in n)if(n.hasOwnProperty(v))q(v);}function s(v){return v.replace(/\d+/g,function(w){return '000'.substring(w.length)+w;});}function t(v){if(!o){if(j.ie()>=9)g.add(window,'unload',r);o=true;}n[v]=v;}var u={embed:function(v,w,x,y){var z=l();v=m(v).replace(/&/g,'&');x=k({allowscriptaccess:'always',flashvars:y,movie:v},x||{});if(typeof x.flashvars=='object')x.flashvars=i.encode(x.flashvars);var aa=[];for(var ba in x)if(x.hasOwnProperty(ba)&&x[ba])aa.push('<param name="'+m(ba)+'" value="'+m(x[ba])+'">');var ca=w.appendChild(p.createElement('span')),da='<object '+(j.ie()?'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ':'type="application/x-shockwave-flash"')+'data="'+v+'" '+(x.height?'height="'+x.height+'" ':'')+(x.width?'width="'+x.width+'" ':'')+'id="'+z+'">'+aa.join('')+'</object>';ca.innerHTML=da;var ea=ca.firstChild;t(z);return ea;},remove:q,getVersion:function(){var v='Shockwave Flash',w='application/x-shockwave-flash',x='ShockwaveFlash.ShockwaveFlash',y;if(navigator.plugins&&typeof navigator.plugins[v]=='object'){var z=navigator.plugins[v].description;if(z&&navigator.mimeTypes&&navigator.mimeTypes[w]&&navigator.mimeTypes[w].enabledPlugin)y=z.match(/\d+/g);}if(!y)try{y=(new ActiveXObject(x)).GetVariable('$version').match(/(\d+),(\d+),(\d+),(\d+)/);y=Array.prototype.slice.call(y,1);}catch(aa){}return y;},checkMinVersion:function(v){var w=u.getVersion();if(!w)return false;return s(w.join('.'))>=s(v);},isAvailable:function(){return !!u.getVersion();}};e.exports=u;},null);
__d("PhotosUploadID",[],function(a,b,c,d,e,f){var g=1024,h={getNewID:function(){return (g++).toString();}};e.exports=h;},null);
__d("Token",["CSS","DataStore","DOM","Locale","UnicodeBidi","fbt"],function(a,b,c,d,e,f,g,h,i,j,k,l){function m(n,o){"use strict";this.info=n;this.paramName=o;}m.prototype.getInfo=function(){"use strict";return this.info;};m.prototype.getText=function(){"use strict";return this.info.text;};m.prototype.getValue=function(){"use strict";return this.info.uid;};m.prototype.isFreeform=function(){"use strict";return !!this.info.freeform;};m.prototype.setSelected=function(n){"use strict";g.conditionClass(this.getElement(),'uiTokenSelected',n);return this;};m.prototype.getElement=function(){"use strict";if(!this.element)this.setElement(this.createElement());return this.element;};m.prototype.setElement=function(n){"use strict";h.set(n,'Token',this);this.element=n;return this;};m.prototype.isRemovable=function(){"use strict";return g.hasClass(this.element,'removable');};m.prototype.getTextDirection=function(){"use strict";var n=k.isDirectionRTL(this.getText()),o=j.isRTL();if(n&&!o)return 'rtl';if(!n&&o)return 'ltr';return null;};m.prototype.createElement=function(n,o){"use strict";var p=this.paramName,q=this.getText(),r=this.getValue(),s=i.create('a',{href:'#','aria-label':l._("Remove {item}",[l.param("item",q)]),className:'remove uiCloseButton uiCloseButtonSmall'});if(n)g.addClass(s,'uiCloseButtonSmallGray');var t=i.create('input',{type:'hidden',value:r,name:p+'[]',autocomplete:'off'}),u=i.create('input',{type:'hidden',value:q,name:'text_'+p+'[]',autocomplete:'off'}),v={className:'removable uiToken'},w=this.getTextDirection();if(w!==null)v.dir=w;var x=i.create('span',v,[q,t,u,s]);if(n)g.addClass(x,'uiTokenGray');if(o){var y=i.create('i',{className:o});i.prependContent(x,y);}return x;};e.exports=m;},null);
__d("WeakToken",["CSS","Token"],function(a,b,c,d,e,f,g,h){for(var i in h)if(h.hasOwnProperty(i))k[i]=h[i];var j=h===null?null:h.prototype;k.prototype=Object.create(j);k.prototype.constructor=k;k.__superConstructor__=h;function k(){"use strict";if(h!==null)h.apply(this,arguments);}k.prototype.createElement=function(){"use strict";var l=j.createElement.call(this,true,'UFIWeakReferenceIcon');g.addClass(l,'uiTokenWeakReference');return l;};e.exports=k;},null);
__d("Tokenizer",["Arbiter","ArbiterMixin","CSS","DataStore","DOM","DOMQuery","Event","Focus","Input","Keys","Parent","StickyPlaceholderInput","Style","TextMetrics","Token","UserAgent_DEPRECATED","WeakToken","copyProperties","createObjectFrom","emptyFunction","mixin"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,aa){var ba=20,ca=aa(h);for(var da in ca)if(ca.hasOwnProperty(da))fa[da]=ca[da];var ea=ca===null?null:ca.prototype;fa.prototype=Object.create(ea);fa.prototype.constructor=fa;fa.__superConstructor__=ca;function fa(ga,ha,ia){"use strict";this.element=ga;this.typeahead=ha;this.input=ha.getCore().getElement();if(ia)this.init(ia.tokenarea,ia.param_name,ia.initial_info,ia.options);j.set(this.element,'Tokenizer',this);}fa.prototype.init=function(ga,ha,ia,ja){"use strict";this.init=z;this.tokenarea=ga;this.paramName=ha;if(!this.placeholder)this.placeholder=this.input.getAttribute('data-placeholder')||'';x(this,ja||{});this.initEvents();this.initTypeahead();this.reset(ia);this.initBehaviors();setTimeout(this.adjustWidth.bind(this),0);g.inform('Tokenizer/init',this,g.BEHAVIOR_PERSISTENT);this.inform('init',{tokens:this.getTokens()});};fa.prototype.reset=function(ga){"use strict";this.tokens=[];this.unique={};if(ga){this.populate(ga);}else k.empty(this.tokenarea);this.updateTokenarea();};fa.prototype.populate=function(ga){"use strict";var ha=[];this.tokens=this.getTokenElements().map(function(ia,ja){var ka=ga[ja];ha.push(this._tokenKey(ka));return this.createToken(ka,ia);},this);this.unique=y(ha,this.tokens);};fa.prototype.getElement=function(){"use strict";return this.element;};fa.prototype.getTypeahead=function(){"use strict";return this.typeahead;};fa.prototype.getInput=function(){"use strict";return this.input;};fa.prototype.initBehaviors=function(){"use strict";this.behaviors=this.behaviors||[];if(this.behaviors instanceof Array){this.behaviors.forEach(function(ia){ia.behavior(this,ia.config);}.bind(this));}else for(var ga in (this.behaviors||{})){var ha=window.TokenizerBehaviors&&window.TokenizerBehaviors[ga];ha.call(null,this,this.behaviors[ga]);}};fa.prototype.initTypeahead=function(){"use strict";var ga=this.typeahead.getCore();ga.resetOnSelect=true;ga.setValueOnSelect=false;ga.preventFocusChangeOnTab=true;if(this.inline){var ha=this.typeahead.getView();i.addClass(ha.getElement(),'uiInlineTokenizerView');}this.typeahead.subscribe('select',function(ia,ja){var ka=ja.selected;if('uid' in ka){this.updateInput();this.addToken(this.createToken(ka));}}.bind(this));this.typeahead.subscribe('blur',this.handleBlur.bind(this));};fa.prototype.handleBlur=function(event){"use strict";this.inform('blur',{event:event});this.updatePlaceholder();};fa.prototype.initEvents=function(){"use strict";var ga=this.handleEvents.bind(this),ha=v.firefox()<4?'keypress':'keydown';m.listen(this.tokenarea,{click:ga,keydown:ga});m.listen(this.input,'paste',this.paste.bind(this));m.listen(this.input,ha,this.keydown.bind(this));};fa.prototype.handleEvents=function(event){"use strict";var ga=event.getTarget(),ha=ga&&this.getTokenElementFromTarget(ga);if(!ha)return;if(event.type!='keydown'||m.getKeyCode(event)==p.RETURN)this.processEvents(event,ga,ha);};fa.prototype.processEvents=function(event,ga,ha){"use strict";if(q.byClass(ga,'remove')){var ia=ha.nextSibling;ia=ia&&l.scry(ha.nextSibling,'.remove')[0];var ja=this.getTokenFromElement(ha);ja=this.addTokenData(ja,ga);this.removeToken(ja);this.focusOnTokenRemoval(event,ia);event.kill();}};fa.prototype.focusOnTokenRemoval=function(event,ga){"use strict";n.set(event.type=='keydown'&&ga||this.input);};fa.prototype.addTokenData=function(ga,ha){"use strict";return ga;};fa.prototype.keydown=function(event){"use strict";this.inform('keydown',{event:event});var ga=m.getKeyCode(event),ha=this.input;if(this.inline&&ga==p.BACKSPACE&&o.isEmpty(ha)){var ia=this.getLastToken();if(ia&&ia.isRemovable())this.removeToken(ia);}this.updateInput();};fa.prototype.paste=function(event){"use strict";this.inform('paste',{event:event});this.updateInput(true);};fa.prototype.focusInput=function(){"use strict";n.set(this.input);};fa.prototype.updateInput=function(ga){"use strict";if(!this.inline)return;setTimeout(function(){this.adjustWidth(this.input.value);if(ga)this.input.value=this.input.value;}.bind(this),20);r.setPlaceholderText(this.input,'');this.inform('resize');};fa.prototype.setPlaceholder=function(ga){"use strict";this.placeholder=ga;if(this.stickyPlaceholder)r.setPlaceholderText(this.input,ga);this.updatePlaceholder();};fa.prototype.updatePlaceholder=function(){"use strict";if(!this.inline||this.input.value)return;var ga=!this.tokens.length,ha='';if(ga||this.stickyPlaceholder){this.adjustWidth(this.placeholder);ha=this.placeholder;}else this.adjustWidth(this.input.value);r.setPlaceholderText(this.input,ha);};fa.prototype.adjustWidth=function(ga){"use strict";if(!this.inline||!this._getIsInDOM())return;if(!ga&&this.input.value==='')ga=this.placeholder;var ha=ba;if(ga!==this.placeholder||!this.getTokens().length||this.stickyPlaceholder){var ia=s.getFloat(this.getElement(),'width'),ja=this._getMetrics().measure(ga);ha=ja.width+this._getWidthOffset()+10;ha=(ha>=ia)?ia:ha;}s.set(this.input,'width',ha+'px');this.inform('resize');g.inform('reflow');};fa.prototype.getToken=function(ga){"use strict";return this.unique[ga]||null;};fa.prototype.getTokens=function(){"use strict";return this.tokens||[];};fa.prototype.getTokenElements=function(){"use strict";return l.scry(this.tokenarea,'span.uiToken');};fa.prototype.getTokenElementFromTarget=function(ga){"use strict";return q.byClass(ga,'uiToken');};fa.prototype.getTokenFromElement=function(ga){"use strict";return j.get(ga,'Token');};fa.prototype.getTokenValues=function(){"use strict";if(!this.tokens)return [];return this.tokens.map(function(ga){return ga.getValue();});};fa.prototype.getFirstToken=function(){"use strict";return this.tokens[0]||null;};fa.prototype.getLastToken=function(){"use strict";return this.tokens[this.tokens.length-1]||null;};fa.prototype.hasMaxTokens=function(){"use strict";return this.maxTokens&&this.maxTokens<=this.tokens.length;};fa.prototype.createToken=function(ga,ha){"use strict";var ia=this.getToken(this._tokenKey(ga));if(!ia)ia=ga.weak_reference?new w(ga,this.paramName):new u(ga,this.paramName);ha&&ia.setElement(ha);return ia;};fa.prototype.addToken=function(ga){"use strict";if(this.hasMaxTokens())return;var ha=this._tokenKey(ga.getInfo());if(ha in this.unique)return;this.unique[ha]=ga;this.tokens.push(ga);this.insertToken(ga);this.updateTokenarea();this.inform('addToken',ga);this.inform('changeTokens');g.inform('Form/change',{node:this.element});};fa.prototype.insertToken=function(ga){"use strict";k.appendContent(this.tokenarea,ga.getElement());};fa.prototype.removeToken=function(ga){"use strict";if(!ga)return;var ha=this.tokens.indexOf(ga);if(ha<0)return;this.tokens.splice(this.tokens.indexOf(ga),1);delete this.unique[this._tokenKey(ga.getInfo())];k.remove(ga.getElement());this.updateTokenarea();this.inform('removeToken',ga);this.inform('changeTokens');g.inform('Form/change',{node:this.element});};fa.prototype.removeAllTokens=function(){"use strict";this.reset();this.inform('changeTokens');this.inform('removeAllTokens');};fa.prototype.updateTokenarea=function(){"use strict";var ga=this.typeahead.getCore(),ha=this.getTokenValues();if(this.excludeDuplicates){this._exclusions||(this._exclusions=ga.getExclusions());ga.setExclusions(ha.concat(this._exclusions));}ga.setEnabled(!this.hasMaxTokens());this.updateTokenareaVisibility();this.updatePlaceholder();this.inform('resize');g.inform('reflow');};fa.prototype.updateTokenareaVisibility=function(){"use strict";i.conditionShow(this.tokenarea,this.tokens.length!==0);};fa.prototype._tokenKey=function(ga){"use strict";return ga.uid+(ga.freeform?':':'');};fa.prototype._getWidthOffset=function(){"use strict";if(this._widthOffset===null){var ga=this.input.clientWidth,ha=s.getFloat(this.input,'width');if(ga==ha){this._widthOffset=s.getFloat(this.input,'paddingLeft')+s.getFloat(this.input,'paddingRight');}else this._widthOffset=0;}return this._widthOffset;};fa.prototype._getMetrics=function(){"use strict";if(!this._metrics)this._metrics=new t(this.input,this.inline);return this._metrics;};fa.prototype._getIsInDOM=function(){"use strict";return this._isInDOM||(this._isInDOM=l.contains(document.body,this.input));};fa.getInstance=function(ga){"use strict";var ha=q.byClass(ga,'uiTokenizer');return ha?j.get(ha,'Tokenizer'):null;};fa.init=function(ga,ha){"use strict";ga.init(ha.tokenarea,ha.param_name,ha.initial_info,ha.options);};x(fa.prototype,{inline:false,maxTokens:null,excludeDuplicates:true,placeholder:'',_widthOffset:null,_metrics:null});e.exports=fa;},null);
__d("XLinkshimLogControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/si\/ajax\/l\/render_linkshim_log\/",{u:{type:"String",required:true},h:{type:"String",required:true},render_verification:{type:"Bool"},enc:{type:"String"},d:{type:"String"}});},null);
__d("LinkshimHandler",["Event","LinkshimAsyncLink","LinkshimHandlerConfig","URI","XLinkshimLogControllerURIBuilder","shield"],function(a,b,c,d,e,f,g,h,i,j,k,l){var m={setUpLinkshimHandling:function(s){try{var u=j(s.getAttribute('href')),v=n(u);if(v&&o(u)){g.listen(s,'mouseover',l(h.swap,null,s,v));var w=q(u);g.listen(s,'click',function(){if(i.supports_meta_referrer){h.referrer_log(s,w,p(u).toString());}else h.swap(s,u);});}}catch(t){}}};function n(s){return s.getQueryData().u?new j(s.getQueryData().u):null;}function o(s){return s.getQueryData().hasOwnProperty('s');}function p(s){var t=s.getQueryData().hasOwnProperty('enc')?s.getQueryData().enc:'';return (new k()).setString('u',s.getQueryData().u).setString('h',s.getQueryData().h).setBool('render_verification',s.getQueryData().hasOwnProperty('render_verification')).setString('enc',t).getURI();}function q(s){var t;if(r()){t=j(s).addQueryData({render_verification:true});}else t=n(s);return t;}function r(){var s=i.render_verification_rate||0;return Math.floor(Math.random()*s+1)===s;}e.exports=m;},null);
__d("XPhotosWaterfallBatchLoggingControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/photos\/logging\/waterfall\/batch\/",{});},null);
__d("PhotosUploadWaterfall",["AsyncRequest","AsyncSignal","Banzai","PhotosUploadWaterfallXConfig","XPhotosWaterfallBatchLoggingControllerURIBuilder","emptyFunction","randomInt","throttle"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){var o=[],p={APP_FLASH:'flash_pro',APP_SIMPLE:'simple',APP_ARCHIVE:'archive',APP_COMPOSER:'composer',APP_MESSENGER:'messenger',APP_HTML5:'html5',APP_CHAT:'chat',INSTALL_CANCEL:1,INSTALL_INSTALL:2,INSTALL_UPDATE:3,INSTALL_REINSTALL:4,INSTALL_PERMA_CANCEL:5,INSTALL_SILENT_SKIP:6,INSTALL_DOWNLOAD:7,CERROR_RESIZING_FAILED:6,CERROR_MARKER_EXTRACTION_FAILED:9,BEGIN:1,UPLOAD_START:4,ALL_UPLOADS_DONE:6,CLIENT_ERROR:7,RECOVERABLE_CLIENT_ERROR:12,IMAGES_SELECTED:9,UPGRADE_REQUIRED:11,VERSION:15,SELECT_START:18,SELECT_CANCELED:19,CANCEL:22,CANCEL_DURING_UPLOAD:83,ONE_RESIZING_START:2,ONE_UPLOAD_START:10,ONE_UPLOAD_DONE:29,ONE_RESIZING_DONE:34,PROGRESS_BAR_STOPPED:44,MISSED_BEAT:45,HEART_ATTACK:46,PUBLISH_SENT:99,PUBLISH_START:100,PUBLISH_SUCCESS:101,PUBLISH_FAILURE:102,CLUSTERING_START:103,CLUSTERING_SUCCESS:104,CLUSTERING_FAILURE:105,POST_BUTTON_CLICKED:110,POST_BUTTON_ERROR:111,PHOTO_DELETED:114,PUBLISH_CLIENT_SUCCESS:115,PHOTO_ROTATED:117,SAVE_DRAFT_BUTTON_CLICKED:123,RECOVERY_START_ON_CLIENT:124,CHANGE_PHOTO_QUALITY_SETTING:126,TAG_ADDED:127,TAG_REMOVED:128,TAB_BUTTON_CLICKED:129,EDITABLE_PHOTO_FETCH_START:106,EDITABLE_PHOTO_FETCH_SUCCESS:107,EDITABLE_PHOTO_FETCH_FAILURE:108,EDITABLE_PHOTO_FETCH_DELAY:116,CANCEL_INDIVIDUAL_UPLOAD:109,MISSING_OVERLAY_NODE:118,PUBLISH_RETRY_FAILURE:119,MISSING_UPLOAD_STATE:120,SESSION_POSTED:72,POST_PUBLISHED:80,ONE_UPLOAD_CANCELED:81,ONE_UPLOAD_CANCELED_DURING_UPLOAD:82,RESIZER_AVAILABLE:20,OVERLAY_FIRST:61,ASYNC_AVAILABLE:63,FALLBACK_TO_FLASH:13,RETRY_UPLOAD:17,TAGGED_ALL_FACES:14,VAULT_IMAGES_SELECTED:62,VAULT_CREATE_POST_CANCEL:65,VAULT_SEND_IN_MESSAGE_CLICKED:66,VAULT_DELETE_CANCEL:68,VAULT_ADD_TO_ALBUM_CANCEL:74,VAULT_SHARE_IN_AN_ALBUM_CLICKED:76,VAULT_SHARE_OWN_TIMELINE_CLICKED:77,VAULT_SHARE_FRIENDS_TIMELINE_CLICKED:78,VAULT_SHARE_IN_A_GROUP_CLICKED:79,VAULT_SYNCED_PAGED_LINK_CLICKED:84,VAULTBOX:'vaultbox',GRID:'grid',SPOTLIGHT_VAULT_VIEWER:'spotlight_vault_viewer',REF_VAULT_NOTIFICATION:'vault_notification',_checkRequiredFields:function(r){},sendBanzai:function(r,s){this._checkRequiredFields(r);var t={};r.scuba_ints=r.scuba_ints||{};r.scuba_ints.client_time=Math.round(Date.now()/1000);if(j.retryBanzai){t.retry=true;r.scuba_ints.nonce=m(4294967296);}i.post(j.deprecatedBanzaiRoute,r,t);if(s)setTimeout(s,0);},sendSignal:function(r,s){this._checkRequiredFields(r);if(j.useBanzai){this.sendBanzai(r,s);}else if(j.reduceLoggingRequests){this.queueLog(r,s);}else{var t=new h('/ajax/photos/waterfall.php',{data:JSON.stringify(r)}).setHandler(s);if(j.timeout)t.setTimeout(10*1000);t.send();}},queueLog:function(r,s){o.push(r);if(!!s){this.flushQueue(s);}else q();},flushQueue:function(r){var s=JSON.stringify(o);o=[];var t=new k().getURI();new g().setURI(t).setData({logs:s}).setFinallyHandler(r||l).setTimeoutHandler(10*1000,r||l).send();}},q=n(p.flushQueue,j.batchInterval*1000);e.exports=p;},null);
__d("XStickersAddPackControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/stickers\/addpack\/",{pack_id:{type:"Int"},size:{type:"String"},redirect_uri:{type:"String"},is_promoted:{type:"Bool"}});},null);
__d("XStickersRemovePackControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/stickers\/removepack\/",{pack_id:{type:"Int"},size:{type:"String"},redirect_uri:{type:"String"}});},null);
__d("XStickerTagImagesControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/stickers\/tag\/images\/",{tag_ids:{type:"IntVector",required:true}});},null);
__d("XStickerQueryImagesControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/stickers\/query\/images\/",{query:{type:"String",required:true}});},null);
__d("StickersDispatcher",["Dispatcher","StickerConstants","copyProperties","merge"],function(a,b,c,d,e,f,g,h,i,j){'use strict';var k=i(new g(),{_handleUpdate:function(l,m){var n=j({payloadSource:l},m);this.dispatch(n);},handleUpdateFromViewActions:function(l){this._handleUpdate(h.PayloadSource.VIEW_ACTION,l);}});e.exports=k;},null);
__d("StickerState",["ImmutableObject","StickerConfig","PresenceState","StickerConstants","StickerImages","StickersDispatcher","StickerServerRequests","mixInEventEmitter"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n){'use strict';var o={},p,q,r,s=null,t=0,u={},v=[],w=[],x=[],y=null,z=i.get();if(z)y=z.tray_pack_id;var aa=h.ShowStickerReplyNUX,ba=h.ShowStickerSearchNUX,ca={onTrayDataReady:function(fa){if(!q)q=m.fetchTrayData(function(ga){v=ga.packs.map(function(ha){return da(ha);});r=ga.mru;t=ga.num_new_packs;x=ga.tags;});q.then(fa);},onStoreDataReady:function(fa){if(!p)p=m.fetchStoreData(function(ga){w=ga.packs.map(function(ha){return da(ha);});});p.then(fa);},onPackDataReady:function(fa,ga){if(!o[fa])o[fa]=m.fetchPackData(fa,function(ha){da(ha);});o[fa].then(ga);},getPacksInTray:function(){return v;},getPacksInCommentsTray:function(){var fa=[],ga=[],ha;for(var ia=0;ia<v.length;ia++)if(v[ia].id==j.EMOTICON_PACK_ID){ha=v[ia];}else if(v[ia].isMessengerOnly){ga.push(v[ia]);}else fa.push(v[ia]);var ja=fa.concat(ga);if(ha)ja.push(ha);return ja;},getPackIDsInTray:function(){return v.map(function(fa){return fa.id;});},getPacksInStore:function(){return w;},getPack:function(fa){return u[fa];},getNumNewPacks:function(){return t;},getFeaturedTags:function(){return x;},resetNumNewPacks:function(){if(t){t=0;this.emit(this.NUM_NEW_PACKS_CHANGED,0);}},addMRUPack:function(){if(r){this._addPackToTray(r);r=null;}},addPack:function(fa){var ga=false;if(u[fa])ga=u[fa].isPromoted;m.addPack(fa,ga,function(ha){this._addPackToTray(ha);}.bind(this));},removePack:function(fa){m.removePack(fa,function(ga){v=v.filter(function(ha){return ha.id!==ga;});u[ga]=g.set(u[ga],{isInTray:false});w=w.map(function(ha){return u[ha.id];});this.emit(this.PACKS_CHANGED,ga);}.bind(this));},setTrayPackID:function(fa){y=fa;i.doSync();this.emit(ca.PACK_SELECTED,fa);},getTrayPackID:function(){return y;},shouldShowStickerReplyNUX:function(){return aa;},clearShowStickerReplyNUX:function(){aa=false;},shouldShowStickerSearchNUX:function(){return ba;},clearShowStickerSearchNUX:function(){m.markSeenSearchNUX();ba=false;},_addPackToTray:function(fa,ga){da(fa);u[fa.id]=g.set(u[fa.id],{isPurchased:!ga,isInTray:true});var ha=v.filter(function(ja){return ja.id===fa.id;}).length>0;if(!ha){var ia;if(!ga){ia=v.filter(function(ja){return ja.isMRU||ja.isSearch;}).length;}else ia=v.filter(function(ja){return ja.id!==j.EMOTICON_PACK_ID;}).length;v.splice(ia,0,u[fa.id]);}w=w.map(function(ja){return u[ja.id];});this.emit(this.PACKS_CHANGED,fa.id);},_addRecentlyUsedSticker:function(fa){for(var ga=0;ga<s.length;++ga)if(s[ga].id===fa.id){s.splice(ga,1);break;}s.unshift(fa);},getMRUStickerPack:function(fa){if(!s)s=fa;return s;},updateRecentlyUsed:function(fa){if(!s){this.addMRUPack();return;}this._addRecentlyUsedSticker(k.getSticker(fa));},promotePackSentFromSearch:function(fa){m.promotePackSentFromSearch(fa,function(ga){return ga&&this._addPackToTray(ga,true);}.bind(this));}};l.register(function(fa){if(fa.actions&&fa.actions.length){var ga=j.ActionTypes;fa.actions.forEach(function(ha){switch(ha.actionType){case ga.ADD_PACK:ca.addPack(ha.packID);break;case ga.REMOVE_PACK:ca.removePack(ha.packID);break;case ga.SELECT_PACK:ca.setTrayPackID(ha.packID);break;case ga.RESET_NUM_NEW_PACKS:ca.resetNumNewPacks();break;}});}});ca.PACKS_CHANGED='StickerState/packsChanged';ca.PACK_SELECTED='StickerState/packSelected';ca.NUM_NEW_PACKS_CHANGED='StickerState/numNewPacksChanged';i.registerStateStorer(function(fa){fa.tray_pack_id=y;});function da(fa){var ga=fa.id;if(!u[ga]){return (u[ga]=new g(fa));}else return (u[ga]=g.set(u[ga],fa));}var ea={};ea[ca.PACK_SELECTED]=true;ea[ca.PACKS_CHANGED]=true;ea[ca.NUM_NEW_PACKS_CHANGED]=true;n(ca,ea);e.exports=ca;},null);
__d("StickerSearch",["StickerImages","StickerServerRequests","StickerState","createObjectFrom","getObjectValues"],function(a,b,c,d,e,f,g,h,i,j,k){'use strict';var l=100,m=1000,n=10000,o,p,q,r=null,s={},t={requestStickersForTags:function(u,v,w,x){p=w;var y=u,z=v.length>1;if(z)y=y.concat(v);g.requestStickersForTags(y,function(){if(p===w)x(this._getSortedStickersForTags(u,v,w,z));}.bind(this));},requestStickersForQuery:function(u,v){p=u;h.getStickersForQuery(u,function(w){return p===u&&v(w.payload);});},_getSortedStickersForTags:function(u,v,w,x){var y={},z=this._getTypeaheadStickers(u,w,y),aa=k(z);if(x){var ba=this._getIntersectionStickers(v,y);aa=aa.concat(ba.filter(function(ca){return !z.hasOwnProperty(ca.id);}));}aa.map(function(ca){return g.cacheSticker(ca);});aa.sort(function(ca,da){return y[da.id]-y[ca.id];});return aa;},_getTypeaheadStickers:function(u,v,w){var x={},y=g.getStickerTagsData();o=j(i.getPackIDsInTray());u.forEach(function(z){y[z.id].forEach(function(aa){var ba=aa.score+l;if(o[aa.packID])ba+=m;if(z.name===v)ba+=n;if(!x[aa.id]||ba>w[aa.id]){x[aa.id]=aa;w[aa.id]=ba;}});});return x;},_getIntersectionStickers:function(u,v){var w=g.getStickerTagsData(),x=u.map(function(z){return w[z.id].map(function(aa){return aa.id;});}),y=w[u[0].id].filter(function(z){v[z.id]=z.score;for(var aa=1;aa<x.length;aa++)if(x[aa].indexOf(z.id)===-1){return false;}else v[z.id]+=w[u[aa].id].score;return true;});return y;},prepareTagsData:function(){if(!q)q=h.fetchTagData(function(u){r=u;r.map(function(v){return s[v.name]=v;});});return q;},getTagByName:function(u){return s[u];},getTags:function(){return r;},getTagsIndex:function(){return s;}};e.exports=t;},null);
__d("ProgressBarBase",["emptyFunction","requestAnimationFrame","removeFromArray","arrayContains"],function(a,b,c,d,e,f,g,h,i,j){var k=[];function l(m,n){"use strict";this._min=m||0;this._max=n||100;this._initialPosition=0;this._position=0;this._initialVelocity=0;this._velocity=0;this._acceleration=0;this.useAcceleration=true;this._targetPosition=0;this._targetTime=0;this._startTime=null;this._onComplete=g;}l.prototype.setPosition=function(m){"use strict";m=this._normalizePosition(m);this._initialPosition=m;this._position=m;this.updateMeter(this._position);this.stop();return this;};l.prototype.setCompleteHandler=function(m){"use strict";this._onComplete=m||g;return this;};l.prototype.setTarget=function(m,n){"use strict";this._stopAnimating();this._clearOnCompleteTimeout();this._targetPosition=m;var o=this._normalizePosition(m);this._targetTime=n;this._initialVelocity=this._velocity;this._initialPosition=this._position;if(this.useAcceleration){this._acceleration=2*(o-this._initialPosition-this._initialVelocity*n)/(n*n);}else{this._acceleration=0;this._velocity=this._initialVelocity=(o-this._initialPosition)/n;}if(this._position>=o){this._onComplete();}else this._start();return this;};l.prototype.setNoAcceleration=function(m){"use strict";this.useAcceleration=!m;return this;};l.prototype._clearOnCompleteTimeout=function(){"use strict";a.clearTimeout(this._onCompleteTimeout);};l.prototype.stop=function(){"use strict";this._clearOnCompleteTimeout();this._velocity=0;this._initialVelocity=0;this._acceleration=0;this._stopAnimating();return this;};l.prototype._start=function(){"use strict";this._startTime=Date.now();this._onCompleteTimeout=a.setTimeout(function(){this.setPosition(this._targetPosition);this._onComplete();}.bind(this),this._targetTime);this._startAnimating();return this;};l.prototype._loop=function(){"use strict";var m=Date.now()-this._startTime;this._position=(.5*this._acceleration*m*m)+(this._initialVelocity*m)+this._initialPosition;var n=this._velocity;this._velocity=this._acceleration*m+this._initialVelocity;var o=n<0!==this._velocity<0;if(this._position>this._normalizePosition(this._targetPosition)||o){this.setPosition(this._targetPosition);this._onComplete();}else this.updateMeter(this._position);};l.prototype.updateMeter=function(m){"use strict";throw "Unimplemented function: updateMeter";};l.prototype._normalizePosition=function(m){"use strict";return Math.min(Math.max((m-this._min)/(this._max-this._min),0),1);};l.prototype._startAnimating=function(){"use strict";if(!j(k,this)){k.push(this);if(k.length===1)h(l.prototype._requestAnimationFrameCallback);}};l.prototype._stopAnimating=function(){"use strict";i(k,this);};l.prototype._requestAnimationFrameCallback=function(){"use strict";k.forEach(function(m){m._loop();});if(k.length)h(l.prototype._requestAnimationFrameCallback);};l.setPosition=function(m,n){"use strict";m.setPosition(n);};l.setTarget=function(m,n,o){"use strict";m.setTarget(n,o);};e.exports=l;},null);
__d("ProgressBar",["ProgressBarBase","CSS","Style","cx","csx","DOM"],function(a,b,c,d,e,f,g,h,i,j,k,l){for(var m in g)if(g.hasOwnProperty(m))o[m]=g[m];var n=g===null?null:g.prototype;o.prototype=Object.create(n);o.prototype.constructor=o;o.__superConstructor__=g;function o(p,q,r){"use strict";g.call(this,q,r);this._root=p;this._meter=l.find(p,"div._5e4k");this._meter2=l.scry(p,"div._5e2g")[0];}o.prototype.getRoot=function(){"use strict";return this._root;};o.prototype.updateMeter=function(p){"use strict";var q=Math.min(Math.max(p,0),1);h.conditionClass(this._meter,"_5e2d",q<=0);h.conditionClass(this._meter,"_5e4j",q>=1);q=q*100+'%';i.set(this._meter,'width',q);if(this._meter2){i.set(this._meter2,'left',q);i.set(this._meter2,'width',q);}};o.prototype.changeLabel=function(p){"use strict";var q=l.scry(this._root,"span._5e2h");q.forEach(function(r){l.setContent(r,p);});return this;};e.exports=o;},null);
__d("FormSubmitOnChange",["Event","copyProperties","submitForm"],function(a,b,c,d,e,f,g,h,i){function j(k){"use strict";this._form=k;}j.prototype.enable=function(){"use strict";this._listener=g.listen(this._form.getRoot(),'change',this._submit.bind(this));};j.prototype.disable=function(){"use strict";this._listener.remove();this._listener=null;};j.prototype._submit=function(){"use strict";i(this._form.getRoot());};h(j.prototype,{_listener:null});e.exports=j;},null);
__d("XMessagingVideoAttachmentControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/mercury\/attachments\/video\/",{video_id:{type:"Int",required:true},window_width:{type:"Int",required:true},window_height:{type:"Int",required:true}});},null);
__d("XSkypeDeprecationWarningDialogControllerURIBuilder",["XControllerURIBuilder"],function(a,b,c,d,e,f){e.exports=b("XControllerURIBuilder").create("\/videocall\/skype_deprecation_warning\/",{__asyncDialog:{type:"Int"}});},null);
|
src/components/stories/Signup.js
|
neontribe/spool
|
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Signup } from '../Signup';
const initial = {
viewer: {
region: null,
role: {
__typename: 'Missing'
}
},
meta: {
regions: ['Liverpool', 'South Shields']
}
};
storiesOf('Signup', module)
.add('initial view', () => (
<Signup meta={initial.meta} viewer={initial.viewer}/>
));
|
src/List11/lten2.js
|
DangrMiao/House
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
export default class lten2 extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native 12!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
ajax/libs/algoliasearch.zendesk-hc/3.0.0-alpha.2/algoliasearch.zendesk-hc.min.js
|
cdnjs/cdnjs
|
parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"EfvZ":[function(require,module,exports) {
"use strict";var t=Function.prototype.bind;function r(r){var o=function(){for(var o=arguments.length,n=Array(o),e=0;e<o;e++)n[e]=arguments[e];return new(t.apply(r,[null].concat(n)))};return o.__proto__=r,o.prototype=r.prototype,o}module.exports=r;
},{}],"HHCo":[function(require,module,exports) {
function o(o){return void 0===o}module.exports=o;
},{}],"YkwH":[function(require,module,exports) {
"use strict";var e=require("lodash/isUndefined"),n=r(e);function r(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"undefined",checker:n.default,printer:function(){return"undefined"}};
},{"lodash/isUndefined":"HHCo"}],"A6c3":[function(require,module,exports) {
function n(n){return null===n}module.exports=n;
},{}],"R81P":[function(require,module,exports) {
"use strict";var e=require("lodash/isNull"),u=r(e);function r(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"null",checker:u.default,printer:function(){return"null"}};
},{"lodash/isNull":"A6c3"}],"PrXa":[function(require,module,exports) {
var global = arguments[3];
var e=arguments[3],t="object"==typeof e&&e&&e.Object===Object&&e;module.exports=t;
},{}],"M4cY":[function(require,module,exports) {
var e=require("./_freeGlobal"),t="object"==typeof self&&self&&self.Object===Object&&self,l=e||t||Function("return this")();module.exports=l;
},{"./_freeGlobal":"PrXa"}],"ydxh":[function(require,module,exports) {
var o=require("./_root"),r=o.Symbol;module.exports=r;
},{"./_root":"M4cY"}],"MKxR":[function(require,module,exports) {
var r=require("./_Symbol"),t=Object.prototype,e=t.hasOwnProperty,o=t.toString,a=r?r.toStringTag:void 0;function l(r){var t=e.call(r,a),l=r[a];try{r[a]=void 0;var c=!0}catch(n){}var i=o.call(r);return c&&(t?r[a]=l:delete r[a]),i}module.exports=l;
},{"./_Symbol":"ydxh"}],"SM0O":[function(require,module,exports) {
var t=Object.prototype,o=t.toString;function r(t){return o.call(t)}module.exports=r;
},{}],"fkTb":[function(require,module,exports) {
var e=require("./_Symbol"),r=require("./_getRawTag"),o=require("./_objectToString"),t="[object Null]",i="[object Undefined]",n=e?e.toStringTag:void 0;function u(e){return null==e?void 0===e?i:t:n&&n in Object(e)?r(e):o(e)}module.exports=u;
},{"./_Symbol":"ydxh","./_getRawTag":"MKxR","./_objectToString":"SM0O"}],"cwaR":[function(require,module,exports) {
function e(e){return null!=e&&"object"==typeof e}module.exports=e;
},{}],"gJCV":[function(require,module,exports) {
var e=require("./_baseGetTag"),r=require("./isObjectLike"),o="[object Boolean]";function t(t){return!0===t||!1===t||r(t)&&e(t)==o}module.exports=t;
},{"./_baseGetTag":"fkTb","./isObjectLike":"cwaR"}],"oCiB":[function(require,module,exports) {
"use strict";var e=require("lodash/isBoolean"),r=o(e);function o(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"boolean",checker:r.default,printer:JSON.stringify};
},{"lodash/isBoolean":"gJCV"}],"Pq7J":[function(require,module,exports) {
var e=require("./_baseGetTag"),r=require("./isObjectLike"),t="[object Number]";function u(u){return"number"==typeof u||r(u)&&e(u)==t}module.exports=u;
},{"./_baseGetTag":"fkTb","./isObjectLike":"cwaR"}],"FZBu":[function(require,module,exports) {
"use strict";var e=require("lodash/isNumber"),r=u(e);function u(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"number",checker:r.default,printer:JSON.stringify};
},{"lodash/isNumber":"Pq7J"}],"F0hp":[function(require,module,exports) {
var r=Array.isArray;module.exports=r;
},{}],"QWfy":[function(require,module,exports) {
var e=require("./_baseGetTag"),r=require("./isArray"),i=require("./isObjectLike"),t="[object String]";function u(u){return"string"==typeof u||!r(u)&&i(u)&&e(u)==t}module.exports=u;
},{"./_baseGetTag":"fkTb","./isArray":"F0hp","./isObjectLike":"cwaR"}],"R1Wc":[function(require,module,exports) {
"use strict";var e=require("lodash/isString"),r=t(e);function t(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"string",checker:r.default,printer:JSON.stringify};
},{"lodash/isString":"QWfy"}],"ihtJ":[function(require,module,exports) {
function n(n){var o=typeof n;return null!=n&&("object"==o||"function"==o)}module.exports=n;
},{}],"CqcF":[function(require,module,exports) {
var e=require("./_baseGetTag"),r=require("./isObject"),t="[object AsyncFunction]",n="[object Function]",o="[object GeneratorFunction]",c="[object Proxy]";function u(u){if(!r(u))return!1;var i=e(u);return i==n||i==o||i==t||i==c}module.exports=u;
},{"./_baseGetTag":"fkTb","./isObject":"ihtJ"}],"b66e":[function(require,module,exports) {
"use strict";var e=require("lodash/isFunction"),n=t(e);function t(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"function",checker:n.default,printer:function(e){return(e.name||"anonymous")+"("+(e.length?e.length+" argument"+(e.length>1?"s":""):"")+")"}};
},{"lodash/isFunction":"CqcF"}],"T6Us":[function(require,module,exports) {
"use strict";var r=require("lodash/isArray"),e=t(r);function t(r){return r&&r.__esModule?r:{default:r}}module.exports={name:"Array",checker:e.default,printer:JSON.stringify};
},{"lodash/isArray":"F0hp"}],"Sosh":[function(require,module,exports) {
function n(n,r){return function(t){return n(r(t))}}module.exports=n;
},{}],"q4qA":[function(require,module,exports) {
var e=require("./_overArg"),r=e(Object.getPrototypeOf,Object);module.exports=r;
},{"./_overArg":"Sosh"}],"XOVF":[function(require,module,exports) {
var t=require("./_baseGetTag"),e=require("./_getPrototype"),r=require("./isObjectLike"),o="[object Object]",c=Function.prototype,n=Object.prototype,u=c.toString,i=n.hasOwnProperty,a=u.call(Object);function l(c){if(!r(c)||t(c)!=o)return!1;var n=e(c);if(null===n)return!0;var l=i.call(n,"constructor")&&n.constructor;return"function"==typeof l&&l instanceof l&&u.call(l)==a}module.exports=l;
},{"./_baseGetTag":"fkTb","./_getPrototype":"q4qA","./isObjectLike":"cwaR"}],"TIJW":[function(require,module,exports) {
"use strict";var e=require("lodash/isPlainObject"),r=t(e);function t(e){return e&&e.__esModule?e:{default:e}}module.exports={name:"Object",checker:r.default,printer:JSON.stringify};
},{"lodash/isPlainObject":"XOVF"}],"wX1A":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){function e(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)}}return function(t,n,r){return n&&e(t.prototype,n),r&&e(t,r),t}}();function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var n=function(){function n(e){var r=arguments.length<=1||void 0===arguments[1]?"":arguments[1];t(this,n),this.path=r+"["+e+"]"}return e(n,[{key:"nest",value:function(e){return new n(e,this.path)}},{key:"throw",value:function(e){throw new Error(this.path+" "+e)}}]),n}();exports.default=n;
},{}],"vLP6":[function(require,module,exports) {
function n(n,r){for(var e=-1,l=null==n?0:n.length;++e<l&&!1!==r(n[e],e,n););return n}module.exports=n;
},{}],"WSXs":[function(require,module,exports) {
function r(r){return function(e,n,t){for(var o=-1,u=Object(e),f=t(e),a=f.length;a--;){var c=f[r?a:++o];if(!1===n(u[c],c,u))break}return e}}module.exports=r;
},{}],"eVSI":[function(require,module,exports) {
var e=require("./_createBaseFor"),r=e();module.exports=r;
},{"./_createBaseFor":"WSXs"}],"zW8l":[function(require,module,exports) {
function r(r,o){for(var e=-1,n=Array(r);++e<r;)n[e]=o(e);return n}module.exports=r;
},{}],"rx9e":[function(require,module,exports) {
var e=require("./_baseGetTag"),r=require("./isObjectLike"),t="[object Arguments]";function u(u){return r(u)&&e(u)==t}module.exports=u;
},{"./_baseGetTag":"fkTb","./isObjectLike":"cwaR"}],"oh3z":[function(require,module,exports) {
var e=require("./_baseIsArguments"),r=require("./isObjectLike"),t=Object.prototype,l=t.hasOwnProperty,n=t.propertyIsEnumerable,u=e(function(){return arguments}())?e:function(e){return r(e)&&l.call(e,"callee")&&!n.call(e,"callee")};module.exports=u;
},{"./_baseIsArguments":"rx9e","./isObjectLike":"cwaR"}],"i9YA":[function(require,module,exports) {
function e(){return!1}module.exports=e;
},{}],"Cdux":[function(require,module,exports) {
var e=require("./_root"),o=require("./stubFalse"),r="object"==typeof exports&&exports&&!exports.nodeType&&exports,t=r&&"object"==typeof module&&module&&!module.nodeType&&module,p=t&&t.exports===r,u=p?e.Buffer:void 0,d=u?u.isBuffer:void 0,s=d||o;module.exports=s;
},{"./_root":"M4cY","./stubFalse":"i9YA"}],"XqZz":[function(require,module,exports) {
var e=9007199254740991,r=/^(?:0|[1-9]\d*)$/;function t(t,n){var o=typeof t;return!!(n=null==n?e:n)&&("number"==o||"symbol"!=o&&r.test(t))&&t>-1&&t%1==0&&t<n}module.exports=t;
},{}],"Lm6w":[function(require,module,exports) {
var e=9007199254740991;function r(r){return"number"==typeof r&&r>-1&&r%1==0&&r<=e}module.exports=r;
},{}],"IQli":[function(require,module,exports) {
var e=require("./_baseGetTag"),t=require("./isLength"),r=require("./isObjectLike"),o="[object Arguments]",b="[object Array]",c="[object Boolean]",j="[object Date]",a="[object Error]",n="[object Function]",i="[object Map]",A="[object Number]",y="[object Object]",u="[object RegExp]",g="[object Set]",l="[object String]",p="[object WeakMap]",s="[object ArrayBuffer]",m="[object DataView]",U="[object Float32Array]",f="[object Float64Array]",q="[object Int8Array]",F="[object Int16Array]",I="[object Int32Array]",d="[object Uint8Array]",h="[object Uint8ClampedArray]",k="[object Uint16Array]",x="[object Uint32Array]",B={};function D(o){return r(o)&&t(o.length)&&!!B[e(o)]}B[U]=B[f]=B[q]=B[F]=B[I]=B[d]=B[h]=B[k]=B[x]=!0,B[o]=B[b]=B[s]=B[c]=B[m]=B[j]=B[a]=B[n]=B[i]=B[A]=B[y]=B[u]=B[g]=B[l]=B[p]=!1,module.exports=D;
},{"./_baseGetTag":"fkTb","./isLength":"Lm6w","./isObjectLike":"cwaR"}],"kFVy":[function(require,module,exports) {
function n(n){return function(r){return n(r)}}module.exports=n;
},{}],"a9Sd":[function(require,module,exports) {
var e=require("./_freeGlobal"),o="object"==typeof exports&&exports&&!exports.nodeType&&exports,r=o&&"object"==typeof module&&module&&!module.nodeType&&module,t=r&&r.exports===o,p=t&&e.process,u=function(){try{var e=r&&r.require&&r.require("util").types;return e||p&&p.binding&&p.binding("util")}catch(o){}}();module.exports=u;
},{"./_freeGlobal":"PrXa"}],"pKgN":[function(require,module,exports) {
var e=require("./_baseIsTypedArray"),r=require("./_baseUnary"),a=require("./_nodeUtil"),i=a&&a.isTypedArray,s=i?r(i):e;module.exports=s;
},{"./_baseIsTypedArray":"IQli","./_baseUnary":"kFVy","./_nodeUtil":"a9Sd"}],"Fz1h":[function(require,module,exports) {
var e=require("./_baseTimes"),r=require("./isArguments"),t=require("./isArray"),i=require("./isBuffer"),n=require("./_isIndex"),s=require("./isTypedArray"),u=Object.prototype,f=u.hasOwnProperty;function a(u,a){var o=t(u),p=!o&&r(u),y=!o&&!p&&i(u),g=!o&&!p&&!y&&s(u),h=o||p||y||g,l=h?e(u.length,String):[],q=l.length;for(var b in u)!a&&!f.call(u,b)||h&&("length"==b||y&&("offset"==b||"parent"==b)||g&&("buffer"==b||"byteLength"==b||"byteOffset"==b)||n(b,q))||l.push(b);return l}module.exports=a;
},{"./_baseTimes":"zW8l","./isArguments":"oh3z","./isArray":"F0hp","./isBuffer":"Cdux","./_isIndex":"XqZz","./isTypedArray":"pKgN"}],"GRYO":[function(require,module,exports) {
var t=Object.prototype;function o(o){var r=o&&o.constructor;return o===("function"==typeof r&&r.prototype||t)}module.exports=o;
},{}],"NtzY":[function(require,module,exports) {
var e=require("./_overArg"),r=e(Object.keys,Object);module.exports=r;
},{"./_overArg":"Sosh"}],"stqF":[function(require,module,exports) {
var r=require("./_isPrototype"),e=require("./_nativeKeys"),t=Object.prototype,o=t.hasOwnProperty;function n(t){if(!r(t))return e(t);var n=[];for(var u in Object(t))o.call(t,u)&&"constructor"!=u&&n.push(u);return n}module.exports=n;
},{"./_isPrototype":"GRYO","./_nativeKeys":"NtzY"}],"XeS6":[function(require,module,exports) {
var e=require("./isFunction"),n=require("./isLength");function r(r){return null!=r&&n(r.length)&&!e(r)}module.exports=r;
},{"./isFunction":"CqcF","./isLength":"Lm6w"}],"svoD":[function(require,module,exports) {
var e=require("./_arrayLikeKeys"),r=require("./_baseKeys"),i=require("./isArrayLike");function u(u){return i(u)?e(u):r(u)}module.exports=u;
},{"./_arrayLikeKeys":"Fz1h","./_baseKeys":"stqF","./isArrayLike":"XeS6"}],"DQ8x":[function(require,module,exports) {
var e=require("./_baseFor"),r=require("./keys");function u(u,o){return u&&e(u,o,r)}module.exports=u;
},{"./_baseFor":"eVSI","./keys":"svoD"}],"He6B":[function(require,module,exports) {
var r=require("./isArrayLike");function e(e,n){return function(t,u){if(null==t)return t;if(!r(t))return e(t,u);for(var i=t.length,f=n?i:-1,o=Object(t);(n?f--:++f<i)&&!1!==u(o[f],f,o););return t}}module.exports=e;
},{"./isArrayLike":"XeS6"}],"vYTM":[function(require,module,exports) {
var e=require("./_baseForOwn"),r=require("./_createBaseEach"),a=r(e);module.exports=a;
},{"./_baseForOwn":"DQ8x","./_createBaseEach":"He6B"}],"FRcP":[function(require,module,exports) {
function e(e){return e}module.exports=e;
},{}],"pajS":[function(require,module,exports) {
var e=require("./identity");function t(t){return"function"==typeof t?t:e}module.exports=t;
},{"./identity":"FRcP"}],"Cllr":[function(require,module,exports) {
var r=require("./_arrayEach"),e=require("./_baseEach"),a=require("./_castFunction"),u=require("./isArray");function i(i,c){return(u(i)?r:e)(i,a(c))}module.exports=i;
},{"./_arrayEach":"vLP6","./_baseEach":"vYTM","./_castFunction":"pajS","./isArray":"F0hp"}],"UuqP":[function(require,module,exports) {
function t(){this.__data__=[],this.size=0}module.exports=t;
},{}],"LaH9":[function(require,module,exports) {
function e(e,n){return e===n||e!=e&&n!=n}module.exports=e;
},{}],"TrJy":[function(require,module,exports) {
var r=require("./eq");function e(e,n){for(var t=e.length;t--;)if(r(e[t][0],n))return t;return-1}module.exports=e;
},{"./eq":"LaH9"}],"UjAu":[function(require,module,exports) {
var e=require("./_assocIndexOf"),r=Array.prototype,t=r.splice;function a(r){var a=this.__data__,o=e(a,r);return!(o<0)&&(o==a.length-1?a.pop():t.call(a,o,1),--this.size,!0)}module.exports=a;
},{"./_assocIndexOf":"TrJy"}],"bvw3":[function(require,module,exports) {
var r=require("./_assocIndexOf");function e(e){var a=this.__data__,o=r(a,e);return o<0?void 0:a[o][1]}module.exports=e;
},{"./_assocIndexOf":"TrJy"}],"Yobp":[function(require,module,exports) {
var e=require("./_assocIndexOf");function r(r){return e(this.__data__,r)>-1}module.exports=r;
},{"./_assocIndexOf":"TrJy"}],"afRd":[function(require,module,exports) {
var s=require("./_assocIndexOf");function e(e,r){var t=this.__data__,i=s(t,e);return i<0?(++this.size,t.push([e,r])):t[i][1]=r,this}module.exports=e;
},{"./_assocIndexOf":"TrJy"}],"hCml":[function(require,module,exports) {
var e=require("./_listCacheClear"),t=require("./_listCacheDelete"),r=require("./_listCacheGet"),l=require("./_listCacheHas"),o=require("./_listCacheSet");function a(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var l=e[t];this.set(l[0],l[1])}}a.prototype.clear=e,a.prototype.delete=t,a.prototype.get=r,a.prototype.has=l,a.prototype.set=o,module.exports=a;
},{"./_listCacheClear":"UuqP","./_listCacheDelete":"UjAu","./_listCacheGet":"bvw3","./_listCacheHas":"Yobp","./_listCacheSet":"afRd"}],"oGrO":[function(require,module,exports) {
var e=require("./_ListCache");function i(){this.__data__=new e,this.size=0}module.exports=i;
},{"./_ListCache":"hCml"}],"gG8W":[function(require,module,exports) {
function e(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i}module.exports=e;
},{}],"bAeR":[function(require,module,exports) {
function t(t){return this.__data__.get(t)}module.exports=t;
},{}],"xs8c":[function(require,module,exports) {
function t(t){return this.__data__.has(t)}module.exports=t;
},{}],"FwgM":[function(require,module,exports) {
var r=require("./_root"),e=r["__core-js_shared__"];module.exports=e;
},{"./_root":"M4cY"}],"VZNt":[function(require,module,exports) {
var e=require("./_coreJsData"),r=function(){var r=/[^.]+$/.exec(e&&e.keys&&e.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function n(e){return!!r&&r in e}module.exports=n;
},{"./_coreJsData":"FwgM"}],"MjOM":[function(require,module,exports) {
var t=Function.prototype,r=t.toString;function n(t){if(null!=t){try{return r.call(t)}catch(n){}try{return t+""}catch(n){}}return""}module.exports=n;
},{}],"tEmV":[function(require,module,exports) {
var e=require("./isFunction"),r=require("./_isMasked"),t=require("./isObject"),o=require("./_toSource"),n=/[\\^$.*+?()[\]{}|]/g,c=/^\[object .+?Constructor\]$/,i=Function.prototype,u=Object.prototype,p=i.toString,s=u.hasOwnProperty,a=RegExp("^"+p.call(s).replace(n,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function l(n){return!(!t(n)||r(n))&&(e(n)?a:c).test(o(n))}module.exports=l;
},{"./isFunction":"CqcF","./_isMasked":"VZNt","./isObject":"ihtJ","./_toSource":"MjOM"}],"ONap":[function(require,module,exports) {
function n(n,o){return null==n?void 0:n[o]}module.exports=n;
},{}],"b5xW":[function(require,module,exports) {
var e=require("./_baseIsNative"),r=require("./_getValue");function u(u,a){var i=r(u,a);return e(i)?i:void 0}module.exports=u;
},{"./_baseIsNative":"tEmV","./_getValue":"ONap"}],"ztLC":[function(require,module,exports) {
var e=require("./_getNative"),r=require("./_root"),o=e(r,"Map");module.exports=o;
},{"./_getNative":"b5xW","./_root":"M4cY"}],"Shes":[function(require,module,exports) {
var e=require("./_getNative"),r=e(Object,"create");module.exports=r;
},{"./_getNative":"b5xW"}],"w7U7":[function(require,module,exports) {
var e=require("./_nativeCreate");function t(){this.__data__=e?e(null):{},this.size=0}module.exports=t;
},{"./_nativeCreate":"Shes"}],"iOZZ":[function(require,module,exports) {
function t(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}module.exports=t;
},{}],"hBF7":[function(require,module,exports) {
var e=require("./_nativeCreate"),r="__lodash_hash_undefined__",t=Object.prototype,a=t.hasOwnProperty;function _(t){var _=this.__data__;if(e){var o=_[t];return o===r?void 0:o}return a.call(_,t)?_[t]:void 0}module.exports=_;
},{"./_nativeCreate":"Shes"}],"CKBs":[function(require,module,exports) {
var e=require("./_nativeCreate"),r=Object.prototype,t=r.hasOwnProperty;function a(r){var a=this.__data__;return e?void 0!==a[r]:t.call(a,r)}module.exports=a;
},{"./_nativeCreate":"Shes"}],"rhCp":[function(require,module,exports) {
var e=require("./_nativeCreate"),_="__lodash_hash_undefined__";function i(i,t){var a=this.__data__;return this.size+=this.has(i)?0:1,a[i]=e&&void 0===t?_:t,this}module.exports=i;
},{"./_nativeCreate":"Shes"}],"GyRm":[function(require,module,exports) {
var e=require("./_hashClear"),r=require("./_hashDelete"),t=require("./_hashGet"),h=require("./_hashHas"),o=require("./_hashSet");function a(e){var r=-1,t=null==e?0:e.length;for(this.clear();++r<t;){var h=e[r];this.set(h[0],h[1])}}a.prototype.clear=e,a.prototype.delete=r,a.prototype.get=t,a.prototype.has=h,a.prototype.set=o,module.exports=a;
},{"./_hashClear":"w7U7","./_hashDelete":"iOZZ","./_hashGet":"hBF7","./_hashHas":"CKBs","./_hashSet":"rhCp"}],"UOHr":[function(require,module,exports) {
var e=require("./_Hash"),i=require("./_ListCache"),r=require("./_Map");function a(){this.size=0,this.__data__={hash:new e,map:new(r||i),string:new e}}module.exports=a;
},{"./_Hash":"GyRm","./_ListCache":"hCml","./_Map":"ztLC"}],"MmTn":[function(require,module,exports) {
function o(o){var n=typeof o;return"string"==n||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==o:null===o}module.exports=o;
},{}],"us4P":[function(require,module,exports) {
var r=require("./_isKeyable");function e(e,a){var t=e.__data__;return r(a)?t["string"==typeof a?"string":"hash"]:t.map}module.exports=e;
},{"./_isKeyable":"MmTn"}],"QjAw":[function(require,module,exports) {
var e=require("./_getMapData");function t(t){var r=e(this,t).delete(t);return this.size-=r?1:0,r}module.exports=t;
},{"./_getMapData":"us4P"}],"XTfE":[function(require,module,exports) {
var e=require("./_getMapData");function t(t){return e(this,t).get(t)}module.exports=t;
},{"./_getMapData":"us4P"}],"jqgC":[function(require,module,exports) {
var e=require("./_getMapData");function r(r){return e(this,r).has(r)}module.exports=r;
},{"./_getMapData":"us4P"}],"QE4m":[function(require,module,exports) {
var e=require("./_getMapData");function t(t,i){var s=e(this,t),r=s.size;return s.set(t,i),this.size+=s.size==r?0:1,this}module.exports=t;
},{"./_getMapData":"us4P"}],"ZmWn":[function(require,module,exports) {
var e=require("./_mapCacheClear"),r=require("./_mapCacheDelete"),t=require("./_mapCacheGet"),a=require("./_mapCacheHas"),p=require("./_mapCacheSet");function o(e){var r=-1,t=null==e?0:e.length;for(this.clear();++r<t;){var a=e[r];this.set(a[0],a[1])}}o.prototype.clear=e,o.prototype.delete=r,o.prototype.get=t,o.prototype.has=a,o.prototype.set=p,module.exports=o;
},{"./_mapCacheClear":"UOHr","./_mapCacheDelete":"QjAw","./_mapCacheGet":"XTfE","./_mapCacheHas":"jqgC","./_mapCacheSet":"QE4m"}],"nHDT":[function(require,module,exports) {
var e=require("./_ListCache"),i=require("./_Map"),t=require("./_MapCache"),s=200;function _(_,a){var r=this.__data__;if(r instanceof e){var h=r.__data__;if(!i||h.length<s-1)return h.push([_,a]),this.size=++r.size,this;r=this.__data__=new t(h)}return r.set(_,a),this.size=r.size,this}module.exports=_;
},{"./_ListCache":"hCml","./_Map":"ztLC","./_MapCache":"ZmWn"}],"rYKR":[function(require,module,exports) {
var e=require("./_ListCache"),t=require("./_stackClear"),r=require("./_stackDelete"),a=require("./_stackGet"),s=require("./_stackHas"),o=require("./_stackSet");function i(t){var r=this.__data__=new e(t);this.size=r.size}i.prototype.clear=t,i.prototype.delete=r,i.prototype.get=a,i.prototype.has=s,i.prototype.set=o,module.exports=i;
},{"./_ListCache":"hCml","./_stackClear":"oGrO","./_stackDelete":"gG8W","./_stackGet":"bAeR","./_stackHas":"xs8c","./_stackSet":"nHDT"}],"kGbX":[function(require,module,exports) {
var e=require("./_getNative"),r=function(){try{var r=e(Object,"defineProperty");return r({},"",{}),r}catch(t){}}();module.exports=r;
},{"./_getNative":"b5xW"}],"qFLy":[function(require,module,exports) {
var e=require("./_defineProperty");function r(r,o,u){"__proto__"==o&&e?e(r,o,{configurable:!0,enumerable:!0,value:u,writable:!0}):r[o]=u}module.exports=r;
},{"./_defineProperty":"kGbX"}],"g7Kx":[function(require,module,exports) {
var e=require("./_baseAssignValue"),r=require("./eq"),o=Object.prototype,a=o.hasOwnProperty;function i(o,i,t){var n=o[i];a.call(o,i)&&r(n,t)&&(void 0!==t||i in o)||e(o,i,t)}module.exports=i;
},{"./_baseAssignValue":"qFLy","./eq":"LaH9"}],"Gk15":[function(require,module,exports) {
var r=require("./_assignValue"),e=require("./_baseAssignValue");function a(a,i,u,n){var o=!u;u||(u={});for(var s=-1,v=i.length;++s<v;){var l=i[s],t=n?n(u[l],a[l],l,u,a):void 0;void 0===t&&(t=a[l]),o?e(u,l,t):r(u,l,t)}return u}module.exports=a;
},{"./_assignValue":"g7Kx","./_baseAssignValue":"qFLy"}],"HAX5":[function(require,module,exports) {
var e=require("./_copyObject"),r=require("./keys");function u(u,o){return u&&e(o,r(o),u)}module.exports=u;
},{"./_copyObject":"Gk15","./keys":"svoD"}],"WhKt":[function(require,module,exports) {
function r(r){var n=[];if(null!=r)for(var u in Object(r))n.push(u);return n}module.exports=r;
},{}],"Q6xK":[function(require,module,exports) {
var r=require("./isObject"),e=require("./_isPrototype"),t=require("./_nativeKeysIn"),o=Object.prototype,i=o.hasOwnProperty;function n(o){if(!r(o))return t(o);var n=e(o),u=[];for(var s in o)("constructor"!=s||!n&&i.call(o,s))&&u.push(s);return u}module.exports=n;
},{"./isObject":"ihtJ","./_isPrototype":"GRYO","./_nativeKeysIn":"WhKt"}],"H2Yl":[function(require,module,exports) {
var e=require("./_arrayLikeKeys"),r=require("./_baseKeysIn"),i=require("./isArrayLike");function u(u){return i(u)?e(u,!0):r(u)}module.exports=u;
},{"./_arrayLikeKeys":"Fz1h","./_baseKeysIn":"Q6xK","./isArrayLike":"XeS6"}],"lmMK":[function(require,module,exports) {
var e=require("./_copyObject"),r=require("./keysIn");function u(u,n){return u&&e(n,r(n),u)}module.exports=u;
},{"./_copyObject":"Gk15","./keysIn":"H2Yl"}],"t32k":[function(require,module,exports) {
var e=require("./_root"),o="object"==typeof exports&&exports&&!exports.nodeType&&exports,r=o&&"object"==typeof module&&module&&!module.nodeType&&module,t=r&&r.exports===o,p=t?e.Buffer:void 0,u=p?p.allocUnsafe:void 0;function n(e,o){if(o)return e.slice();var r=e.length,t=u?u(r):new e.constructor(r);return e.copy(t),t}module.exports=n;
},{"./_root":"M4cY"}],"nApe":[function(require,module,exports) {
function r(r,e){var n=-1,o=r.length;for(e||(e=Array(o));++n<o;)e[n]=r[n];return e}module.exports=r;
},{}],"Kder":[function(require,module,exports) {
function r(r,n){for(var e=-1,l=null==r?0:r.length,o=0,t=[];++e<l;){var u=r[e];n(u,e,r)&&(t[o++]=u)}return t}module.exports=r;
},{}],"k193":[function(require,module,exports) {
function e(){return[]}module.exports=e;
},{}],"WqEW":[function(require,module,exports) {
var r=require("./_arrayFilter"),e=require("./stubArray"),t=Object.prototype,u=t.propertyIsEnumerable,n=Object.getOwnPropertySymbols,o=n?function(e){return null==e?[]:(e=Object(e),r(n(e),function(r){return u.call(e,r)}))}:e;module.exports=o;
},{"./_arrayFilter":"Kder","./stubArray":"k193"}],"uJWd":[function(require,module,exports) {
var e=require("./_copyObject"),r=require("./_getSymbols");function o(o,t){return e(o,r(o),t)}module.exports=o;
},{"./_copyObject":"Gk15","./_getSymbols":"WqEW"}],"CDJt":[function(require,module,exports) {
function e(e,n){for(var r=-1,t=n.length,o=e.length;++r<t;)e[o+r]=n[r];return e}module.exports=e;
},{}],"xwPX":[function(require,module,exports) {
var r=require("./_arrayPush"),e=require("./_getPrototype"),t=require("./_getSymbols"),o=require("./stubArray"),u=Object.getOwnPropertySymbols,y=u?function(o){for(var u=[];o;)r(u,t(o)),o=e(o);return u}:o;module.exports=y;
},{"./_arrayPush":"CDJt","./_getPrototype":"q4qA","./_getSymbols":"WqEW","./stubArray":"k193"}],"pCbY":[function(require,module,exports) {
var e=require("./_copyObject"),r=require("./_getSymbolsIn");function o(o,t){return e(o,r(o),t)}module.exports=o;
},{"./_copyObject":"Gk15","./_getSymbolsIn":"xwPX"}],"UoCT":[function(require,module,exports) {
var r=require("./_arrayPush"),e=require("./isArray");function u(u,a,i){var n=a(u);return e(u)?n:r(n,i(u))}module.exports=u;
},{"./_arrayPush":"CDJt","./isArray":"F0hp"}],"cWHV":[function(require,module,exports) {
var e=require("./_baseGetAllKeys"),r=require("./_getSymbols"),u=require("./keys");function s(s){return e(s,u,r)}module.exports=s;
},{"./_baseGetAllKeys":"UoCT","./_getSymbols":"WqEW","./keys":"svoD"}],"YDpP":[function(require,module,exports) {
var e=require("./_baseGetAllKeys"),r=require("./_getSymbolsIn"),u=require("./keysIn");function n(n){return e(n,u,r)}module.exports=n;
},{"./_baseGetAllKeys":"UoCT","./_getSymbolsIn":"xwPX","./keysIn":"H2Yl"}],"tNX1":[function(require,module,exports) {
var e=require("./_getNative"),r=require("./_root"),t=e(r,"DataView");module.exports=t;
},{"./_getNative":"b5xW","./_root":"M4cY"}],"xIO6":[function(require,module,exports) {
var e=require("./_getNative"),r=require("./_root"),o=e(r,"Promise");module.exports=o;
},{"./_getNative":"b5xW","./_root":"M4cY"}],"dnze":[function(require,module,exports) {
var e=require("./_getNative"),r=require("./_root"),t=e(r,"Set");module.exports=t;
},{"./_getNative":"b5xW","./_root":"M4cY"}],"zzh8":[function(require,module,exports) {
var e=require("./_getNative"),r=require("./_root"),a=e(r,"WeakMap");module.exports=a;
},{"./_getNative":"b5xW","./_root":"M4cY"}],"Q9e6":[function(require,module,exports) {
var e=require("./_DataView"),r=require("./_Map"),t=require("./_Promise"),a=require("./_Set"),u=require("./_WeakMap"),c=require("./_baseGetTag"),o=require("./_toSource"),i="[object Map]",n="[object Object]",s="[object Promise]",b="[object Set]",w="[object WeakMap]",j="[object DataView]",q=o(e),_=o(r),p=o(t),f=o(a),v=o(u),M=c;(e&&M(new e(new ArrayBuffer(1)))!=j||r&&M(new r)!=i||t&&M(t.resolve())!=s||a&&M(new a)!=b||u&&M(new u)!=w)&&(M=function(e){var r=c(e),t=r==n?e.constructor:void 0,a=t?o(t):"";if(a)switch(a){case q:return j;case _:return i;case p:return s;case f:return b;case v:return w}return r}),module.exports=M;
},{"./_DataView":"tNX1","./_Map":"ztLC","./_Promise":"xIO6","./_Set":"dnze","./_WeakMap":"zzh8","./_baseGetTag":"fkTb","./_toSource":"MjOM"}],"J6OF":[function(require,module,exports) {
var t=Object.prototype,n=t.hasOwnProperty;function e(t){var e=t.length,r=new t.constructor(e);return e&&"string"==typeof t[0]&&n.call(t,"index")&&(r.index=t.index,r.input=t.input),r}module.exports=e;
},{}],"NRNF":[function(require,module,exports) {
var r=require("./_root"),e=r.Uint8Array;module.exports=e;
},{"./_root":"M4cY"}],"amnB":[function(require,module,exports) {
var e=require("./_Uint8Array");function r(r){var n=new r.constructor(r.byteLength);return new e(n).set(new e(r)),n}module.exports=r;
},{"./_Uint8Array":"NRNF"}],"QFWB":[function(require,module,exports) {
var e=require("./_cloneArrayBuffer");function r(r,f){var t=f?e(r.buffer):r.buffer;return new r.constructor(t,r.byteOffset,r.byteLength)}module.exports=r;
},{"./_cloneArrayBuffer":"amnB"}],"R2Eh":[function(require,module,exports) {
var e=/\w*$/;function r(r){var n=new r.constructor(r.source,e.exec(r));return n.lastIndex=r.lastIndex,n}module.exports=r;
},{}],"IKOn":[function(require,module,exports) {
var e=require("./_Symbol"),o=e?e.prototype:void 0,r=o?o.valueOf:void 0;function t(e){return r?Object(r.call(e)):{}}module.exports=t;
},{"./_Symbol":"ydxh"}],"WfSD":[function(require,module,exports) {
var r=require("./_cloneArrayBuffer");function e(e,f){var t=f?r(e.buffer):e.buffer;return new e.constructor(t,e.byteOffset,e.length)}module.exports=e;
},{"./_cloneArrayBuffer":"amnB"}],"f9cg":[function(require,module,exports) {
var e=require("./_cloneArrayBuffer"),r=require("./_cloneDataView"),c=require("./_cloneRegExp"),t=require("./_cloneSymbol"),a=require("./_cloneTypedArray"),o="[object Boolean]",n="[object Date]",b="[object Map]",s="[object Number]",u="[object RegExp]",j="[object Set]",y="[object String]",i="[object Symbol]",l="[object ArrayBuffer]",A="[object DataView]",w="[object Float32Array]",p="[object Float64Array]",f="[object Int8Array]",m="[object Int16Array]",q="[object Int32Array]",_="[object Uint8Array]",S="[object Uint8ClampedArray]",U="[object Uint16Array]",d="[object Uint32Array]";function g(g,x,B){var D=g.constructor;switch(x){case l:return e(g);case o:case n:return new D(+g);case A:return r(g,B);case w:case p:case f:case m:case q:case _:case S:case U:case d:return a(g,B);case b:return new D;case s:case y:return new D(g);case u:return c(g);case j:return new D;case i:return t(g)}}module.exports=g;
},{"./_cloneArrayBuffer":"amnB","./_cloneDataView":"QFWB","./_cloneRegExp":"R2Eh","./_cloneSymbol":"IKOn","./_cloneTypedArray":"WfSD"}],"PSsF":[function(require,module,exports) {
var r=require("./isObject"),e=Object.create,t=function(){function t(){}return function(n){if(!r(n))return{};if(e)return e(n);t.prototype=n;var o=new t;return t.prototype=void 0,o}}();module.exports=t;
},{"./isObject":"ihtJ"}],"PDaD":[function(require,module,exports) {
var e=require("./_baseCreate"),r=require("./_getPrototype"),t=require("./_isPrototype");function o(o){return"function"!=typeof o.constructor||t(o)?{}:e(r(o))}module.exports=o;
},{"./_baseCreate":"PSsF","./_getPrototype":"q4qA","./_isPrototype":"GRYO"}],"DNH3":[function(require,module,exports) {
var e=require("./_getTag"),r=require("./isObjectLike"),t="[object Map]";function i(i){return r(i)&&e(i)==t}module.exports=i;
},{"./_getTag":"Q9e6","./isObjectLike":"cwaR"}],"jHOR":[function(require,module,exports) {
var e=require("./_baseIsMap"),r=require("./_baseUnary"),a=require("./_nodeUtil"),i=a&&a.isMap,s=i?r(i):e;module.exports=s;
},{"./_baseIsMap":"DNH3","./_baseUnary":"kFVy","./_nodeUtil":"a9Sd"}],"AB6A":[function(require,module,exports) {
var e=require("./_getTag"),r=require("./isObjectLike"),t="[object Set]";function i(i){return r(i)&&e(i)==t}module.exports=i;
},{"./_getTag":"Q9e6","./isObjectLike":"cwaR"}],"vvmV":[function(require,module,exports) {
var e=require("./_baseIsSet"),r=require("./_baseUnary"),i=require("./_nodeUtil"),s=i&&i.isSet,a=s?r(s):e;module.exports=a;
},{"./_baseIsSet":"AB6A","./_baseUnary":"kFVy","./_nodeUtil":"a9Sd"}],"f0rf":[function(require,module,exports) {
var e=require("./_Stack"),r=require("./_arrayEach"),t=require("./_assignValue"),i=require("./_baseAssign"),o=require("./_baseAssignIn"),n=require("./_cloneBuffer"),a=require("./_copyArray"),c=require("./_copySymbols"),u=require("./_copySymbolsIn"),b=require("./_getAllKeys"),j=require("./_getAllKeysIn"),y=require("./_getTag"),s=require("./_initCloneArray"),q=require("./_initCloneByTag"),f=require("./_initCloneObject"),l=require("./isArray"),A=require("./isBuffer"),_=require("./isMap"),g=require("./isObject"),p=require("./isSet"),v=require("./keys"),m=require("./keysIn"),I=1,S=2,d=4,B="[object Arguments]",E="[object Array]",k="[object Boolean]",C="[object Date]",F="[object Error]",U="[object Function]",h="[object GeneratorFunction]",M="[object Map]",O="[object Number]",w="[object Object]",x="[object RegExp]",D="[object Set]",K="[object String]",T="[object Symbol]",V="[object WeakMap]",G="[object ArrayBuffer]",N="[object DataView]",R="[object Float32Array]",W="[object Float64Array]",z="[object Int8Array]",H="[object Int16Array]",J="[object Int32Array]",L="[object Uint8Array]",P="[object Uint8ClampedArray]",Q="[object Uint16Array]",X="[object Uint32Array]",Y={};function Z(E,k,C,F,M,O){var x,D=k&I,K=k&S,T=k&d;if(C&&(x=M?C(E,F,M,O):C(E)),void 0!==x)return x;if(!g(E))return E;var V=l(E);if(V){if(x=s(E),!D)return a(E,x)}else{var G=y(E),N=G==U||G==h;if(A(E))return n(E,D);if(G==w||G==B||N&&!M){if(x=K||N?{}:f(E),!D)return K?u(E,o(x,E)):c(E,i(x,E))}else{if(!Y[G])return M?E:{};x=q(E,G,D)}}O||(O=new e);var R=O.get(E);if(R)return R;O.set(E,x),p(E)?E.forEach(function(e){x.add(Z(e,k,C,e,E,O))}):_(E)&&E.forEach(function(e,r){x.set(r,Z(e,k,C,r,E,O))});var W=V?void 0:(T?K?j:b:K?m:v)(E);return r(W||E,function(e,r){W&&(e=E[r=e]),t(x,r,Z(e,k,C,r,E,O))}),x}Y[B]=Y[E]=Y[G]=Y[N]=Y[k]=Y[C]=Y[R]=Y[W]=Y[z]=Y[H]=Y[J]=Y[M]=Y[O]=Y[w]=Y[x]=Y[D]=Y[K]=Y[T]=Y[L]=Y[P]=Y[Q]=Y[X]=!0,Y[F]=Y[U]=Y[V]=!1,module.exports=Z;
},{"./_Stack":"rYKR","./_arrayEach":"vLP6","./_assignValue":"g7Kx","./_baseAssign":"HAX5","./_baseAssignIn":"lmMK","./_cloneBuffer":"t32k","./_copyArray":"nApe","./_copySymbols":"uJWd","./_copySymbolsIn":"pCbY","./_getAllKeys":"cWHV","./_getAllKeysIn":"YDpP","./_getTag":"Q9e6","./_initCloneArray":"J6OF","./_initCloneByTag":"f9cg","./_initCloneObject":"PDaD","./isArray":"F0hp","./isBuffer":"Cdux","./isMap":"jHOR","./isObject":"ihtJ","./isSet":"vvmV","./keys":"svoD","./keysIn":"H2Yl"}],"j2CJ":[function(require,module,exports) {
var e=require("./_baseClone"),r=4;function n(n){return e(n,r)}module.exports=n;
},{"./_baseClone":"f0rf"}],"wZpv":[function(require,module,exports) {
var _="__lodash_hash_undefined__";function t(t){return this.__data__.set(t,_),this}module.exports=t;
},{}],"Ne64":[function(require,module,exports) {
var e=require("./_MapCache"),t=require("./_setCacheAdd"),r=require("./_setCacheHas");function a(t){var r=-1,a=null==t?0:t.length;for(this.__data__=new e;++r<a;)this.add(t[r])}a.prototype.add=a.prototype.push=t,a.prototype.has=r,module.exports=a;
},{"./_MapCache":"ZmWn","./_setCacheAdd":"wZpv","./_setCacheHas":"xs8c"}],"MOxx":[function(require,module,exports) {
function r(r,n){for(var e=-1,t=null==r?0:r.length;++e<t;)if(n(r[e],e,r))return!0;return!1}module.exports=r;
},{}],"qOwK":[function(require,module,exports) {
function e(e,n){return e.has(n)}module.exports=e;
},{}],"ACVG":[function(require,module,exports) {
var e=require("./_SetCache"),r=require("./_arraySome"),i=require("./_cacheHas"),t=1,a=2;function n(n,f,u,o,v,c){var l=u&t,s=n.length,d=f.length;if(s!=d&&!(l&&d>s))return!1;var h=c.get(n),g=c.get(f);if(h&&g)return h==f&&g==n;var b=-1,k=!0,q=u&a?new e:void 0;for(c.set(n,f),c.set(f,n);++b<s;){var _=n[b],m=f[b];if(o)var p=l?o(m,_,b,f,n,c):o(_,m,b,n,f,c);if(void 0!==p){if(p)continue;k=!1;break}if(q){if(!r(f,function(e,r){if(!i(q,r)&&(_===e||v(_,e,u,o,c)))return q.push(r)})){k=!1;break}}else if(_!==m&&!v(_,m,u,o,c)){k=!1;break}}return c.delete(n),c.delete(f),k}module.exports=n;
},{"./_SetCache":"Ne64","./_arraySome":"MOxx","./_cacheHas":"qOwK"}],"XDXg":[function(require,module,exports) {
function r(r){var n=-1,o=Array(r.size);return r.forEach(function(r,e){o[++n]=[e,r]}),o}module.exports=r;
},{}],"xWx9":[function(require,module,exports) {
function r(r){var n=-1,o=Array(r.size);return r.forEach(function(r){o[++n]=r}),o}module.exports=r;
},{}],"Cm03":[function(require,module,exports) {
var e=require("./_Symbol"),r=require("./_Uint8Array"),t=require("./eq"),a=require("./_equalArrays"),c=require("./_mapToArray"),o=require("./_setToArray"),s=1,u=2,n="[object Boolean]",b="[object Date]",i="[object Error]",f="[object Map]",y="[object Number]",j="[object RegExp]",l="[object Set]",g="[object String]",m="[object Symbol]",q="[object ArrayBuffer]",v="[object DataView]",p=e?e.prototype:void 0,h=p?p.valueOf:void 0;function A(e,p,A,_,d,w,L){switch(A){case v:if(e.byteLength!=p.byteLength||e.byteOffset!=p.byteOffset)return!1;e=e.buffer,p=p.buffer;case q:return!(e.byteLength!=p.byteLength||!w(new r(e),new r(p)));case n:case b:case y:return t(+e,+p);case i:return e.name==p.name&&e.message==p.message;case j:case g:return e==p+"";case f:var S=c;case l:var O=_&s;if(S||(S=o),e.size!=p.size&&!O)return!1;var x=L.get(e);if(x)return x==p;_|=u,L.set(e,p);var z=a(S(e),S(p),_,d,w,L);return L.delete(e),z;case m:if(h)return h.call(e)==h.call(p)}return!1}module.exports=A;
},{"./_Symbol":"ydxh","./_Uint8Array":"NRNF","./eq":"LaH9","./_equalArrays":"ACVG","./_mapToArray":"XDXg","./_setToArray":"xWx9"}],"ZpQC":[function(require,module,exports) {
var r=require("./_getAllKeys"),t=1,e=Object.prototype,n=e.hasOwnProperty;function o(e,o,c,i,a,f){var u=c&t,s=r(e),v=s.length;if(v!=r(o).length&&!u)return!1;for(var l=v;l--;){var p=s[l];if(!(u?p in o:n.call(o,p)))return!1}var g=f.get(e),y=f.get(o);if(g&&y)return g==o&&y==e;var d=!0;f.set(e,o),f.set(o,e);for(var h=u;++l<v;){var b=e[p=s[l]],O=o[p];if(i)var j=u?i(O,b,p,o,e,f):i(b,O,p,e,o,f);if(!(void 0===j?b===O||a(b,O,c,i,f):j)){d=!1;break}h||(h="constructor"==p)}if(d&&!h){var k=e.constructor,m=o.constructor;k!=m&&"constructor"in e&&"constructor"in o&&!("function"==typeof k&&k instanceof k&&"function"==typeof m&&m instanceof m)&&(d=!1)}return f.delete(e),f.delete(o),d}module.exports=o;
},{"./_getAllKeys":"cWHV"}],"FN8H":[function(require,module,exports) {
var e=require("./_Stack"),r=require("./_equalArrays"),a=require("./_equalByTag"),u=require("./_equalObjects"),t=require("./_getTag"),i=require("./isArray"),_=require("./isBuffer"),n=require("./isTypedArray"),q=1,c="[object Arguments]",l="[object Array]",o="[object Object]",p=Object.prototype,f=p.hasOwnProperty;function s(p,s,y,b,j,v){var w=i(p),A=i(s),d=w?l:t(p),g=A?l:t(s),O=(d=d==c?o:d)==o,T=(g=g==c?o:g)==o,m=d==g;if(m&&_(p)){if(!_(s))return!1;w=!0,O=!1}if(m&&!O)return v||(v=new e),w||n(p)?r(p,s,y,b,j,v):a(p,s,d,y,b,j,v);if(!(y&q)){var B=O&&f.call(p,"__wrapped__"),h=T&&f.call(s,"__wrapped__");if(B||h){var k=B?p.value():p,x=h?s.value():s;return v||(v=new e),j(k,x,y,b,v)}}return!!m&&(v||(v=new e),u(p,s,y,b,j,v))}module.exports=s;
},{"./_Stack":"rYKR","./_equalArrays":"ACVG","./_equalByTag":"Cm03","./_equalObjects":"ZpQC","./_getTag":"Q9e6","./isArray":"F0hp","./isBuffer":"Cdux","./isTypedArray":"pKgN"}],"ANt1":[function(require,module,exports) {
var e=require("./_baseIsEqualDeep"),r=require("./isObjectLike");function u(l,i,n,s,t){return l===i||(null==l||null==i||!r(l)&&!r(i)?l!=l&&i!=i:e(l,i,n,s,u,t))}module.exports=u;
},{"./_baseIsEqualDeep":"FN8H","./isObjectLike":"cwaR"}],"WLLv":[function(require,module,exports) {
var r=require("./_Stack"),e=require("./_baseIsEqual"),i=1,n=2;function u(u,t,a,f){var v=a.length,o=v,l=!f;if(null==u)return!o;for(u=Object(u);v--;){var s=a[v];if(l&&s[2]?s[1]!==u[s[0]]:!(s[0]in u))return!1}for(;++v<o;){var c=(s=a[v])[0],d=u[c],q=s[1];if(l&&s[2]){if(void 0===d&&!(c in u))return!1}else{var b=new r;if(f)var _=f(d,q,c,u,t,b);if(!(void 0===_?e(q,d,i|n,f,b):_))return!1}}return!0}module.exports=u;
},{"./_Stack":"rYKR","./_baseIsEqual":"ANt1"}],"YxmV":[function(require,module,exports) {
var e=require("./isObject");function r(r){return r==r&&!e(r)}module.exports=r;
},{"./isObject":"ihtJ"}],"hPkd":[function(require,module,exports) {
var r=require("./_isStrictComparable"),e=require("./keys");function t(t){for(var a=e(t),i=a.length;i--;){var o=a[i],u=t[o];a[i]=[o,u,r(u)]}return a}module.exports=t;
},{"./_isStrictComparable":"YxmV","./keys":"svoD"}],"EIPX":[function(require,module,exports) {
function n(n,t){return function(u){return null!=u&&(u[n]===t&&(void 0!==t||n in Object(u)))}}module.exports=n;
},{}],"xxHk":[function(require,module,exports) {
var e=require("./_baseIsMatch"),r=require("./_getMatchData"),t=require("./_matchesStrictComparable");function a(a){var u=r(a);return 1==u.length&&u[0][2]?t(u[0][0],u[0][1]):function(r){return r===a||e(r,a,u)}}module.exports=a;
},{"./_baseIsMatch":"WLLv","./_getMatchData":"hPkd","./_matchesStrictComparable":"EIPX"}],"DFEd":[function(require,module,exports) {
var e=require("./_baseGetTag"),r=require("./isObjectLike"),o="[object Symbol]";function t(t){return"symbol"==typeof t||r(t)&&e(t)==o}module.exports=t;
},{"./_baseGetTag":"fkTb","./isObjectLike":"cwaR"}],"Bhgs":[function(require,module,exports) {
var e=require("./isArray"),r=require("./isSymbol"),t=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,n=/^\w*$/;function u(u,l){if(e(u))return!1;var o=typeof u;return!("number"!=o&&"symbol"!=o&&"boolean"!=o&&null!=u&&!r(u))||(n.test(u)||!t.test(u)||null!=l&&u in Object(l))}module.exports=u;
},{"./isArray":"F0hp","./isSymbol":"DFEd"}],"wFGW":[function(require,module,exports) {
var e=require("./_MapCache"),r="Expected a function";function t(n,a){if("function"!=typeof n||null!=a&&"function"!=typeof a)throw new TypeError(r);var c=function(){var e=arguments,r=a?a.apply(this,e):e[0],t=c.cache;if(t.has(r))return t.get(r);var o=n.apply(this,e);return c.cache=t.set(r,o)||t,o};return c.cache=new(t.Cache||e),c}t.Cache=e,module.exports=t;
},{"./_MapCache":"ZmWn"}],"CquK":[function(require,module,exports) {
var e=require("./memoize"),r=500;function n(n){var u=e(n,function(e){return c.size===r&&c.clear(),e}),c=u.cache;return u}module.exports=n;
},{"./memoize":"wFGW"}],"pYME":[function(require,module,exports) {
var e=require("./_memoizeCapped"),r=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,p=/\\(\\)?/g,u=e(function(e){var u=[];return 46===e.charCodeAt(0)&&u.push(""),e.replace(r,function(e,r,a,o){u.push(a?o.replace(p,"$1"):r||e)}),u});module.exports=u;
},{"./_memoizeCapped":"CquK"}],"oCpU":[function(require,module,exports) {
function r(r,n){for(var e=-1,l=null==r?0:r.length,o=Array(l);++e<l;)o[e]=n(r[e],e,r);return o}module.exports=r;
},{}],"e2ls":[function(require,module,exports) {
var r=require("./_Symbol"),e=require("./_arrayMap"),i=require("./isArray"),t=require("./isSymbol"),o=1/0,u=r?r.prototype:void 0,n=u?u.toString:void 0;function a(r){if("string"==typeof r)return r;if(i(r))return e(r,a)+"";if(t(r))return n?n.call(r):"";var u=r+"";return"0"==u&&1/r==-o?"-0":u}module.exports=a;
},{"./_Symbol":"ydxh","./_arrayMap":"oCpU","./isArray":"F0hp","./isSymbol":"DFEd"}],"QWoG":[function(require,module,exports) {
var r=require("./_baseToString");function e(e){return null==e?"":r(e)}module.exports=e;
},{"./_baseToString":"e2ls"}],"RbEK":[function(require,module,exports) {
var r=require("./isArray"),e=require("./_isKey"),i=require("./_stringToPath"),t=require("./toString");function u(u,n){return r(u)?u:e(u,n)?[u]:i(t(u))}module.exports=u;
},{"./isArray":"F0hp","./_isKey":"Bhgs","./_stringToPath":"pYME","./toString":"QWoG"}],"BA1W":[function(require,module,exports) {
var r=require("./isSymbol"),e=1/0;function t(t){if("string"==typeof t||r(t))return t;var i=t+"";return"0"==i&&1/t==-e?"-0":i}module.exports=t;
},{"./isSymbol":"DFEd"}],"Ws9z":[function(require,module,exports) {
var r=require("./_castPath"),e=require("./_toKey");function t(t,o){for(var u=0,n=(o=r(o,t)).length;null!=t&&u<n;)t=t[e(o[u++])];return u&&u==n?t:void 0}module.exports=t;
},{"./_castPath":"RbEK","./_toKey":"BA1W"}],"BBFX":[function(require,module,exports) {
var e=require("./_baseGet");function r(r,o,u){var i=null==r?void 0:e(r,o);return void 0===i?u:i}module.exports=r;
},{"./_baseGet":"Ws9z"}],"Ag0k":[function(require,module,exports) {
function n(n,e){return null!=n&&e in Object(n)}module.exports=n;
},{}],"KEJA":[function(require,module,exports) {
var r=require("./_castPath"),e=require("./isArguments"),i=require("./isArray"),u=require("./_isIndex"),n=require("./isLength"),t=require("./_toKey");function a(a,l,s){for(var q=-1,o=(l=r(l,a)).length,g=!1;++q<o;){var h=t(l[q]);if(!(g=null!=a&&s(a,h)))break;a=a[h]}return g||++q!=o?g:!!(o=null==a?0:a.length)&&n(o)&&u(h,o)&&(i(a)||e(a))}module.exports=a;
},{"./_castPath":"RbEK","./isArguments":"oh3z","./isArray":"F0hp","./_isIndex":"XqZz","./isLength":"Lm6w","./_toKey":"BA1W"}],"RLtF":[function(require,module,exports) {
var e=require("./_baseHasIn"),r=require("./_hasPath");function u(u,a){return null!=u&&r(u,a,e)}module.exports=u;
},{"./_baseHasIn":"Ag0k","./_hasPath":"KEJA"}],"A3nB":[function(require,module,exports) {
var e=require("./_baseIsEqual"),r=require("./get"),i=require("./hasIn"),u=require("./_isKey"),t=require("./_isStrictComparable"),a=require("./_matchesStrictComparable"),o=require("./_toKey"),q=1,n=2;function s(s,c){return u(s)&&t(c)?a(o(s),c):function(u){var t=r(u,s);return void 0===t&&t===c?i(u,s):e(c,t,q|n)}}module.exports=s;
},{"./_baseIsEqual":"ANt1","./get":"BBFX","./hasIn":"RLtF","./_isKey":"Bhgs","./_isStrictComparable":"YxmV","./_matchesStrictComparable":"EIPX","./_toKey":"BA1W"}],"gnsq":[function(require,module,exports) {
function n(n){return function(u){return null==u?void 0:u[n]}}module.exports=n;
},{}],"BXs1":[function(require,module,exports) {
var e=require("./_baseGet");function r(r){return function(n){return e(n,r)}}module.exports=r;
},{"./_baseGet":"Ws9z"}],"TQRE":[function(require,module,exports) {
var e=require("./_baseProperty"),r=require("./_basePropertyDeep"),u=require("./_isKey"),i=require("./_toKey");function o(o){return u(o)?e(i(o)):r(o)}module.exports=o;
},{"./_baseProperty":"gnsq","./_basePropertyDeep":"BXs1","./_isKey":"Bhgs","./_toKey":"BA1W"}],"T11M":[function(require,module,exports) {
var e=require("./_baseMatches"),r=require("./_baseMatchesProperty"),t=require("./identity"),i=require("./isArray"),u=require("./property");function o(o){return"function"==typeof o?o:null==o?t:"object"==typeof o?i(o)?r(o[0],o[1]):e(o):u(o)}module.exports=o;
},{"./_baseMatches":"xxHk","./_baseMatchesProperty":"A3nB","./identity":"FRcP","./isArray":"F0hp","./property":"TQRE"}],"LPtf":[function(require,module,exports) {
var r=require("./_baseIteratee"),e=require("./isArrayLike"),i=require("./keys");function t(t){return function(u,n,a){var o=Object(u);if(!e(u)){var v=r(n,3);u=i(u),n=function(r){return v(o[r],r,o)}}var c=t(u,n,a);return c>-1?o[v?u[c]:c]:void 0}}module.exports=t;
},{"./_baseIteratee":"T11M","./isArrayLike":"XeS6","./keys":"svoD"}],"InoQ":[function(require,module,exports) {
function r(r,e,n,t){for(var o=r.length,u=n+(t?1:-1);t?u--:++u<o;)if(e(r[u],u,r))return u;return-1}module.exports=r;
},{}],"bNFp":[function(require,module,exports) {
var r=/\s/;function t(t){for(var e=t.length;e--&&r.test(t.charAt(e)););return e}module.exports=t;
},{}],"lyYi":[function(require,module,exports) {
var e=require("./_trimmedEndIndex"),r=/^\s+/;function n(n){return n?n.slice(0,e(n)+1).replace(r,""):n}module.exports=n;
},{"./_trimmedEndIndex":"bNFp"}],"K9rX":[function(require,module,exports) {
var e=require("./_baseTrim"),r=require("./isObject"),t=require("./isSymbol"),i=NaN,u=/^[-+]0x[0-9a-f]+$/i,f=/^0b[01]+$/i,n=/^0o[0-7]+$/i,s=parseInt;function a(a){if("number"==typeof a)return a;if(t(a))return i;if(r(a)){var o="function"==typeof a.valueOf?a.valueOf():a;a=r(o)?o+"":o}if("string"!=typeof a)return 0===a?a:+a;a=e(a);var b=f.test(a);return b||n.test(a)?s(a.slice(2),b?2:8):u.test(a)?i:+a}module.exports=a;
},{"./_baseTrim":"lyYi","./isObject":"ihtJ","./isSymbol":"DFEd"}],"jW8b":[function(require,module,exports) {
var e=require("./toNumber"),r=1/0,u=1.7976931348623157e308;function o(o){return o?(o=e(o))===r||o===-r?(o<0?-1:1)*u:o==o?o:0:0===o?o:0}module.exports=o;
},{"./toNumber":"K9rX"}],"HNkt":[function(require,module,exports) {
var r=require("./toFinite");function e(e){var t=r(e),i=t%1;return t==t?i?t-i:t:0}module.exports=e;
},{"./toFinite":"jW8b"}],"KVQO":[function(require,module,exports) {
var e=require("./_baseFindIndex"),r=require("./_baseIteratee"),n=require("./toInteger"),t=Math.max;function u(u,a,i){var l=null==u?0:u.length;if(!l)return-1;var o=null==i?0:n(i);return o<0&&(o=t(l+o,0)),e(u,r(a,3),o)}module.exports=u;
},{"./_baseFindIndex":"InoQ","./_baseIteratee":"T11M","./toInteger":"HNkt"}],"AiQZ":[function(require,module,exports) {
var e=require("./_createFind"),r=require("./findIndex"),d=e(r);module.exports=d;
},{"./_createFind":"LPtf","./findIndex":"KVQO"}],"CiX3":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},t=function(){function e(e,t){for(var i=0;i<t.length;i++){var l=t[i];l.enumerable=l.enumerable||!1,l.configurable=!0,"value"in l&&(l.writable=!0),Object.defineProperty(e,l.key,l)}}return function(t,i,l){return i&&e(t.prototype,i),l&&e(t,l),t}}(),i=require("lodash/clone"),l=E(i),u=require("lodash/find"),a=E(u),h=require("lodash/forEach"),r=E(h),s=require("lodash/isArray"),n=E(s),d=require("lodash/isFunction"),o=E(d),f=require("lodash/isNumber"),c=E(f),v=require("lodash/isNull"),m=E(v),p=require("lodash/isPlainObject"),y=E(p),b=require("lodash/isString"),P=E(b),q=require("lodash/isUndefined"),g=E(q);function E(e){return e&&e.__esModule?e:{default:e}}function w(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var V=function(){function i(e,t,l){var u=this,a=arguments.length<=3||void 0===arguments[3]?null:arguments[3],h=!(arguments.length<=4||void 0===arguments[4])&&arguments[4];w(this,i);var s=t.thrower,d=t.typeCheckers,o=t.typePrinters;this.path=l,this.fullPath=""+((0,m.default)(a)?"":a)+l,(0,g.default)(e)&&s.throw("`"+this.fullPath+"`'s `structure` must be defined"),(0,P.default)(e.type)||s.throw("`"+this.fullPath+"` must have a `type`"),this.types=e.type.split("|"),this.typeCheck=d.check.bind(d,this.types),this.typesStr=this.types.join("|"),this.required=!0===e.required,this.hasValue=e.hasOwnProperty("value")||e.hasOwnProperty("computeValue"),this.value=(e.computeValue||function(){return e.value})(),this.computeValue=e.computeValue,this.hasValue&&(this.valueStr=o.get(this.types[0])(this.value)),this.hasValue&&this.required&&s.throw("`"+this.fullPath+"` can't be `required` and have a `value`"),this.validators=e.validators||[],this.isElement=h,this.isElement&&(this.hasValue&&s.throw("`"+this.fullPath+"` is an `element`, it can't have a `value`"),this.required&&s.throw("`"+this.fullPath+"` is an `element`, it can't be `required`")),this.hasElement=!(0,g.default)(e.element),this.hasChildren=!(0,g.default)(e.children),this.hasElement&&this.hasChildren&&s.throw("`"+this.fullPath+"`'s structure can't have both `element` and `children`"),this.children=null,this.hasChildren&&(this.children=(0,n.default)(e.children)?[]:{},(0,r.default)(e.children,function(l,a){var h=(0,n.default)(e.children)?"["+a+"]":"."+a;u.children[a]=new i(l,t,h,u.fullPath)})),this.element=null,this.hasElement&&(this.element=new i(e.element,t,"[]",this.fullPath,!0))}return t(i,[{key:"buildValue",value:function(e){var t=this;if((0,g.default)(e)&&this.hasValue)if((0,o.default)(this.computeValue))e=this.computeValue();else{var i=(0,l.default)(this.value);e=(0,y.default)(i)&&!(0,y.default)(this.value)?this.value:i}return(0,m.default)(this.children)||(0,r.default)(this.children,function(t,i){var l=t.buildValue(e[i]);(0,g.default)(l)||(e[i]=l)}),(0,m.default)(this.element)||(0,r.default)(e,function(i,l){e[l]=t.element.buildValue(i)}),e}},{key:"_addError",value:function(e,t,i,l){(0,m.default)(i)&&(i=""),e.push({actualPath:""+i+(this.isElement?"["+l+"]":this.path),message:t,structurePath:this.isElement?i:this.fullPath})}},{key:"check",value:function(t,i){var l=this,u=arguments.length<=2||void 0===arguments[2]?null:arguments[2],a=arguments.length<=3||void 0===arguments[3]?null:arguments[3],h=void 0===t?"undefined":e(t);if(this.isElement){var s=-1===this.types.indexOf("undefined")&&-1===this.types.indexOf("any");if((0,g.default)(t)&&s)return void this._addError(i,"should be defined",u,a)}if(this.required&&(0,g.default)(t))this._addError(i,"is required",u,a);else if(!(0,g.default)(t)||this.isElement||this.required)if(this.typeCheck(t)){for(var n=0;n<this.validators.length;++n){var d=this.validators[n](t);if(!0!==d)return void this._addError(i,d,u,a)}this.hasChildren&&(0,r.default)(this.children,function(e,u){e.check(t[u],i,l.fullPath)}),this.hasElement&&(0,r.default)(t,function(e,t){l.element.check(e,i,l.fullPath,t)})}else{var o="should be <"+this.typesStr+">, received "+h;this._addError(i,o,u,a)}}},{key:"usage",value:function(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],t=this,i=arguments.length<=1||void 0===arguments[1]?[]:arguments[1],l=arguments.length<=2||void 0===arguments[2]?4:arguments[2],u=new Array(l+1).join(" "),h=(this.required?"*":" ")+((0,a.default)(i,{structurePath:this.fullPath})?"X":" ")+u.substring(0,u.length-2),s=!(0,g.default)(e)&&!(0,m.default)(e)&&!(0,c.default)(e);s||(e="");var d=""+h+e+"<"+this.typesStr+">";return(0,m.default)(this.children)&&(0,m.default)(this.element)||!s||(d+=": "),(0,m.default)(this.children)||function(){var e=(0,n.default)(t.children);d+=e?"[":"{",d+="\n";var a=[];(0,r.default)(t.children,function(e,t){a.push(e.usage(t,i,l+2))}),d+=a.join(",\n"),d+="\n"+u,d+=e?"]":"}"}(),(0,m.default)(this.element)||(d+="["+this.element.usage(null,i,l).substr(l)+"]"),this.hasValue&&(d+=" = "+this.valueStr),d}}]),i}();exports.default=V;
},{"lodash/clone":"j2CJ","lodash/find":"AiQZ","lodash/forEach":"Cllr","lodash/isArray":"F0hp","lodash/isFunction":"CqcF","lodash/isNumber":"Pq7J","lodash/isNull":"A6c3","lodash/isPlainObject":"XOVF","lodash/isString":"QWfy","lodash/isUndefined":"HHCo"}],"XumT":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){function e(e,r){for(var t=0;t<r.length;t++){var n=r[t];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(r,t,n){return t&&e(r.prototype,t),n&&e(r,n),r}}(),r=require("lodash/forEach"),t=h(r),n=require("lodash/isNull"),u=h(n),s=require("lodash/isUndefined"),i=h(s),a=require("./Structure.js"),o=h(a);function h(e){return e&&e.__esModule?e:{default:e}}function l(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}var c=function(){function r(e,t){l(this,r),this.name=e,this.options=[],this.errors=[],this.shared=t}return e(r,[{key:"arg",value:function(e,r){if((0,i.default)(r)&&(r=e,e=null),!(r instanceof o.default)){var t=(0,u.default)(e)?"arguments["+this.options.length+"]":e;r=new o.default(r,this.shared,t)}return this.options.push({name:e,structure:r}),this}},{key:"_legend",value:function(){var e=["<...> Type","* Required"];return this.errors.length>0&&e.push("X Error"),e}},{key:"usage",value:function(){var e=this,r=[];(0,t.default)(this.options,function(t){var n=t.structure,u=t.name;r.push(n.usage(u,e.errors))});var n=[];if(n.push("Usage:\n "+this.name+"(\n"+r.join(",\n")+"\n )"),this.errors.length>0){var u=this.errors.map(function(e){return" - `"+e.actualPath+"` "+e.message}).join("\n");n.push("Errors:\n"+u)}return n.push("Legend:\n "+this._legend().join("\n ")),"\n"+n.join("\n----------------\n")}},{key:"check",value:function(){var e=this;if(this.errors=[],(0,t.default)(this.options,function(r){var t=r.structure,n=r.value;t.check(n,e.errors)}),this.errors.length>0)throw new Error(this.usage())}},{key:"values",value:function(){var e=arguments.length<=0||void 0===arguments[0]?[]:arguments[0],r=[];return(0,t.default)(this.options,function(t,n){t.value=e[n],r.push(t.structure.buildValue(t.value))}),this.check(),r}}]),r}();exports.default=c;
},{"lodash/forEach":"Cllr","lodash/isNull":"A6c3","lodash/isUndefined":"HHCo","./Structure.js":"CiX3"}],"xkg1":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),t=require("lodash/isFunction"),r=h(t),n=require("lodash/isNull"),o=h(n),i=require("lodash/isString"),u=h(i),a=require("lodash/isUndefined"),s=h(a),l=require("./ExceptionThrower.js"),d=h(l);function h(e){return e&&e.__esModule?e:{default:e}}function f(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var c=function(){function t(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],r=arguments.length<=1||void 0===arguments[1]?"Store":arguments[1];f(this,t),this.thrower=(0,o.default)(e)?new d.default(r):e.nest(r),this.store={}}return e(t,[{key:"get",value:function(e){var t=this.thrower.nest(".get");(0,u.default)(e)||t.throw("Name `"+e+"` should be a string");var r=this.store[e];return(0,s.default)(r)&&t.throw("Name `"+e+"` has no associated function"),r}},{key:"set",value:function(e,t){var n=arguments.length<=2||void 0===arguments[2]?"set":arguments[2],o=this.thrower.nest("."+n);(0,u.default)(e)||o.throw("Name `"+e+"` should be a string"),(0,r.default)(t)||o.throw("Function `"+t+"` should be a function"),this.store[e]=t}},{key:"add",value:function(e,t){this.set(e,t,"add")}}]),t}();exports.default=c;
},{"lodash/isFunction":"CqcF","lodash/isNull":"A6c3","lodash/isString":"QWfy","lodash/isUndefined":"HHCo","./ExceptionThrower.js":"wX1A"}],"otYL":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),t=require("lodash/isArray"),r=u(t),n=require("./Store.js"),o=u(n);function u(e){return e&&e.__esModule?e:{default:e}}function a(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 c(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 f=function(t){function n(e){return a(this,n),i(this,Object.getPrototypeOf(n).call(this,e,"TypeCheckerStore"))}return c(n,o.default),e(n,[{key:"check",value:function(e,t){var n=this,o=this.thrower.nest(".check");(0,r.default)(e)||o.throw("Types `"+e+"` should be an array"),0===e.length&&o.throw("Types `[]` must have at least one element");var u=!1;return e.forEach(function(e){n.get(e)(t)&&(u=!0)}),u}}]),n}();exports.default=f;
},{"lodash/isArray":"F0hp","./Store.js":"xkg1"}],"qyTw":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Store.js"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(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 u(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 i=function(e){function r(e){return o(this,r),n(this,Object.getPrototypeOf(r).call(this,e,"TypePrinterStore"))}return u(r,t.default),r}();exports.default=i;
},{"./Store.js":"xkg1"}],"bDRC":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Store.js"),t=r(e);function r(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(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 u(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 i=function(e){function r(e){return o(this,r),n(this,Object.getPrototypeOf(r).call(this,e,"ValidatorStore"))}return u(r,t.default),r}();exports.default=i;
},{"./Store.js":"xkg1"}],"UG7E":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=Object.assign||function(e){for(var r=1;r<arguments.length;r++){var t=arguments[r];for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i])}return e},r=function(){function e(e,r){for(var t=0;t<r.length;t++){var i=r[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(r,t,i){return t&&e(r.prototype,t),i&&e(r,i),r}}(),t=require("lodash/isUndefined"),i=v(t),n=require("./ExceptionThrower.js"),a=v(n),s=require("./FunctionChecker.js"),o=v(s),u=require("./Structure.js"),h=v(u),c=require("./TypeCheckerStore.js"),l=v(c),f=require("./TypePrinterStore.js"),d=v(f),y=require("./ValidatorStore.js"),p=v(y);function v(e){return e&&e.__esModule?e:{default:e}}function w(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function k(e){return e.toString()}var g=function(){function t(){w(this,t),this.thrower=new a.default("OptionsManager"),this.typeCheckers=new l.default(this.thrower),this.typePrinters=new d.default(this.thrower),this.validators=new p.default(this.thrower),this._shared={thrower:this.thrower,typeCheckers:this.typeCheckers,typePrinters:this.typePrinters}}return r(t,[{key:"registerType",value:function(e){var r=e.name,t=e.checker,i=e.printer,n=void 0===i?k:i;return this.typeCheckers.add(r,t),this.typePrinters.add(r,n),this}},{key:"registerTypes",value:function(e){return e.forEach(this.registerType,this),this}},{key:"registerValidator",value:function(e){var r=e.name,t=e.validator;return this.validators.add(r,t),this}},{key:"registerValidators",value:function(e){return e.forEach(this.registerValidator,this),this}},{key:"validator",value:function(e){for(var r=arguments.length,t=Array(r>1?r-1:0),i=1;i<r;i++)t[i-1]=arguments[i];return this.validators.get(e).apply(void 0,t)}},{key:"structure",value:function(e,r){return(0,i.default)(r)&&(r=e,e=""),new h.default(r,this._shared,e)}},{key:"check",value:function(r){var t=e({},this._shared,{thrower:this.thrower.nest(".check")});return new o.default(r,t)}}]),t}();exports.default=g;
},{"lodash/isUndefined":"HHCo","./ExceptionThrower.js":"wX1A","./FunctionChecker.js":"XumT","./Structure.js":"CiX3","./TypeCheckerStore.js":"otYL","./TypePrinterStore.js":"qyTw","./ValidatorStore.js":"bDRC"}],"mUuq":[function(require,module,exports) {
"use strict";var e=require("./src/types/undefined.js"),r=g(e),s=require("./src/types/null.js"),t=g(s),u=require("./src/types/boolean.js"),i=g(u),n=require("./src/types/number.js"),a=g(n),l=require("./src/types/string.js"),c=g(l),d=require("./src/types/function.js"),f=g(d),p=require("./src/types/Array.js"),j=g(p),y=require("./src/types/Object.js"),o=g(y),q=require("./src/OptionsManager.js"),b=g(q);function g(e){return e&&e.__esModule?e:{default:e}}module.exports=function(){return(new b.default).registerTypes([r.default,t.default,i.default,a.default,c.default,f.default,j.default,o.default])};
},{"./src/types/undefined.js":"YkwH","./src/types/null.js":"R81P","./src/types/boolean.js":"oCiB","./src/types/number.js":"FZBu","./src/types/string.js":"R1Wc","./src/types/function.js":"b66e","./src/types/Array.js":"T6Us","./src/types/Object.js":"TIJW","./src/OptionsManager.js":"UG7E"}],"ucH8":[function(require,module,exports) {
module.exports={name:"algoliasearch.zendesk-hc",version:"3.0.0-alpha.2",description:"Algolia Search for Zendesk's Help Center",author:"Algolia <support@algolia.com>",keywords:["algolia","search","zendesk","help center"],homepage:"https://github.com/algolia/algoliasearch-zendesk",bugs:"https://github.com/algolia/algoliasearch-zendesk/issues",license:"MIT",repository:{type:"git",url:"https://github.com/algolia/algoliasearch-zendesk.git"},files:["dist/"],main:"dist/algoliasearch.zendesk-hc.js",dependencies:{"@algolia/autocomplete-js":"1.0.0-alpha.43","@algolia/autocomplete-plugin-algolia-insights":"1.0.0-alpha.43","@algolia/autocomplete-plugin-recent-searches":"1.0.0-alpha.43","@algolia/autocomplete-preset-algolia":"1.0.0-alpha.43","@algolia/autocomplete-theme-classic":"1.0.0-alpha.43","@algolia/client-search":"4.8.3",algoliasearch:"4.8.3",fargs:"^1.1.1","js-cookie":"^2.2.1",lodash:"^4.17.21",preact:"^10.5.12","search-insights":"1.6.3","to-factory":"^1.0.0"},devDependencies:{"babel-core":"^6.26.3","babel-eslint":"^10.1.0","babel-plugin-transform-object-rest-spread":"^6.26.0","babel-preset-es2015":"^6.24.1",eslint:"^7.20.0","eslint-config-algolia":"15.0.0","eslint-config-prettier":"6.15.0","eslint-plugin-eslint-comments":"3.2.0","eslint-plugin-import":"2.22.1","eslint-plugin-prettier":"3.2.0","eslint-plugin-react":"7.21.5","parcel-bundler":"1.12.4",prettier:"^2.2.1"},scripts:{clean:"rm -rf dist/ node_modules/",build:"parcel build index.js --global algoliasearchZendeskHC -o algoliasearch.zendesk-hc.min.js",dev:"parcel index.html --global algoliasearchZendeskHC",format:"prettier --write .",lint:"eslint --ext .js src"}};
},{}],"BM46":[function(require,module,exports) {
var define;
var e;!function(t,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof e&&e.amd?e(r):(t=t||self).algoliasearch=r()}(this,function(){"use strict";function e(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function r(r){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?t(Object(o),!0).forEach(function(t){e(r,t,o[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(o)):t(Object(o)).forEach(function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(o,e))})}return r}function n(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e)){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{n||null==i.return||i.return()}finally{if(o)throw a}}return r}}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function o(e){return function(e){if(Array.isArray(e)){for(var t=0,r=new Array(e.length);t<e.length;t++)r[t]=e[t];return r}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}function a(e){var t,r="algoliasearch-client-js-".concat(e.key),o=function(){return void 0===t&&(t=e.localStorage||window.localStorage),t},a=function(){return JSON.parse(o().getItem(r)||"{}")};return{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return Promise.resolve().then(function(){var r=JSON.stringify(e),n=a()[r];return Promise.all([n||t(),void 0!==n])}).then(function(e){var t=n(e,2),o=t[0],a=t[1];return Promise.all([o,a||r.miss(o)])}).then(function(e){return n(e,1)[0]})},set:function(e,t){return Promise.resolve().then(function(){var n=a();return n[JSON.stringify(e)]=t,o().setItem(r,JSON.stringify(n)),t})},delete:function(e){return Promise.resolve().then(function(){var t=a();delete t[JSON.stringify(e)],o().setItem(r,JSON.stringify(t))})},clear:function(){return Promise.resolve().then(function(){o().removeItem(r)})}}}function u(e){var t=o(e.caches),r=t.shift();return void 0===r?{get:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return t().then(function(e){return Promise.all([e,r.miss(e)])}).then(function(e){return n(e,1)[0]})},set:function(e,t){return Promise.resolve(t)},delete:function(e){return Promise.resolve()},clear:function(){return Promise.resolve()}}:{get:function(e,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}};return r.get(e,n,o).catch(function(){return u({caches:t}).get(e,n,o)})},set:function(e,n){return r.set(e,n).catch(function(){return u({caches:t}).set(e,n)})},delete:function(e){return r.delete(e).catch(function(){return u({caches:t}).delete(e)})},clear:function(){return r.clear().catch(function(){return u({caches:t}).clear()})}}}function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{serializable:!0},t={};return{get:function(r,n){var o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{miss:function(){return Promise.resolve()}},a=JSON.stringify(r);if(a in t)return Promise.resolve(e.serializable?JSON.parse(t[a]):t[a]);var u=n(),i=o&&o.miss||function(){return Promise.resolve()};return u.then(function(e){return i(e)}).then(function(){return u})},set:function(r,n){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(n):n,Promise.resolve(n)},delete:function(e){return delete t[JSON.stringify(e)],Promise.resolve()},clear:function(){return t={},Promise.resolve()}}}function s(e){for(var t=e.length-1;t>0;t--){var r=Math.floor(Math.random()*(t+1)),n=e[t];e[t]=e[r],e[r]=n}return e}function c(e,t){return t?(Object.keys(t).forEach(function(r){e[r]=t[r](e)}),e):e}function l(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var o=0;return e.replace(/%s/g,function(){return encodeURIComponent(r[o++])})}var f={WithinQueryParameters:0,WithinHeaders:1};function h(e,t){var r=e||{},n=r.data||{};return Object.keys(r).forEach(function(e){-1===["timeout","headers","queryParameters","data","cacheable"].indexOf(e)&&(n[e]=r[e])}),{data:Object.entries(n).length>0?n:void 0,timeout:r.timeout||t,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var d={Read:1,Write:2,Any:3},m=1,p=2,v=3;function y(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:m;return r(r({},e),{},{status:t,lastUpdate:Date.now()})}function g(e){return"string"==typeof e?{protocol:"https",url:e,accept:d.Any}:{protocol:e.protocol||"https",url:e.url,accept:e.accept||d.Any}}var b="GET",O="POST";function P(e,t,n,a){var u=[],i=function(e,t){if(e.method!==b&&(void 0!==e.data||void 0!==t.data)){var n=Array.isArray(e.data)?e.data:r(r({},e.data),t.data);return JSON.stringify(n)}}(n,a),s=function(e,t){var n=r(r({},e.headers),t.headers),o={};return Object.keys(n).forEach(function(e){var t=n[e];o[e.toLowerCase()]=t}),o}(e,a),c=n.method,l=n.method!==b?{}:r(r({},n.data),a.data),f=r(r(r({"x-algolia-agent":e.userAgent.value},e.queryParameters),l),a.queryParameters),h=0,d=function t(r,o){var l=r.pop();if(void 0===l)throw{name:"RetryError",message:"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.",transporterStackTrace:S(u)};var d={data:i,headers:s,method:c,url:j(l,n.path,f),connectTimeout:o(h,e.timeouts.connect),responseTimeout:o(h,a.timeout)},m=function(e){var t={request:d,response:e,host:l,triesLeft:r.length};return u.push(t),t},g={onSucess:function(e){return function(e){try{return JSON.parse(e.content)}catch(t){throw function(e,t){return{name:"DeserializationError",message:e,response:t}}(t.message,e)}}(e)},onRetry:function(n){var a=m(n);return n.isTimedOut&&h++,Promise.all([e.logger.info("Retryable failure",T(a)),e.hostsCache.set(l,y(l,n.isTimedOut?v:p))]).then(function(){return t(r,o)})},onFail:function(e){throw m(e),function(e,t){var r=e.content,n=e.status,o=r;try{o=JSON.parse(r).message}catch(e){}return function(e,t,r){return{name:"ApiError",message:o,status:n,transporterStackTrace:r}}(0,0,t)}(e,S(u))}};return e.requester.send(d).then(function(e){return function(e,t){return function(e){var t=e.status;return e.isTimedOut||function(e){var t=e.isTimedOut,r=e.status;return!t&&0==~~r}(e)||2!=~~(t/100)&&4!=~~(t/100)}(e)?t.onRetry(e):2==~~(e.status/100)?t.onSucess(e):t.onFail(e)}(e,g)})};return function(e,t){return Promise.all(t.map(function(t){return e.get(t,function(){return Promise.resolve(y(t))})})).then(function(e){var r=e.filter(function(e){return function(e){return e.status===m||Date.now()-e.lastUpdate>12e4}(e)}),n=e.filter(function(e){return function(e){return e.status===v&&Date.now()-e.lastUpdate<=12e4}(e)}),a=[].concat(o(r),o(n));return{getTimeout:function(e,t){return(0===n.length&&0===e?1:n.length+3+e)*t},statelessHosts:a.length>0?a.map(function(e){return g(e)}):t}})}(e.hostsCache,t).then(function(e){return d(o(e.statelessHosts).reverse(),e.getTimeout)})}function q(e){var t={value:"Algolia for JavaScript (".concat(e,")"),add:function(e){var r="; ".concat(e.segment).concat(void 0!==e.version?" (".concat(e.version,")"):"");return-1===t.value.indexOf(r)&&(t.value="".concat(t.value).concat(r)),t}};return t}function j(e,t,r){var n=w(r),o="".concat(e.protocol,"://").concat(e.url,"/").concat("/"===t.charAt(0)?t.substr(1):t);return n.length&&(o+="?".concat(n)),o}function w(e){return Object.keys(e).map(function(t){return l("%s=%s",t,(r=e[t],"[object Object]"===Object.prototype.toString.call(r)||"[object Array]"===Object.prototype.toString.call(r)?JSON.stringify(e[t]):e[t]));var r}).join("&")}function S(e){return e.map(function(e){return T(e)})}function T(e){var t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return r(r({},e),{},{request:r(r({},e.request),{},{headers:r(r({},e.request.headers),t)})})}var A=function(e){var t=e.appId,o=function(e,t,r){var n={"x-algolia-api-key":r,"x-algolia-application-id":t};return{headers:function(){return e===f.WithinHeaders?n:{}},queryParameters:function(){return e===f.WithinQueryParameters?n:{}}}}(void 0!==e.authMode?e.authMode:f.WithinHeaders,t,e.apiKey),a=function(e){var t=e.hostsCache,r=e.logger,o=e.requester,a=e.requestsCache,u=e.responsesCache,i=e.timeouts,s=e.userAgent,c=e.hosts,l=e.queryParameters,f={hostsCache:t,logger:r,requester:o,requestsCache:a,responsesCache:u,timeouts:i,userAgent:s,headers:e.headers,queryParameters:l,hosts:c.map(function(e){return g(e)}),read:function(e,t){var r=h(t,f.timeouts.read),o=function(){return P(f,f.hosts.filter(function(e){return 0!=(e.accept&d.Read)}),e,r)};if(!0!==(void 0!==r.cacheable?r.cacheable:e.cacheable))return o();var a={request:e,mappedRequestOptions:r,transporter:{queryParameters:f.queryParameters,headers:f.headers}};return f.responsesCache.get(a,function(){return f.requestsCache.get(a,function(){return f.requestsCache.set(a,o()).then(function(e){return Promise.all([f.requestsCache.delete(a),e])},function(e){return Promise.all([f.requestsCache.delete(a),Promise.reject(e)])}).then(function(e){var t=n(e,2);return t[0],t[1]})})},{miss:function(e){return f.responsesCache.set(a,e)}})},write:function(e,t){return P(f,f.hosts.filter(function(e){return 0!=(e.accept&d.Write)}),e,h(t,f.timeouts.write))}};return f}(r(r({hosts:[{url:"".concat(t,"-dsn.algolia.net"),accept:d.Read},{url:"".concat(t,".algolia.net"),accept:d.Write}].concat(s([{url:"".concat(t,"-1.algolianet.com")},{url:"".concat(t,"-2.algolianet.com")},{url:"".concat(t,"-3.algolianet.com")}]))},e),{},{headers:r(r(r({},o.headers()),{"content-type":"application/x-www-form-urlencoded"}),e.headers),queryParameters:r(r({},o.queryParameters()),e.queryParameters)}));return c({transporter:a,appId:t,addAlgoliaAgent:function(e,t){a.userAgent.add({segment:e,version:t})},clearCache:function(){return Promise.all([a.requestsCache.clear(),a.responsesCache.clear()]).then(function(){})}},e.methods)},x=function(e){return function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return c({transporter:e.transporter,appId:e.appId,indexName:t},r.methods)}},N=function(e){return function(t,n){var o=t.map(function(e){return r(r({},e),{},{params:w(e.params||{})})});return e.transporter.read({method:O,path:"1/indexes/*/queries",data:{requests:o},cacheable:!0},n)}},C=function(e){return function(t,n){return Promise.all(t.map(function(t){var o=t.params,a=o.facetName,u=o.facetQuery,i=function(e,t){if(null==e)return{};var r,n,o=function(e,t){if(null==e)return{};var r,n,o={},a=Object.keys(e);for(n=0;n<a.length;n++)r=a[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(n=0;n<a.length;n++)r=a[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}(o,["facetName","facetQuery"]);return x(e)(t.indexName,{methods:{searchForFacetValues:E}}).searchForFacetValues(a,u,r(r({},n),i))}))}},k=function(e){return function(t,r,n){return e.transporter.read({method:O,path:l("1/answers/%s/prediction",e.indexName),data:{query:t,queryLanguages:r},cacheable:!0},n)}},J=function(e){return function(t,r){return e.transporter.read({method:O,path:l("1/indexes/%s/query",e.indexName),data:{query:t},cacheable:!0},r)}},E=function(e){return function(t,r,n){return e.transporter.read({method:O,path:l("1/indexes/%s/facets/%s/query",e.indexName,t),data:{facetQuery:r},cacheable:!0},n)}},I=1,F=2,R=3;function D(e,t,n){var o,s={appId:e,apiKey:t,timeouts:{connect:1,read:2,write:30},requester:{send:function(e){return new Promise(function(t){var r=new XMLHttpRequest;r.open(e.method,e.url,!0),Object.keys(e.headers).forEach(function(t){return r.setRequestHeader(t,e.headers[t])});var n,o=function(e,n){return setTimeout(function(){r.abort(),t({status:0,content:n,isTimedOut:!0})},1e3*e)},a=o(e.connectTimeout,"Connection timeout");r.onreadystatechange=function(){r.readyState>r.OPENED&&void 0===n&&(clearTimeout(a),n=o(e.responseTimeout,"Socket timeout"))},r.onerror=function(){0===r.status&&(clearTimeout(a),clearTimeout(n),t({content:r.responseText||"Network request failed",status:r.status,isTimedOut:!1}))},r.onload=function(){clearTimeout(a),clearTimeout(n),t({content:r.responseText,status:r.status,isTimedOut:!1})},r.send(e.data)})}},logger:(o=R,{debug:function(e,t){return I>=o&&console.debug(e,t),Promise.resolve()},info:function(e,t){return F>=o&&console.info(e,t),Promise.resolve()},error:function(e,t){return console.error(e,t),Promise.resolve()}}),responsesCache:i(),requestsCache:i({serializable:!1}),hostsCache:u({caches:[a({key:"".concat("4.8.3","-").concat(e)}),i()]}),userAgent:q("4.8.3").add({segment:"Browser",version:"lite"}),authMode:f.WithinQueryParameters};return A(r(r(r({},s),n),{},{methods:{search:N,searchForFacetValues:C,multipleQueries:N,multipleSearchForFacetValues:C,initIndex:function(e){return function(t){return x(e)(t,{methods:{search:J,searchForFacetValues:E,findAnswers:k}})}}}}))}return D.version="4.8.3",D});
},{}],"kOTw":[function(require,module,exports) {
"use strict";function e(e){return{current:e}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createRef=e;
},{}],"X7Bg":[function(require,module,exports) {
"use strict";function e(e,r){var t=void 0;return function(){for(var o=arguments.length,n=new Array(o),u=0;u<o;u++)n[u]=arguments[u];t&&clearTimeout(t),t=setTimeout(function(){return e.apply(void 0,n)},r)}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.debounce=e;
},{}],"uq8s":[function(require,module,exports) {
"use strict";function e(e){return 0===e.collections.length?0:e.collections.reduce(function(e,t){return e+t.items.length},0)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getItemsCount=e;
},{}],"zLfE":[function(require,module,exports) {
"use strict";function e(e,t){}Object.defineProperty(exports,"__esModule",{value:!0}),exports.invariant=e;
},{}],"Zi4t":[function(require,module,exports) {
"use strict";function e(e){return e!==Object(e)}function t(r,n){if(r===n)return!0;if(e(r)||e(n)||"function"==typeof r||"function"==typeof n)return r===n;if(Object.keys(r).length!==Object.keys(n).length)return!1;for(var u=0,f=Object.keys(r);u<f.length;u++){var i=f[u];if(!(i in n))return!1;if(!t(r[i],n[i]))return!1}return!0}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isEqual=t;
},{}],"DMuU":[function(require,module,exports) {
},{}],"buRw":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.warn=r,exports.warnCache=void 0;var e={current:{}};function r(e,r){}exports.warnCache=e;
},{}],"uvJf":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./createRef");Object.keys(e).forEach(function(r){"default"!==r&&"__esModule"!==r&&(r in exports&&exports[r]===e[r]||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}}))});var r=require("./debounce");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var t=require("./getItemsCount");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var n=require("./invariant");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===n[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return n[e]}}))});var o=require("./isEqual");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});var u=require("./MaybePromise");Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===u[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return u[e]}}))});var s=require("./warn");Object.keys(s).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===s[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return s[e]}}))});
},{"./createRef":"kOTw","./debounce":"X7Bg","./getItemsCount":"uq8s","./invariant":"zLfE","./isEqual":"Zi4t","./MaybePromise":"DMuU","./warn":"buRw"}],"yw18":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.checkOptions=t;var e=require("@algolia/autocomplete-shared");function t(e){}
},{"@algolia/autocomplete-shared":"uvJf"}],"FMkh":[function(require,module,exports) {
"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?e(Object(o),!0).forEach(function(e){r(t,e,o[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):e(Object(o)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))})}return t}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,r,n){var o=r.initialState;return{getState:function(){return o},dispatch:function(c,i){var p=t({},o);o=e(o,{type:c,props:r,payload:i}),n({state:o,prevState:p})}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=n;
},{}],"Medz":[function(require,module,exports) {
"use strict";function e(){var e=-1,r=-1,t=void 0;return function(n){var o=++e;return Promise.resolve(n).then(function(e){return t&&o<r?t:(r=o,t=e,e)})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createConcurrentSafePromise=e;
},{}],"NKHT":[function(require,module,exports) {
"use strict";function e(e){return e.reduce(function(e,t){return e.concat(t)},[])}Object.defineProperty(exports,"__esModule",{value:!0}),exports.flatten=e;
},{}],"ix4A":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.generateAutocompleteId=t;var e=0;function t(){return"autocomplete-".concat(e++)}
},{}],"Y6HM":[function(require,module,exports) {
"use strict";function e(e,t,l,u){if(e<0&&(null===t||null!==u&&0===t))return l+e;var n=(null===t?-1:t)+e;return n<=-1||n>=l?null===u?null:0:n}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getNextActiveItemId=e;
},{}],"y8Nb":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.noop=void 0;var e=function(){};exports.noop=e;
},{}],"DfJx":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getNormalizedSources=i;var e=require("@algolia/autocomplete-shared"),t=require("./noop");function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function n(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}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}function u(e){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function i(r,o){return Promise.resolve(r(o)).then(function(r){return(0,e.invariant)(Array.isArray(r),"The `getSources` function must return an array of sources but returned type ".concat(JSON.stringify(u(r)),":\n\n").concat(JSON.stringify(r,null,2))),Promise.all(r.filter(function(e){return Boolean(e)}).map(function(r){(0,e.invariant)("string"==typeof r.sourceId,"A source must provide a `sourceId` string.");var o=n({getItemInputValue:function(e){return e.state.query},getItemUrl:function(){},onSelect:function(e){(0,e.setIsOpen)(!1)},onActive:t.noop},r);return Promise.resolve(o)}))})}
},{"@algolia/autocomplete-shared":"uvJf","./noop":"y8Nb"}],"bHsM":[function(require,module,exports) {
"use strict";function e(e){var t=e.collections.map(function(e){return e.items.length}).reduce(function(e,t,r){var n=(e[r-1]||0)+t;return e.push(n),e},[]).reduce(function(t,r){return r<=e.activeItemId?t+1:t},0);return e.collections[t]}function t(e){for(var t=e.state,r=e.collection,n=!1,i=0,u=0;!1===n;){var c=t.collections[i];if(c===r){n=!0;break}u+=c.items.length,i++}return t.activeItemId-u}function r(r){var n=e(r);if(!n)return null;var i=n.items[t({state:r,collection:n})],u=n.source;return{item:i,itemInputValue:u.getItemInputValue({item:i,state:r}),itemUrl:u.getItemUrl({item:i,state:r}),source:u}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getActiveItem=r;
},{}],"p4Ur":[function(require,module,exports) {
"use strict";function e(e,t){return e===t||e.contains(t)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.isOrContainsNode=e;
},{}],"JDJs":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./createConcurrentSafePromise");Object.keys(e).forEach(function(t){"default"!==t&&"__esModule"!==t&&(t in exports&&exports[t]===e[t]||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}}))});var t=require("./flatten");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var r=require("./generateAutocompleteId");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var o=require("./getNextActiveItemId");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});var n=require("./getNormalizedSources");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===n[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return n[e]}}))});var u=require("./getActiveItem");Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===u[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return u[e]}}))});var c=require("./isOrContainsNode");Object.keys(c).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===c[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return c[e]}}))});var i=require("./noop");Object.keys(i).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===i[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return i[e]}}))});
},{"./createConcurrentSafePromise":"Medz","./flatten":"NKHT","./generateAutocompleteId":"ix4A","./getNextActiveItemId":"Y6HM","./getNormalizedSources":"DfJx","./getActiveItem":"bHsM","./isOrContainsNode":"p4Ur","./noop":"y8Nb"}],"hiJN":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAutocompleteSetters=o;var t=require("./utils");function e(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable})),r.push.apply(r,n)}return r}function r(t){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?e(Object(o),!0).forEach(function(e){n(t,e,o[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):e(Object(o)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))})}return t}function n(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function o(e){var n=e.store;return{setActiveItemId:function(t){n.dispatch("setActiveItemId",t)},setQuery:function(t){n.dispatch("setQuery",t)},setCollections:function(e){var o=0,c=e.map(function(e){return r(r({},e),{},{items:(0,t.flatten)(e.items).map(function(t){return r(r({},t),{},{__autocomplete_id:o++})})})});n.dispatch("setCollections",c)},setIsOpen:function(t){n.dispatch("setIsOpen",t)},setStatus:function(t){n.dispatch("setStatus",t)},setContext:function(t){n.dispatch("setContext",t)}}}
},{"./utils":"JDJs"}],"sYLM":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getDefaultProps=s;var e=require("@algolia/autocomplete-shared"),t=require("./utils");function n(e){return a(e)||i(e)||o(e)||r()}function r(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function o(e,t){if(e){if("string"==typeof e)return u(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)?u(e,t):void 0}}function i(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}function a(e){if(Array.isArray(e))return u(e)}function u(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 l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?l(Object(n),!0).forEach(function(t){f(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function f(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function s(r,o){var i,a="undefined"!=typeof window?window:{},u=r.plugins||[];return c(c({debug:!1,openOnFocus:!1,placeholder:"",autoFocus:!1,defaultActiveItemId:null,stallThreshold:300,environment:a,shouldPanelOpen:function(t){var n=t.state;return(0,e.getItemsCount)(n)>0}},r),{},{id:null!==(i=r.id)&&void 0!==i?i:(0,t.generateAutocompleteId)(),plugins:u,initialState:c({activeItemId:null,query:"",completion:null,collections:[],isOpen:!1,status:"idle",context:{}},r.initialState),onStateChange:function(e){var t;null===(t=r.onStateChange)||void 0===t||t.call(r,e),u.forEach(function(t){var n;return null===(n=t.onStateChange)||void 0===n?void 0:n.call(t,e)})},onSubmit:function(e){var t;null===(t=r.onSubmit)||void 0===t||t.call(r,e),u.forEach(function(t){var n;return null===(n=t.onSubmit)||void 0===n?void 0:n.call(t,e)})},onReset:function(e){var t;null===(t=r.onReset)||void 0===t||t.call(r,e),u.forEach(function(t){var n;return null===(n=t.onReset)||void 0===n?void 0:n.call(t,e)})},getSources:function(e){return Promise.all([].concat(n(u.map(function(e){return e.getSources})),[r.getSources]).filter(Boolean).map(function(n){return(0,t.getNormalizedSources)(n,e)})).then(function(e){return(0,t.flatten)(e)}).then(function(e){return e.map(function(e){return c(c({},e),{},{onSelect:function(t){e.onSelect(t),o.forEach(function(e){var n;return null===(n=e.onSelect)||void 0===n?void 0:n.call(e,t)})},onActive:function(t){e.onActive(t),o.forEach(function(e){var n;return null===(n=e.onActive)||void 0===n?void 0:n.call(e,t)})}})})})},navigator:c({navigate:function(e){var t=e.itemUrl;a.location.assign(t)},navigateNewTab:function(e){var t=e.itemUrl,n=a.open(t,"_blank","noopener");null==n||n.focus()},navigateNewWindow:function(e){var t=e.itemUrl;a.open(t,"_blank","noopener")}},r.navigator)})}
},{"@algolia/autocomplete-shared":"uvJf","./utils":"JDJs"}],"kj0K":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.onInput=a;var e=require("@algolia/autocomplete-shared"),t=require("./utils");function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){if(null==e)return{};var r,n,o=l(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function l(e,t){if(null==e)return{};var r,n,o={},i=Object.keys(e);for(n=0;n<i.length;n++)r=i[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}var s=null;function a(n){var i=n.event,l=n.nextState,a=void 0===l?{}:l,c=n.props,f=n.query,p=n.refresh,y=n.store,m=u(n,["event","nextState","props","query","refresh","store"]);s&&c.environment.clearTimeout(s);var O,b=m.setCollections,v=m.setIsOpen,g=m.setQuery,d=m.setActiveItemId,S=m.setStatus;return g(f),d(c.defaultActiveItemId),f||!1!==c.openOnFocus?(S("loading"),s=c.environment.setTimeout(function(){S("stalled")},c.stallThreshold),c.getSources(o({query:f,refresh:p,state:y.getState()},m)).then(function(n){return S("loading"),Promise.all(n.map(function(t){return Promise.resolve(t.getItems(o({query:f,refresh:p,state:y.getState()},m))).then(function(n){return(0,e.invariant)(Array.isArray(n),"The `getItems` function must return an array of items but returned type ".concat(JSON.stringify(r(n)),":\n\n").concat(JSON.stringify(n,null,2))),{source:t,items:n}})})).then(function(e){var r;S("idle"),b(e);var n=c.shouldPanelOpen({state:y.getState()});v(null!==(r=a.isOpen)&&void 0!==r?r:c.openOnFocus&&!f&&n||n);var u=(0,t.getActiveItem)(y.getState());if(null!==y.getState().activeItemId&&u){var l=u.item,s=u.itemInputValue,O=u.itemUrl,g=u.source;g.onActive(o({event:i,item:l,itemInputValue:s,itemUrl:O,refresh:p,source:g,state:y.getState()},m))}}).finally(function(){s&&c.environment.clearTimeout(s)})})):(S("idle"),b(y.getState().collections.map(function(e){return o(o({},e),{},{items:[]})})),v(null!==(O=a.isOpen)&&void 0!==O?O:c.shouldPanelOpen({state:y.getState()})),Promise.resolve())}
},{"@algolia/autocomplete-shared":"uvJf","./utils":"JDJs"}],"dqIq":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.onKeyDown=l;var e=require("./onInput"),t=require("./utils");function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function n(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach(function(t){i(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(null==e)return{};var r,n,i=a(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(i[r]=e[r])}return i}function a(e,t){if(null==e)return{};var r,n,i={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(i[r]=e[r]);return i}function l(r){var i=r.event,a=r.props,l=r.refresh,u=r.store,c=o(r,["event","props","refresh","store"]);if("ArrowUp"===i.key||"ArrowDown"===i.key){i.preventDefault(),u.dispatch(i.key,null);var s=a.environment.document.getElementById("".concat(a.id,"-item-").concat(u.getState().activeItemId));s&&(s.scrollIntoViewIfNeeded?s.scrollIntoViewIfNeeded(!1):s.scrollIntoView(!1));var f=(0,t.getActiveItem)(u.getState());if(null!==u.getState().activeItemId&&f){var p=f.item,m=f.itemInputValue,v=f.itemUrl,g=f.source;g.onActive(n({event:i,item:p,itemInputValue:m,itemUrl:v,refresh:l,source:g,state:u.getState()},c))}}else if("Escape"===i.key)i.preventDefault(),u.dispatch(i.key,null);else if("Enter"===i.key){if(null===u.getState().activeItemId||u.getState().collections.every(function(e){return 0===e.items.length}))return;i.preventDefault();var y=(0,t.getActiveItem)(u.getState()),O=y.item,b=y.itemInputValue,d=y.itemUrl,I=y.source;if(i.metaKey||i.ctrlKey)void 0!==d&&(I.onSelect(n({event:i,item:O,itemInputValue:b,itemUrl:d,refresh:l,source:I,state:u.getState()},c)),a.navigator.navigateNewTab({itemUrl:d,item:O,state:u.getState()}));else if(i.shiftKey)void 0!==d&&(I.onSelect(n({event:i,item:O,itemInputValue:b,itemUrl:d,refresh:l,source:I,state:u.getState()},c)),a.navigator.navigateNewWindow({itemUrl:d,item:O,state:u.getState()}));else if(i.altKey);else{if(void 0!==d)return I.onSelect(n({event:i,item:O,itemInputValue:b,itemUrl:d,refresh:l,source:I,state:u.getState()},c)),void a.navigator.navigate({itemUrl:d,item:O,state:u.getState()});(0,e.onInput)(n({event:i,nextState:{isOpen:!1},props:a,query:b,refresh:l,store:u},c)).then(function(){I.onSelect(n({event:i,item:O,itemInputValue:b,itemUrl:d,refresh:l,source:I,state:u.getState()},c))})}}}
},{"./onInput":"kj0K","./utils":"JDJs"}],"DQqz":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPropGetters=c;var e=require("./onInput"),t=require("./onKeyDown"),n=require("./utils");function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,o)}return n}function r(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o(Object(n),!0).forEach(function(t){i(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function i(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function a(e,t){if(null==e)return{};var n,o,r=u(e,t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function u(e,t){if(null==e)return{};var n,o,r={},i=Object.keys(e);for(o=0;o<i.length;o++)n=i[o],t.indexOf(n)>=0||(r[n]=e[n]);return r}function c(o){var i=o.props,u=o.refresh,c=o.store,l=a(o,["props","refresh","store"]);return{getEnvironmentProps:function(e){var t=e.inputElement,o=e.formElement,u=e.panelElement;return r({onTouchStart:function(e){!1!==c.getState().isOpen&&e.target!==t&&!1===[o,u].some(function(t){return(0,n.isOrContainsNode)(t,e.target)||(0,n.isOrContainsNode)(t,i.environment.document.activeElement)})&&c.dispatch("blur",null)},onTouchMove:function(e){!1!==c.getState().isOpen&&t===i.environment.document.activeElement&&e.target!==t&&t.blur()}},a(e,["inputElement","formElement","panelElement"]))},getRootProps:function(e){return r({role:"combobox","aria-expanded":c.getState().isOpen,"aria-haspopup":"listbox","aria-owns":c.getState().isOpen?"".concat(i.id,"-list"):void 0,"aria-labelledby":"".concat(i.id,"-label")},e)},getFormProps:function(e){e.inputElement;return r({action:"",noValidate:!0,role:"search",onSubmit:function(t){var n;t.preventDefault(),i.onSubmit(r({event:t,refresh:u,state:c.getState()},l)),c.dispatch("submit",null),null===(n=e.inputElement)||void 0===n||n.blur()},onReset:function(t){var n;t.preventDefault(),i.onReset(r({event:t,refresh:u,state:c.getState()},l)),c.dispatch("reset",null),null===(n=e.inputElement)||void 0===n||n.focus()}},a(e,["inputElement"]))},getLabelProps:function(e){return r({htmlFor:"".concat(i.id,"-input"),id:"".concat(i.id,"-label")},e)},getInputProps:function(o){function s(t){(i.openOnFocus||Boolean(c.getState().query))&&(0,e.onInput)(r({event:t,props:i,query:c.getState().completion||c.getState().query,refresh:u,store:c},l)),c.dispatch("focus",null)}var p="ontouchstart"in i.environment,m=o||{},f=(m.inputElement,m.maxLength),v=void 0===f?512:f,d=a(m,["inputElement","maxLength"]),g=(0,n.getActiveItem)(c.getState());return r({"aria-autocomplete":"both","aria-activedescendant":c.getState().isOpen&&null!==c.getState().activeItemId?"".concat(i.id,"-item-").concat(c.getState().activeItemId):void 0,"aria-controls":c.getState().isOpen?"".concat(i.id,"-list"):void 0,"aria-labelledby":"".concat(i.id,"-label"),value:c.getState().completion||c.getState().query,id:"".concat(i.id,"-input"),autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",enterKeyHint:null!=g&&g.itemUrl?"go":"search",spellCheck:"false",autoFocus:i.autoFocus,placeholder:i.placeholder,maxLength:v,type:"search",onChange:function(t){(0,e.onInput)(r({event:t,props:i,query:t.currentTarget.value.slice(0,v),refresh:u,store:c},l))},onKeyDown:function(e){(0,t.onKeyDown)(r({event:e,props:i,refresh:u,store:c},l))},onFocus:s,onBlur:function(){p||c.dispatch("blur",null)},onClick:function(e){o.inputElement!==i.environment.document.activeElement||c.getState().isOpen||s(e)}},d)},getPanelProps:function(e){return r({onMouseDown:function(e){e.preventDefault()},onMouseLeave:function(){c.dispatch("mouseleave",null)}},e)},getListProps:function(e){return r({role:"listbox","aria-labelledby":"".concat(i.id,"-label"),id:"".concat(i.id,"-list")},e)},getItemProps:function(t){var o=t.item,s=t.source,p=a(t,["item","source"]);return r({id:"".concat(i.id,"-item-").concat(o.__autocomplete_id),role:"option","aria-selected":c.getState().activeItemId===o.__autocomplete_id,onMouseMove:function(e){if(o.__autocomplete_id!==c.getState().activeItemId){c.dispatch("mousemove",o.__autocomplete_id);var t=(0,n.getActiveItem)(c.getState());if(null!==c.getState().activeItemId&&t){var i=t.item,a=t.itemInputValue,s=t.itemUrl,p=t.source;p.onActive(r({event:e,item:i,itemInputValue:a,itemUrl:s,refresh:u,source:p,state:c.getState()},l))}}},onMouseDown:function(e){e.preventDefault()},onClick:function(t){var n=s.getItemInputValue({item:o,state:c.getState()}),a=s.getItemUrl({item:o,state:c.getState()});(a?Promise.resolve():(0,e.onInput)(r({event:t,nextState:{isOpen:!1},props:i,query:n,refresh:u,store:c},l))).then(function(){s.onSelect(r({event:t,item:o,itemInputValue:n,itemUrl:a,refresh:u,source:s,state:c.getState()},l))})}},p)}}}
},{"./onInput":"kj0K","./onKeyDown":"dqIq","./utils":"JDJs"}],"FPLW":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getCompletion=t;var e=require("./utils");function t(t){var u=t.state;return!1===u.isOpen||null===u.activeItemId?null:(0,e.getActiveItem)(u).itemInputValue||null}
},{"./utils":"JDJs"}],"zS8l":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.stateReducer=void 0;var e=require("@algolia/autocomplete-shared"),t=require("./getCompletion"),r=require("./utils");function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,o)}return r}function n(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?o(Object(r),!0).forEach(function(t){c(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function c(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var s=function(o,c){switch(c.type){case"setActiveItemId":return n(n({},o),{},{activeItemId:c.payload});case"setQuery":return n(n({},o),{},{query:c.payload,completion:null});case"setCollections":return n(n({},o),{},{collections:c.payload});case"setIsOpen":return n(n({},o),{},{isOpen:c.payload});case"setStatus":return n(n({},o),{},{status:c.payload});case"setContext":return n(n({},o),{},{context:n(n({},o.context),c.payload)});case"ArrowDown":var s=n(n({},o),{},{activeItemId:(0,r.getNextActiveItemId)(1,o.activeItemId,(0,e.getItemsCount)(o),c.props.defaultActiveItemId)});return n(n({},s),{},{completion:(0,t.getCompletion)({state:s})});case"ArrowUp":var a=n(n({},o),{},{activeItemId:(0,r.getNextActiveItemId)(-1,o.activeItemId,(0,e.getItemsCount)(o),c.props.defaultActiveItemId)});return n(n({},a),{},{completion:(0,t.getCompletion)({state:a})});case"Escape":return o.isOpen?n(n({},o),{},{isOpen:!1,completion:null}):n(n({},o),{},{query:"",status:"idle",collections:[]});case"submit":return n(n({},o),{},{activeItemId:null,isOpen:!1,status:"idle"});case"reset":return n(n({},o),{},{activeItemId:!0===c.props.openOnFocus?c.props.defaultActiveItemId:null,status:"idle",query:""});case"focus":return n(n({},o),{},{activeItemId:c.props.defaultActiveItemId,isOpen:c.props.openOnFocus||Boolean(o.query)});case"blur":return c.props.debug?o:n(n({},o),{},{isOpen:!1,activeItemId:null});case"mousemove":return n(n({},o),{},{activeItemId:c.payload});case"mouseleave":return n(n({},o),{},{activeItemId:c.props.defaultActiveItemId});default:return(0,e.invariant)(!1,"The reducer action ".concat(JSON.stringify(c.type)," is not supported.")),o}};exports.stateReducer=s;
},{"@algolia/autocomplete-shared":"uvJf","./getCompletion":"FPLW","./utils":"JDJs"}],"bkJG":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createAutocomplete=a;var e=require("./checkOptions"),t=require("./createStore"),r=require("./getAutocompleteSetters"),n=require("./getDefaultProps"),o=require("./getPropGetters"),c=require("./onInput"),u=require("./stateReducer");function i(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function s(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?i(Object(r),!0).forEach(function(t){p(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):i(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function p(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(i){(0,e.checkOptions)(i);var p=[],a=(0,n.getDefaultProps)(i,p),f=(0,t.createStore)(u.stateReducer,a,function(e){var t=e.prevState,r=e.state;a.onStateChange(s({prevState:t,state:r,refresh:b},l))}),l=(0,r.getAutocompleteSetters)({store:f}),O=(0,o.getPropGetters)(s({props:a,refresh:b,store:f},l));function b(){return(0,c.onInput)(s({event:new Event("input"),nextState:{isOpen:f.getState().isOpen},props:a,query:f.getState().query,refresh:b,store:f},l))}return a.plugins.forEach(function(e){var t;return null===(t=e.subscribe)||void 0===t?void 0:t.call(e,s(s({},l),{},{refresh:b,onSelect:function(e){p.push({onSelect:e})},onActive:function(e){p.push({onActive:e})}}))}),s(s({refresh:b},O),l)}
},{"./checkOptions":"yw18","./createStore":"FMkh","./getAutocompleteSetters":"hiJN","./getDefaultProps":"sYLM","./getPropGetters":"DQqz","./onInput":"kj0K","./stateReducer":"zS8l"}],"fwJC":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./AutocompleteApi");Object.keys(e).forEach(function(t){"default"!==t&&"__esModule"!==t&&(t in exports&&exports[t]===e[t]||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}}))});var t=require("./AutocompleteCollection");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var r=require("./AutocompleteContext");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var o=require("./AutocompleteEnvironment");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});var n=require("./AutocompleteOptions");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===n[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return n[e]}}))});var u=require("./AutocompleteSource");Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===u[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return u[e]}}))});var c=require("./AutocompletePropGetters");Object.keys(c).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===c[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return c[e]}}))});var s=require("./AutocompletePlugin");Object.keys(s).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===s[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return s[e]}}))});var i=require("./AutocompleteSetters");Object.keys(i).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===i[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return i[e]}}))});var p=require("./AutocompleteState");Object.keys(p).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===p[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return p[e]}}))});var f=require("./AutocompleteStore");Object.keys(f).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===f[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return f[e]}}))});var l=require("./AutocompleteSubscribers");Object.keys(l).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===l[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return l[e]}}))});
},{"./AutocompleteApi":"DMuU","./AutocompleteCollection":"DMuU","./AutocompleteContext":"DMuU","./AutocompleteEnvironment":"DMuU","./AutocompleteOptions":"DMuU","./AutocompleteSource":"DMuU","./AutocompletePropGetters":"DMuU","./AutocompletePlugin":"DMuU","./AutocompleteSetters":"DMuU","./AutocompleteState":"DMuU","./AutocompleteStore":"DMuU","./AutocompleteSubscribers":"DMuU"}],"Q8BT":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.version=void 0;var e="1.0.0-alpha.43";exports.version=e;
},{}],"mUNi":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./createAutocomplete");Object.keys(e).forEach(function(r){"default"!==r&&"__esModule"!==r&&(r in exports&&exports[r]===e[r]||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}}))});var r=require("./getDefaultProps");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var t=require("./types");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var o=require("./version");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});
},{"./createAutocomplete":"bkJG","./getDefaultProps":"sYLM","./types":"fwJC","./version":"Q8BT"}],"czrS":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getHTMLElement=t;var e=require("@algolia/autocomplete-shared");function t(t){if("string"==typeof t){var r=document.querySelector(t);return(0,e.invariant)(null!==r,"The element ".concat(JSON.stringify(t)," is not in the document.")),r}return t}
},{"@algolia/autocomplete-shared":"uvJf"}],"YBKx":[function(require,module,exports) {
"use strict";function e(){for(var e=arguments.length,r=new Array(e),t=0;t<e;t++)r[t]=arguments[t];return r.reduce(function(e,r){return Object.keys(r).forEach(function(t){var n=e[t],o=r[t];n!==o&&(e[t]=[n,o].filter(Boolean).join(" "))}),e},{})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeClassNames=e;
},{}],"SOLq":[function(require,module,exports) {
"use strict";function r(r){return o(r)||n(r)||e(r)||t()}function t(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function e(r,t){if(r){if("string"==typeof r)return i(r,t);var e=Object.prototype.toString.call(r).slice(8,-1);return"Object"===e&&r.constructor&&(e=r.constructor.name),"Map"===e||"Set"===e?Array.from(r):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?i(r,t):void 0}}function n(r){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(r))return Array.from(r)}function o(r){if(Array.isArray(r))return i(r)}function i(r,t){(null==t||t>r.length)&&(t=r.length);for(var e=0,n=new Array(t);e<t;e++)n[e]=r[e];return n}function u(r){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(r){return typeof r}:function(r){return r&&"function"==typeof Symbol&&r.constructor===Symbol&&r!==Symbol.prototype?"symbol":typeof r})(r)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.mergeDeep=c;var a=function(r){return r&&"object"===u(r)};function c(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return e.reduce(function(t,e){return Object.keys(e).forEach(function(n){var o=t[n],i=e[n];Array.isArray(o)&&Array.isArray(i)?t[n]=o.concat.apply(o,r(i)):a(o)&&a(i)?t[n]=c(o,i):t[n]=i}),t},{})}
},{}],"zASX":[function(require,module,exports) {
"use strict";function e(e,t,n){e[t]=null===n?"":"number"!=typeof n?n:n+"px"}function t(e){this._listeners[e.type](e)}function n(n,r,s){var o,i,l=n[r];if("style"===r)if("string"==typeof s)n.style=s;else if(null===s)n.style="";else for(r in s)l&&s[r]===l[r]||e(n.style,r,s[r]);else"o"===r[0]&&"n"===r[1]?(o=r!==(r=r.replace(/Capture$/,"")),(i=r.toLowerCase())in n&&(r=i),r=r.slice(2),n._listeners||(n._listeners={}),n._listeners[r]=s,s?l||n.addEventListener(r,t,o):n.removeEventListener(r,t,o)):"list"!==r&&"tagName"!==r&&"form"!==r&&"type"!==r&&"size"!==r&&"download"!==r&&"href"!==r&&r in n?n[r]=null==s?"":s:"function"!=typeof s&&"dangerouslySetInnerHTML"!==r&&(null==s||!1===s&&!/^ar/.test(r)?n.removeAttribute(r):n.setAttribute(r,s))}function r(e){switch(e){case"onChange":return"onInput";default:return e}}function s(e,t){for(var s in t)n(e,r(s),t[s])}function o(e,t){for(var s in t)"o"===s[0]&&"n"===s[1]||n(e,r(s),t[s])}Object.defineProperty(exports,"__esModule",{value:!0}),exports.setProperty=n,exports.setProperties=s,exports.setPropertiesWithoutEvents=o;
},{}],"TdV8":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./getHTMLElement");Object.keys(e).forEach(function(r){"default"!==r&&"__esModule"!==r&&(r in exports&&exports[r]===e[r]||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}}))});var r=require("./mergeClassNames");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var t=require("./mergeDeep");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var o=require("./setProperties");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});
},{"./getHTMLElement":"czrS","./mergeClassNames":"YBKx","./mergeDeep":"SOLq","./setProperties":"zASX"}],"ioQ1":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createDomElement=c;var r=require("./utils");function e(r){return i(r)||o(r)||n(r)||t()}function t(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(r,e){if(r){if("string"==typeof r)return a(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);return"Object"===t&&r.constructor&&(t=r.constructor.name),"Map"===t||"Set"===t?Array.from(r):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?a(r,e):void 0}}function o(r){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(r))return Array.from(r)}function i(r){if(Array.isArray(r))return a(r)}function a(r,e){(null==e||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function u(r,e){if(null==r)return{};var t,n,o=l(r,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(r);for(n=0;n<i.length;n++)t=i[n],e.indexOf(t)>=0||Object.prototype.propertyIsEnumerable.call(r,t)&&(o[t]=r[t])}return o}function l(r,e){if(null==r)return{};var t,n,o={},i=Object.keys(r);for(n=0;n<i.length;n++)t=i[n],e.indexOf(t)>=0||(o[t]=r[t]);return o}function c(t,n){var o=n.children,i=void 0===o?[]:o,a=u(n,["children"]),l=document.createElement(t);return(0,r.setProperties)(l,a),l.append.apply(l,e(i)),l}
},{"./utils":"TdV8"}],"sCRz":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Input=void 0;var e=require("../createDomElement"),t=require("../utils");function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function n(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach(function(t){o(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}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}function p(e,t){if(null==e)return{};var r,n,o=c(e,t);if(Object.getOwnPropertySymbols){var p=Object.getOwnPropertySymbols(e);for(n=0;n<p.length;n++)r=p[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(o[r]=e[r])}return o}function c(e,t){if(null==e)return{};var r,n,o={},p=Object.keys(e);for(n=0;n<p.length;n++)r=p[n],t.indexOf(r)>=0||(o[r]=e[r]);return o}var u=function(r){var o=r.autocompleteScopeApi,c=(r.classNames,r.getInputProps),u=r.getInputPropsCore,s=r.onDetachedEscape,i=r.state,a=p(r,["autocompleteScopeApi","classNames","getInputProps","getInputPropsCore","onDetachedEscape","state"]),l=(0,e.createDomElement)("input",a),f=c(n({state:i,props:u({inputElement:l}),inputElement:l},o));return(0,t.setProperties)(l,n(n({},f),{},{onKeyDown:function(e){s&&"Escape"===e.key?s():f.onKeyDown(e)}})),l};exports.Input=u;
},{"../createDomElement":"ioQ1","../utils":"TdV8"}],"oL9b":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LoadingIcon=void 0;var t=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");return t.setAttribute("class","aa-LoadingIcon"),t.setAttribute("viewBox","0 0 100 100"),t.setAttribute("width","20"),t.setAttribute("height","20"),t.innerHTML='<circle\n cx="50"\n cy="50"\n fill="none"\n r="35"\n stroke="currentColor"\n stroke-dasharray="164.93361431346415 56.97787143782138"\n stroke-width="6"\n>\n <animateTransform\n attributeName="transform"\n type="rotate"\n repeatCount="indefinite"\n dur="1s"\n values="0 50 50;90 50 50;180 50 50;360 50 50"\n keyTimes="0;0.40;0.65;1"\n />\n</circle>',t};exports.LoadingIcon=t;
},{}],"xIJV":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.ResetIcon=void 0;var t=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","aa-ResetIcon"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","18"),t.setAttribute("height","18"),t.setAttribute("fill","currentColor");var e=document.createElementNS("http://www.w3.org/2000/svg","path");return e.setAttribute("d","M5.293 6.707l5.293 5.293-5.293 5.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0l5.293-5.293 5.293 5.293c0.391 0.391 1.024 0.391 1.414 0s0.391-1.024 0-1.414l-5.293-5.293 5.293-5.293c0.391-0.391 0.391-1.024 0-1.414s-1.024-0.391-1.414 0l-5.293 5.293-5.293-5.293c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414z"),t.appendChild(e),t};exports.ResetIcon=t;
},{}],"XHk7":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.SearchIcon=void 0;var t=function(){var t=document.createElementNS("http://www.w3.org/2000/svg","svg");t.setAttribute("class","aa-SubmitIcon"),t.setAttribute("viewBox","0 0 24 24"),t.setAttribute("width","20"),t.setAttribute("height","20"),t.setAttribute("fill","currentColor");var e=document.createElementNS("http://www.w3.org/2000/svg","path");return e.setAttribute("d","M16.041 15.856c-0.034 0.026-0.067 0.055-0.099 0.087s-0.060 0.064-0.087 0.099c-1.258 1.213-2.969 1.958-4.855 1.958-1.933 0-3.682-0.782-4.95-2.050s-2.050-3.017-2.050-4.95 0.782-3.682 2.050-4.95 3.017-2.050 4.95-2.050 3.682 0.782 4.95 2.050 2.050 3.017 2.050 4.95c0 1.886-0.745 3.597-1.959 4.856zM21.707 20.293l-3.675-3.675c1.231-1.54 1.968-3.493 1.968-5.618 0-2.485-1.008-4.736-2.636-6.364s-3.879-2.636-6.364-2.636-4.736 1.008-6.364 2.636-2.636 3.879-2.636 6.364 1.008 4.736 2.636 6.364 3.879 2.636 6.364 2.636c2.125 0 4.078-0.737 5.618-1.968l3.675 3.675c0.391 0.391 1.024 0.391 1.414 0s0.391-1.024 0-1.414z"),t.appendChild(e),t};exports.SearchIcon=t;
},{}],"wv7S":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./Input");Object.keys(e).forEach(function(r){"default"!==r&&"__esModule"!==r&&(r in exports&&exports[r]===e[r]||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}}))});var r=require("./LoadingIcon");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var t=require("./ResetIcon");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var o=require("./SearchIcon");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});
},{"./Input":"sCRz","./LoadingIcon":"oL9b","./ResetIcon":"xIJV","./SearchIcon":"XHk7"}],"Vixe":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createAutocompleteDom=a;var e=require("./components"),t=require("./createDomElement"),o=require("./utils");function r(e,t){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),o.push.apply(o,r)}return o}function n(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?r(Object(o),!0).forEach(function(t){c(e,t,o[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):r(Object(o)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))})}return e}function c(e,t,o){return t in e?Object.defineProperty(e,t,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[t]=o,e}function a(o){var r=o.autocomplete,c=o.autocompleteScopeApi,a=o.classNames,l=o.isDetached,s=o.placeholder,i=void 0===s?"Search":s,p=o.propGetters,d=o.state;function u(){r.setQuery(""),r.setIsOpen(!1),r.refresh(),document.body.classList.remove("aa-Detached")}var m=p.getRootProps(n({state:d,props:r.getRootProps({})},c)),h=(0,t.createDomElement)("div",n({class:a.root},m)),b=(0,t.createDomElement)("div",{class:a.detachedContainer,onMouseDown:function(e){e.stopPropagation()}}),f=(0,t.createDomElement)("div",{class:a.detachedOverlay,children:[b],onMouseDown:function(){document.body.removeChild(f),u()}}),v=p.getLabelProps(n({state:d,props:r.getLabelProps({})},c)),D=(0,t.createDomElement)("button",{class:a.submitButton,type:"submit",children:[(0,e.SearchIcon)({})]}),P=(0,t.createDomElement)("label",n({class:a.label,children:[D]},v)),y=(0,t.createDomElement)("button",{class:a.resetButton,type:"reset",children:[(0,e.ResetIcon)({})]}),g=(0,t.createDomElement)("div",{class:a.loadingIndicator,children:[(0,e.LoadingIcon)({})]}),O=(0,e.Input)({class:a.input,state:d,getInputProps:p.getInputProps,getInputPropsCore:r.getInputProps,autocompleteScopeApi:c,onDetachedEscape:l?function(){document.body.removeChild(f),u()}:void 0}),E=(0,t.createDomElement)("div",{class:a.inputWrapperPrefix,children:[P,g]}),C=(0,t.createDomElement)("div",{class:a.inputWrapperSuffix,children:[y]}),j=(0,t.createDomElement)("div",{class:a.inputWrapper,children:[O]}),I=p.getFormProps(n({state:d,props:r.getFormProps({inputElement:O})},c)),S=(0,t.createDomElement)("form",n({class:a.form,children:[E,j,C]},I)),w=p.getPanelProps(n({state:d,props:r.getPanelProps({})},c)),B=(0,t.createDomElement)("div",n({class:a.panel},w));function x(){document.body.appendChild(f),document.body.classList.add("aa-Detached"),O.focus()}if(l){var L=(0,t.createDomElement)("div",{class:a.detachedSearchButtonIcon,children:[(0,e.SearchIcon)({})]}),W=(0,t.createDomElement)("div",{class:a.detachedSearchButtonPlaceholder,textContent:i}),k=(0,t.createDomElement)("button",{class:a.detachedSearchButton,onClick:function(e){e.preventDefault(),x()},children:[L,W]}),q=(0,t.createDomElement)("button",{class:a.detachedCancelButton,textContent:"Cancel",onClick:function(){document.body.removeChild(f),u()}}),A=(0,t.createDomElement)("div",{class:a.detachedFormContainer,children:[S,q]});b.appendChild(A),h.appendChild(k)}else h.appendChild(S);return{openDetachedOverlay:x,detachedContainer:b,detachedOverlay:f,inputWrapper:j,input:O,root:h,form:S,label:P,submitButton:D,resetButton:y,loadingIndicator:g,panel:B}}
},{"./components":"wv7S","./createDomElement":"ioQ1","./utils":"TdV8"}],"mk6c":[function(require,module,exports) {
"use strict";function e(){var e=[],r=[];function t(t){e.push(t);var f=t();r.push(f)}return{runEffect:t,cleanupEffects:function(){var e=r;r=[],e.forEach(function(e){e()})},runEffects:function(){var r=e;e=[],r.forEach(function(e){t(e)})}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createEffectWrapper=e;
},{}],"W1pD":[function(require,module,exports) {
"use strict";function e(){var e=[];return{reactive:function(r){var t={_fn:r,_ref:{current:r()},get value(){return this._ref.current},set value(e){this._ref.current=e}};return e.push(t),r(),t},runReactives:function(){e.forEach(function(e){e._ref.current=e._fn()})}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createReactiveWrapper=e;
},{}],"u8ui":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.render=L,exports.hydrate=F,exports.h=exports.createElement=p,exports.Fragment=d,exports.createRef=a,exports.Component=h,exports.cloneElement=H,exports.createContext=O,exports.toChildArray=b,exports.options=exports.isValidElement=void 0;var e,n,t,_,l,o,r={},i=[],u=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function s(e,n){for(var t in n)e[t]=n[t];return e}function c(e){var n=e.parentNode;n&&n.removeChild(e)}function p(e,n,t){var _,l,o,r=arguments,i={};for(o in n)"key"==o?_=n[o]:"ref"==o?l=n[o]:i[o]=n[o];if(arguments.length>3)for(t=[t],o=3;o<arguments.length;o++)t.push(r[o]);if(null!=t&&(i.children=t),"function"==typeof e&&null!=e.defaultProps)for(o in e.defaultProps)void 0===i[o]&&(i[o]=e.defaultProps[o]);return f(e,i,_,l,null)}function f(n,t,_,l,o){var r={type:n,props:t,key:_,ref:l,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++e.__v:o};return null!=e.vnode&&e.vnode(r),r}function a(){return{current:null}}function d(e){return e.children}function h(e,n){this.props=e,this.context=n}function v(e,n){if(null==n)return e.__?v(e.__,e.__.__k.indexOf(e)+1):null;for(var t;n<e.__k.length;n++)if(null!=(t=e.__k[n])&&null!=t.__e)return t.__e;return"function"==typeof e.type?v(e):null}function y(e){var n,t;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,n=0;n<e.__k.length;n++)if(null!=(t=e.__k[n])&&null!=t.__e){e.__e=e.__c.base=t.__e;break}return y(e)}}function m(n){(!n.__d&&(n.__d=!0)&&t.push(n)&&!k.__r++||l!==e.debounceRendering)&&((l=e.debounceRendering)||_)(k)}function k(){for(var e;k.__r=t.length;)e=t.sort(function(e,n){return e.__v.__b-n.__v.__b}),t=[],e.some(function(e){var n,t,_,l,o,r;e.__d&&(o=(l=(n=e).__v).__e,(r=n.__P)&&(t=[],(_=s({},l)).__v=l.__v+1,D(r,l,_,n.__n,void 0!==r.ownerSVGElement,null!=l.__h?[o]:null,t,null==o?v(l):o,l.__h),T(t,l),l.__e!=o&&y(l)))})}function g(e,n,t,_,l,o,u,s,c,p){var a,h,y,m,k,g,b,P=_&&_.__k||i,S=P.length;for(t.__k=[],a=0;a<n.length;a++)if(null!=(m=t.__k[a]=null==(m=n[a])||"boolean"==typeof m?null:"string"==typeof m||"number"==typeof m?f(null,m,null,null,m):Array.isArray(m)?f(d,{children:m},null,null,null):m.__b>0?f(m.type,m.props,m.key,null,m.__v):m)){if(m.__=t,m.__b=t.__b+1,null===(y=P[a])||y&&m.key==y.key&&m.type===y.type)P[a]=void 0;else for(h=0;h<S;h++){if((y=P[h])&&m.key==y.key&&m.type===y.type){P[h]=void 0;break}y=null}D(e,m,y=y||r,l,o,u,s,c,p),k=m.__e,(h=m.ref)&&y.ref!=h&&(b||(b=[]),y.ref&&b.push(y.ref,null,m),b.push(h,m.__c||k,m)),null!=k?(null==g&&(g=k),"function"==typeof m.type&&null!=m.__k&&m.__k===y.__k?m.__d=c=x(m,c,e):c=C(e,m,y,P,k,c),p||"option"!==t.type?"function"==typeof t.type&&(t.__d=c):e.value=""):c&&y.__e==c&&c.parentNode!=e&&(c=v(y))}for(t.__e=g,a=S;a--;)null!=P[a]&&("function"==typeof t.type&&null!=P[a].__e&&P[a].__e==t.__d&&(t.__d=v(_,a+1)),N(P[a],P[a]));if(b)for(a=0;a<b.length;a++)M(b[a],b[++a],b[++a])}function x(e,n,t){var _,l;for(_=0;_<e.__k.length;_++)(l=e.__k[_])&&(l.__=e,n="function"==typeof l.type?x(l,n,t):C(t,l,l,e.__k,l.__e,n));return n}function b(e,n){return n=n||[],null==e||"boolean"==typeof e||(Array.isArray(e)?e.some(function(e){b(e,n)}):n.push(e)),n}function C(e,n,t,_,l,o){var r,i,u;if(void 0!==n.__d)r=n.__d,n.__d=void 0;else if(null==t||l!=o||null==l.parentNode)e:if(null==o||o.parentNode!==e)e.appendChild(l),r=null;else{for(i=o,u=0;(i=i.nextSibling)&&u<_.length;u+=2)if(i==l)break e;e.insertBefore(l,o),r=o}return void 0!==r?r:l.nextSibling}function P(e,n,t,_,l){var o;for(o in t)"children"===o||"key"===o||o in n||E(e,o,null,t[o],_);for(o in n)l&&"function"!=typeof n[o]||"children"===o||"key"===o||"value"===o||"checked"===o||t[o]===n[o]||E(e,o,n[o],t[o],_)}function S(e,n,t){"-"===n[0]?e.setProperty(n,t):e[n]=null==t?"":"number"!=typeof t||u.test(n)?t:t+"px"}function E(e,n,t,_,l){var o;e:if("style"===n)if("string"==typeof t)e.style.cssText=t;else{if("string"==typeof _&&(e.style.cssText=_=""),_)for(n in _)t&&n in t||S(e.style,n,"");if(t)for(n in t)_&&t[n]===_[n]||S(e.style,n,t[n])}else if("o"===n[0]&&"n"===n[1])o=n!==(n=n.replace(/Capture$/,"")),n=n.toLowerCase()in e?n.toLowerCase().slice(2):n.slice(2),e.l||(e.l={}),e.l[n+o]=t,t?_||e.addEventListener(n,o?U:w,o):e.removeEventListener(n,o?U:w,o);else if("dangerouslySetInnerHTML"!==n){if(l)n=n.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if("href"!==n&&"list"!==n&&"form"!==n&&"download"!==n&&n in e)try{e[n]=null==t?"":t;break e}catch(e){}"function"==typeof t||(null!=t&&(!1!==t||"a"===n[0]&&"r"===n[1])?e.setAttribute(n,t):e.removeAttribute(n))}}function w(n){this.l[n.type+!1](e.event?e.event(n):n)}function U(n){this.l[n.type+!0](e.event?e.event(n):n)}function D(n,t,_,l,o,r,i,u,c){var p,f,a,v,y,m,k,x,b,C,P,S=t.type;if(void 0!==t.constructor)return null;null!=_.__h&&(c=_.__h,u=t.__e=_.__e,t.__h=null,r=[u]),(p=e.__b)&&p(t);try{e:if("function"==typeof S){if(x=t.props,b=(p=S.contextType)&&l[p.__c],C=p?b?b.props.value:p.__:l,_.__c?k=(f=t.__c=_.__c).__=f.__E:("prototype"in S&&S.prototype.render?t.__c=f=new S(x,C):(t.__c=f=new h(x,C),f.constructor=S,f.render=W),b&&b.sub(f),f.props=x,f.state||(f.state={}),f.context=C,f.__n=l,a=f.__d=!0,f.__h=[]),null==f.__s&&(f.__s=f.state),null!=S.getDerivedStateFromProps&&(f.__s==f.state&&(f.__s=s({},f.__s)),s(f.__s,S.getDerivedStateFromProps(x,f.__s))),v=f.props,y=f.state,a)null==S.getDerivedStateFromProps&&null!=f.componentWillMount&&f.componentWillMount(),null!=f.componentDidMount&&f.__h.push(f.componentDidMount);else{if(null==S.getDerivedStateFromProps&&x!==v&&null!=f.componentWillReceiveProps&&f.componentWillReceiveProps(x,C),!f.__e&&null!=f.shouldComponentUpdate&&!1===f.shouldComponentUpdate(x,f.__s,C)||t.__v===_.__v){f.props=x,f.state=f.__s,t.__v!==_.__v&&(f.__d=!1),f.__v=t,t.__e=_.__e,t.__k=_.__k,f.__h.length&&i.push(f);break e}null!=f.componentWillUpdate&&f.componentWillUpdate(x,f.__s,C),null!=f.componentDidUpdate&&f.__h.push(function(){f.componentDidUpdate(v,y,m)})}f.context=C,f.props=x,f.state=f.__s,(p=e.__r)&&p(t),f.__d=!1,f.__v=t,f.__P=n,p=f.render(f.props,f.state,f.context),f.state=f.__s,null!=f.getChildContext&&(l=s(s({},l),f.getChildContext())),a||null==f.getSnapshotBeforeUpdate||(m=f.getSnapshotBeforeUpdate(v,y)),P=null!=p&&p.type===d&&null==p.key?p.props.children:p,g(n,Array.isArray(P)?P:[P],t,_,l,o,r,i,u,c),f.base=t.__e,t.__h=null,f.__h.length&&i.push(f),k&&(f.__E=f.__=null),f.__e=!1}else null==r&&t.__v===_.__v?(t.__k=_.__k,t.__e=_.__e):t.__e=A(_.__e,t,_,l,o,r,i,c);(p=e.diffed)&&p(t)}catch(n){t.__v=null,(c||null!=r)&&(t.__e=u,t.__h=!!c,r[r.indexOf(u)]=null),e.__e(n,t,_)}}function T(n,t){e.__c&&e.__c(t,n),n.some(function(t){try{n=t.__h,t.__h=[],n.some(function(e){e.call(t)})}catch(n){e.__e(n,t.__v)}})}function A(e,n,t,_,l,o,u,s){var p,f,a,d,h=t.props,v=n.props,y=n.type,m=0;if("svg"===y&&(l=!0),null!=o)for(;m<o.length;m++)if((p=o[m])&&(p===e||(y?p.localName==y:3==p.nodeType))){e=p,o[m]=null;break}if(null==e){if(null===y)return document.createTextNode(v);e=l?document.createElementNS("http://www.w3.org/2000/svg",y):document.createElement(y,v.is&&v),o=null,s=!1}if(null===y)h===v||s&&e.data===v||(e.data=v);else{if(o=o&&i.slice.call(e.childNodes),f=(h=t.props||r).dangerouslySetInnerHTML,a=v.dangerouslySetInnerHTML,!s){if(null!=o)for(h={},d=0;d<e.attributes.length;d++)h[e.attributes[d].name]=e.attributes[d].value;(a||f)&&(a&&(f&&a.__html==f.__html||a.__html===e.innerHTML)||(e.innerHTML=a&&a.__html||""))}if(P(e,v,h,l,s),a)n.__k=[];else if(m=n.props.children,g(e,Array.isArray(m)?m:[m],n,t,_,l&&"foreignObject"!==y,o,u,e.firstChild,s),null!=o)for(m=o.length;m--;)null!=o[m]&&c(o[m]);s||("value"in v&&void 0!==(m=v.value)&&(m!==e.value||"progress"===y&&!m)&&E(e,"value",m,h.value,!1),"checked"in v&&void 0!==(m=v.checked)&&m!==e.checked&&E(e,"checked",m,h.checked,!1))}return e}function M(n,t,_){try{"function"==typeof n?n(t):n.current=t}catch(n){e.__e(n,_)}}function N(n,t,_){var l,o,r;if(e.unmount&&e.unmount(n),(l=n.ref)&&(l.current&&l.current!==n.__e||M(l,null,t)),_||"function"==typeof n.type||(_=null!=(o=n.__e)),n.__e=n.__d=void 0,null!=(l=n.__c)){if(l.componentWillUnmount)try{l.componentWillUnmount()}catch(n){e.__e(n,t)}l.base=l.__P=null}if(l=n.__k)for(r=0;r<l.length;r++)l[r]&&N(l[r],t,_);null!=o&&c(o)}function W(e,n,t){return this.constructor(e,t)}function L(n,t,_){var l,o,u;e.__&&e.__(n,t),o=(l="function"==typeof _)?null:_&&_.__k||t.__k,u=[],D(t,n=(!l&&_||t).__k=p(d,null,[n]),o||r,r,void 0!==t.ownerSVGElement,!l&&_?[_]:o?null:t.firstChild?i.slice.call(t.childNodes):null,u,!l&&_?_:o?o.__e:t.firstChild,l),T(u,n)}function F(e,n){L(e,n,F)}function H(e,n,t){var _,l,o,r=arguments,i=s({},e.props);for(o in n)"key"==o?_=n[o]:"ref"==o?l=n[o]:i[o]=n[o];if(arguments.length>3)for(t=[t],o=3;o<arguments.length;o++)t.push(r[o]);return null!=t&&(i.children=t),f(e.type,i,_||e.key,l||e.ref,null)}function O(e,n){var t={__c:n="__cC"+o++,__:e,Consumer:function(e,n){return e.children(n)},Provider:function(e){var t,_;return this.getChildContext||(t=[],(_={})[n]=this,this.getChildContext=function(){return _},this.shouldComponentUpdate=function(e){this.props.value!==e.value&&t.some(m)},this.sub=function(e){t.push(e);var n=e.componentWillUnmount;e.componentWillUnmount=function(){t.splice(t.indexOf(e),1),n&&n.call(e)}}),e.children}};return t.Provider.__=t.Consumer.contextType=t}exports.isValidElement=n,exports.options=e,exports.options=e={__e:function(e,n){for(var t,_,l;n=n.__;)if((t=n.__c)&&!t.__)try{if((_=t.constructor)&&null!=_.getDerivedStateFromError&&(t.setState(_.getDerivedStateFromError(e)),l=t.__d),null!=t.componentDidCatch&&(t.componentDidCatch(e),l=t.__d),l)return t.__E=t}catch(n){e=n}throw e},__v:0},exports.isValidElement=n=function(e){return null!=e&&void 0===e.constructor},h.prototype.setState=function(e,n){var t;t=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=s({},this.state),"function"==typeof e&&(e=e(s({},t),this.props)),e&&s(t,e),null!=e&&this.__v&&(n&&this.__h.push(n),m(this))},h.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),m(this))},h.prototype.render=d,t=[],_="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,k.__r=0,o=0;
},{}],"uArS":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getDefaultOptions=s;var e=require("@algolia/autocomplete-shared"),t=require("preact"),r=require("./utils");function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function a(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach(function(t){o(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}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}function u(e,t){if(null==e)return{};var r,n,a=p(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(e,r)&&(a[r]=e[r])}return a}function p(e,t){if(null==e)return{};var r,n,a={},o=Object.keys(e);for(n=0;n<o.length;n++)r=o[n],t.indexOf(r)>=0||(a[r]=e[r]);return a}var l={detachedCancelButton:"aa-DetachedCancelButton",detachedFormContainer:"aa-DetachedFormContainer",detachedContainer:"aa-DetachedContainer",detachedOverlay:"aa-DetachedOverlay",detachedSearchButton:"aa-DetachedSearchButton",detachedSearchButtonIcon:"aa-DetachedSearchButtonIcon",detachedSearchButtonPlaceholder:"aa-DetachedSearchButtonPlaceholder",form:"aa-Form",input:"aa-Input",inputWrapper:"aa-InputWrapper",inputWrapperPrefix:"aa-InputWrapperPrefix",inputWrapperSuffix:"aa-InputWrapperSuffix",item:"aa-Item",label:"aa-Label",list:"aa-List",loadingIndicator:"aa-LoadingIndicator",panel:"aa-Panel",panelLayout:"aa-PanelLayout",resetButton:"aa-ResetButton",root:"aa-Autocomplete",source:"aa-Source",sourceFooter:"aa-SourceFooter",sourceHeader:"aa-SourceHeader",sourceNoResults:"aa-SourceNoResults",submitButton:"aa-SubmitButton"},c=function(e,r){var n=e.children;(0,t.render)(n,r)},i={createElement:t.createElement,Fragment:t.Fragment};function s(t){var n=t.classNames,o=t.container,p=t.getEnvironmentProps,s=t.getFormProps,d=t.getInputProps,P=t.getItemProps,g=t.getLabelProps,m=t.getListProps,f=t.getPanelProps,h=t.getRootProps,b=t.panelContainer,y=t.panelPlacement,O=t.render,v=t.renderNoResults,S=t.renderer,j=t.detachedMediaQuery,I=u(t,["classNames","container","getEnvironmentProps","getFormProps","getInputProps","getItemProps","getLabelProps","getListProps","getPanelProps","getRootProps","panelContainer","panelPlacement","render","renderNoResults","renderer","detachedMediaQuery"]),w=(0,r.getHTMLElement)(o);(0,e.invariant)("INPUT"!==w.tagName,"The `container` option does not support `input` elements. You need to change the container to a `div`.");var L="undefined"!=typeof window?window:{};return{renderer:{classNames:(0,r.mergeClassNames)(l,null!=n?n:{}),container:w,getEnvironmentProps:null!=p?p:function(e){return e.props},getFormProps:null!=s?s:function(e){return e.props},getInputProps:null!=d?d:function(e){return e.props},getItemProps:null!=P?P:function(e){return e.props},getLabelProps:null!=g?g:function(e){return e.props},getListProps:null!=m?m:function(e){return e.props},getPanelProps:null!=f?f:function(e){return e.props},getRootProps:null!=h?h:function(e){return e.props},panelContainer:b?(0,r.getHTMLElement)(b):document.body,panelPlacement:null!=y?y:"input-wrapper-width",render:null!=O?O:c,renderNoResults:v,renderer:null!=S?S:i,detachedMediaQuery:null!=j?j:getComputedStyle(L.document.documentElement).getPropertyValue("--aa-detached-media-query")},core:a(a({},I),{},{environment:L})}}
},{"@algolia/autocomplete-shared":"uvJf","preact":"u8ui","./utils":"TdV8"}],"NfJk":[function(require,module,exports) {
"use strict";function t(t){var e=t.panelPlacement,n=t.container,i=t.form,r=t.environment,l=void 0===r?window:r,o=n.getBoundingClientRect(),d=n.offsetTop+o.height;switch(e){case"start":return{top:d,left:o.left};case"end":return{top:d,right:l.document.documentElement.clientWidth-(o.left+o.width)};case"full-width":return{top:d,left:0,right:0,width:"unset",maxWidth:"unset"};case"input-wrapper-width":var a=i.getBoundingClientRect();return{top:d,left:a.left,right:l.document.documentElement.clientWidth-(a.left+a.width),width:"unset",maxWidth:"unset"};default:throw new Error("The `panelPlacement` value ".concat(JSON.stringify(e)," is not valid."))}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getPanelPlacementStyle=t;
},{}],"vAOW":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.renderSearchBox=o,exports.renderPanel=n;var e=require("./utils");function t(){return(t=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e}).apply(this,arguments)}function r(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,s)}return r}function s(e){for(var t=1;t<arguments.length;t++){var s=null!=arguments[t]?arguments[t]:{};t%2?r(Object(s),!0).forEach(function(t){a(e,t,s[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(s)):r(Object(s)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(s,t))})}return e}function a(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(t){var r=t.autocomplete,a=t.autocompleteScopeApi,o=t.dom,n=t.propGetters,p=t.state;(0,e.setPropertiesWithoutEvents)(o.root,n.getRootProps(s({state:p,props:r.getRootProps({})},a))),(0,e.setPropertiesWithoutEvents)(o.input,n.getInputProps(s({state:p,props:r.getInputProps({inputElement:o.input}),inputElement:o.input},a))),(0,e.setProperties)(o.label,{hidden:"stalled"===p.status}),(0,e.setProperties)(o.loadingIndicator,{hidden:"stalled"!==p.status}),(0,e.setProperties)(o.resetButton,{hidden:!p.query})}function n(e,r){var a=r.autocomplete,o=r.autocompleteScopeApi,n=r.classNames,p=r.createElement,l=r.dom,i=r.Fragment,c=r.panelContainer,u=r.propGetters,m=r.state;if(m.isOpen){c.contains(l.panel)||"loading"===m.status||c.appendChild(l.panel),l.panel.classList.toggle("aa-Panel--stalled","stalled"===m.status);var d=m.collections.map(function(e,r){var l=e.source,c=e.items;return p("section",{key:r,className:n.source,"data-autocomplete-source-id":l.sourceId},l.templates.header&&p("div",{className:n.sourceHeader},l.templates.header({createElement:p,Fragment:i,items:c,source:l,state:m})),0===c.length&&l.templates.noResults&&m.query?p("div",{className:n.sourceNoResults},l.templates.noResults({createElement:p,Fragment:i,source:l,state:m})):p("ul",t({className:n.list},u.getListProps(s({state:m,props:a.getListProps({})},o))),c.map(function(e){var r=a.getItemProps({item:e,source:l});return p("li",t({key:r.id,className:n.item},u.getItemProps(s({state:m,props:r},o))),l.templates.item({createElement:p,Fragment:i,item:e,state:m}))})),l.templates.footer&&p("div",{className:n.sourceFooter},l.templates.footer({createElement:p,Fragment:i,items:c,source:l,state:m})))});e({children:p("div",{className:"aa-PanelLayout"},d),state:m,sections:d,createElement:p,Fragment:i},l.panel)}else c.contains(l.panel)&&c.removeChild(l.panel)}
},{"./utils":"TdV8"}],"lEBK":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.autocomplete=p;var e=require("@algolia/autocomplete-core"),r=require("@algolia/autocomplete-shared"),t=require("./createAutocompleteDom"),n=require("./createEffectWrapper"),a=require("./createReactiveWrapper"),o=require("./getDefaultOptions"),u=require("./getPanelPlacementStyle"),l=require("./render"),c=require("./utils");function i(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function s(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?i(Object(t),!0).forEach(function(r){v(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):i(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function v(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function p(i){var p=(0,n.createEffectWrapper)(),d=p.runEffect,m=p.cleanupEffects,f=p.runEffects,g=(0,a.createReactiveWrapper)(),P=g.reactive,h=g.runReactives,O=(0,r.createRef)(!1),y=(0,r.createRef)(i),b=(0,r.createRef)(void 0),E=P(function(){return(0,o.getDefaultOptions)(y.current)}),C=P(function(){return E.value.core.environment.matchMedia(E.value.renderer.detachedMediaQuery).matches}),S=P(function(){return(0,e.createAutocomplete)(s(s({},E.value.core),{},{onStateChange:function(e){var r,t,n;O.current=e.state.collections.some(function(e){return e.source.templates.noResults}),null===(r=b.current)||void 0===r||r.call(b,e),null===(t=(n=E.value.core).onStateChange)||void 0===t||t.call(n,e)},shouldPanelOpen:y.current.shouldPanelOpen||function(e){var t=e.state,n=(0,r.getItemsCount)(t)>0;if(!E.value.core.openOnFocus&&!t.query)return n;var a=Boolean(O.current||E.value.renderer.renderNoResults);return!n&&a||n}}))}),j=(0,r.createRef)(s({collections:[],completion:null,context:{},isOpen:!1,query:"",activeItemId:null,status:"idle"},E.value.core.initialState)),q={getEnvironmentProps:E.value.renderer.getEnvironmentProps,getFormProps:E.value.renderer.getFormProps,getInputProps:E.value.renderer.getInputProps,getItemProps:E.value.renderer.getItemProps,getLabelProps:E.value.renderer.getLabelProps,getListProps:E.value.renderer.getListProps,getPanelProps:E.value.renderer.getPanelProps,getRootProps:E.value.renderer.getRootProps},I={setActiveItemId:S.value.setActiveItemId,setQuery:S.value.setQuery,setCollections:S.value.setCollections,setIsOpen:S.value.setIsOpen,setStatus:S.value.setStatus,setContext:S.value.setContext,refresh:S.value.refresh},D=P(function(){return(0,t.createAutocompleteDom)({autocomplete:S.value,autocompleteScopeApi:I,classNames:E.value.renderer.classNames,isDetached:C.value,placeholder:E.value.core.placeholder,propGetters:q,state:j.current})});function R(){(0,c.setProperties)(D.value.panel,{style:C.value?{}:(0,u.getPanelPlacementStyle)({panelPlacement:E.value.renderer.panelPlacement,container:D.value.root,form:D.value.form,environment:E.value.core.environment})})}function w(e){j.current=e;var t={autocomplete:S.value,autocompleteScopeApi:I,classNames:E.value.renderer.classNames,container:E.value.renderer.container,createElement:E.value.renderer.renderer.createElement,dom:D.value,Fragment:E.value.renderer.renderer.Fragment,panelContainer:C.value?D.value.detachedContainer:E.value.renderer.panelContainer,propGetters:q,state:j.current},n=!(0,r.getItemsCount)(e)&&!O.current&&E.value.renderer.renderNoResults||E.value.renderer.render;(0,l.renderSearchBox)(t),(0,l.renderPanel)(n,t)}function A(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};m(),y.current=(0,c.mergeDeep)(E.value.renderer,E.value.core,{initialState:j.current},e),h(),f(),S.value.refresh().then(function(){w(j.current)})}return d(function(){var e=S.value.getEnvironmentProps({formElement:D.value.form,panelElement:D.value.panel,inputElement:D.value.input});return(0,c.setProperties)(E.value.core.environment,e),function(){(0,c.setProperties)(E.value.core.environment,Object.keys(e).reduce(function(e,r){return s(s({},e),{},v({},r,void 0))},{}))}}),d(function(){var e=C.value?E.value.core.environment.document.body:E.value.renderer.panelContainer,r=C.value?D.value.detachedOverlay:D.value.panel;return C.value&&j.current.isOpen&&D.value.openDetachedOverlay(),w(j.current),function(){e.contains(r)&&e.removeChild(r)}}),d(function(){var e=E.value.renderer.container;return e.appendChild(D.value.root),function(){e.removeChild(D.value.root)}}),d(function(){var e=(0,r.debounce)(function(e){w(e.state)},0);return b.current=function(r){var t=r.state,n=r.prevState;t.isOpen&&!n.isOpen&&R(),e({state:t})},function(){b.current=void 0}}),d(function(){var e=(0,r.debounce)(function(){var e=C.value;C.value=E.value.core.environment.matchMedia(E.value.renderer.detachedMediaQuery).matches,e!==C.value?A({}):requestAnimationFrame(R)},20);return E.value.core.environment.addEventListener("resize",e),function(){E.value.core.environment.removeEventListener("resize",e)}}),d(function(){if(!C.value)return function(){};function e(e){D.value.detachedContainer.classList.toggle("aa-DetachedContainer--Modal",e)}function r(r){e(r.matches)}var t=window.matchMedia(getComputedStyle(E.value.core.environment.document.documentElement).getPropertyValue("--aa-detached-modal-media-query"));return e(t.matches),t.addEventListener("change",r),function(){t.removeEventListener("change",r)}}),d(function(){return requestAnimationFrame(R),function(){}}),s(s({},I),{},{update:A,destroy:function(){m()}})}
},{"@algolia/autocomplete-core":"mUNi","@algolia/autocomplete-shared":"uvJf","./createAutocompleteDom":"Vixe","./createEffectWrapper":"mk6c","./createReactiveWrapper":"W1pD","./getDefaultOptions":"uArS","./getPanelPlacementStyle":"NfJk","./render":"vAOW","./utils":"TdV8"}],"PGKh":[function(require,module,exports) {
"use strict";function e(e,t){return t.reduce(function(e,t){return e&&e[t]},e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAttributeValueByPath=e;
},{}],"P9E7":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.HIGHLIGHT_POST_TAG=exports.HIGHLIGHT_PRE_TAG=void 0;var _="__aa-highlight__";exports.HIGHLIGHT_PRE_TAG=_;var e="__/aa-highlight__";exports.HIGHLIGHT_POST_TAG=e;
},{}],"xlAs":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseAttribute=t;var e=require("../constants");function i(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return{get:function(){return e},add:function(i){var t=e[e.length-1];(null==t?void 0:t.isHighlighted)===i.isHighlighted?e[e.length-1]={value:t.value+i.value,isHighlighted:t.isHighlighted}:e.push(i)}}}function t(t){var l=t.highlightedValue.split(e.HIGHLIGHT_PRE_TAG),h=l.shift(),u=i(h?[{value:h,isHighlighted:!1}]:[]);return l.forEach(function(i){var t=i.split(e.HIGHLIGHT_POST_TAG);u.add({value:t[0],isHighlighted:!0}),""!==t[1]&&u.add({value:t[1],isHighlighted:!1})}),u.get()}
},{"../constants":"P9E7"}],"jOox":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseAlgoliaHitHighlight=c;var t=require("@algolia/autocomplete-shared"),r=require("./getAttributeValueByPath"),e=require("./parseAttribute");function i(t){return u(t)||o(t)||a(t)||n()}function n(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function a(t,r){if(t){if("string"==typeof t)return l(t,r);var e=Object.prototype.toString.call(t).slice(8,-1);return"Object"===e&&t.constructor&&(e=t.constructor.name),"Map"===e||"Set"===e?Array.from(t):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?l(t,r):void 0}}function o(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}function u(t){if(Array.isArray(t))return l(t)}function l(t,r){(null==r||r>t.length)&&(r=t.length);for(var e=0,i=new Array(r);e<r;e++)i[e]=t[e];return i}function c(t){var n=t.hit,a=t.attribute,o=Array.isArray(a)?a:[a],u=(0,r.getAttributeValueByPath)(n,["_highlightResult"].concat(i(o),["value"]));return"string"!=typeof u&&(u=(0,r.getAttributeValueByPath)(n,o)||""),(0,e.parseAttribute)({highlightedValue:u})}
},{"@algolia/autocomplete-shared":"uvJf","./getAttributeValueByPath":"PGKh","./parseAttribute":"xlAs"}],"jUE6":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isPartHighlighted=l;var t={"&":"&","<":"<",">":">",""":'"',"'":"'"},e=new RegExp(/\w/i),i=/&(amp|quot|lt|gt|#39);/g,r=RegExp(i.source);function u(e){return e&&r.test(e)?e.replace(i,function(e){return t[e]}):e}function l(t,i){var r,l,o=t[i],g=(null===(r=t[i+1])||void 0===r?void 0:r.isHighlighted)||!0,n=(null===(l=t[i-1])||void 0===l?void 0:l.isHighlighted)||!0;return e.test(u(o.value))||n!==g?o.isHighlighted:n}
},{}],"bh9o":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.reverseHighlightedParts=i;var e=require("./isPartHighlighted");function r(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function t(e){for(var t=1;t<arguments.length;t++){var i=null!=arguments[t]?arguments[t]:{};t%2?r(Object(i),!0).forEach(function(r){n(e,r,i[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(i)):r(Object(i)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(i,r))})}return e}function n(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function i(r){return r.some(function(e){return e.isHighlighted})?r.map(function(n,i){return t(t({},n),{},{isHighlighted:!(0,e.isPartHighlighted)(r,i)})}):r.map(function(e){return t(t({},e),{},{isHighlighted:!1})})}
},{"./isPartHighlighted":"jUE6"}],"u5Dm":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseAlgoliaHitReverseHighlight=i;var e=require("./parseAlgoliaHitHighlight"),r=require("./reverseHighlightedParts");function i(i){return(0,r.reverseHighlightedParts)((0,e.parseAlgoliaHitHighlight)(i))}
},{"./parseAlgoliaHitHighlight":"jOox","./reverseHighlightedParts":"bh9o"}],"if6D":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseAlgoliaHitSnippet=s;var t=require("@algolia/autocomplete-shared"),r=require("./getAttributeValueByPath"),e=require("./parseAttribute");function n(t){return u(t)||o(t)||i(t)||a()}function a(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function i(t,r){if(t){if("string"==typeof t)return l(t,r);var e=Object.prototype.toString.call(t).slice(8,-1);return"Object"===e&&t.constructor&&(e=t.constructor.name),"Map"===e||"Set"===e?Array.from(t):"Arguments"===e||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?l(t,r):void 0}}function o(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}function u(t){if(Array.isArray(t))return l(t)}function l(t,r){(null==r||r>t.length)&&(r=t.length);for(var e=0,n=new Array(r);e<r;e++)n[e]=t[e];return n}function s(t){var a=t.hit,i=t.attribute,o=Array.isArray(i)?i:[i],u=(0,r.getAttributeValueByPath)(a,["_snippetResult"].concat(n(o),["value"]));return"string"!=typeof u&&(u=(0,r.getAttributeValueByPath)(a,o)||""),(0,e.parseAttribute)({highlightedValue:u})}
},{"@algolia/autocomplete-shared":"uvJf","./getAttributeValueByPath":"PGKh","./parseAttribute":"xlAs"}],"ALfz":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.parseAlgoliaHitReverseSnippet=i;var e=require("./parseAlgoliaHitSnippet"),r=require("./reverseHighlightedParts");function i(i){return(0,r.reverseHighlightedParts)((0,e.parseAlgoliaHitSnippet)(i))}
},{"./parseAlgoliaHitSnippet":"if6D","./reverseHighlightedParts":"bh9o"}],"WQwm":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.searchForFacetValues=l;var e=require("../constants"),r=require("../version");function t(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function n(e){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?t(Object(n),!0).forEach(function(r){o(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function o(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function i(e){return s(e)||u(e)||c(e)||a()}function a(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function c(e,r){if(e){if("string"==typeof e)return f(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?f(e,r):void 0}}function u(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}function s(e){if(Array.isArray(e))return f(e)}function f(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function l(t){var o=t.searchClient,a=t.queries,c=t.userAgents,u=void 0===c?[]:c;"function"==typeof o.addAlgoliaAgent&&[{segment:"autocomplete-core",version:r.version}].concat(i(u)).forEach(function(e){var r=e.segment,t=e.version;o.addAlgoliaAgent(r,t)});return o.searchForFacetValues(a.map(function(r){var t=r.indexName,o=r.params;return{indexName:t,params:n({highlightPreTag:e.HIGHLIGHT_PRE_TAG,highlightPostTag:e.HIGHLIGHT_POST_TAG},o)}}))}
},{"../constants":"P9E7","../version":"Q8BT"}],"A6P2":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAlgoliaFacetHits=t;var e=require("./searchForFacetValues");function t(t){var r=t.searchClient,u=t.queries,a=t.userAgents;return(0,e.searchForFacetValues)({searchClient:r,queries:u,userAgents:a}).then(function(e){return e.map(function(e){return e.facetHits.map(function(e){return{label:e.value,count:e.count,_highlightResult:{label:{value:e.highlighted}}}})})})}
},{"./searchForFacetValues":"WQwm"}],"mJd7":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.search=l;var e=require("../constants"),r=require("../version");function t(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function n(e){for(var r=1;r<arguments.length;r++){var n=null!=arguments[r]?arguments[r]:{};r%2?t(Object(n),!0).forEach(function(r){o(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function o(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function i(e){return s(e)||u(e)||c(e)||a()}function a(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function c(e,r){if(e){if("string"==typeof e)return f(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?f(e,r):void 0}}function u(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}function s(e){if(Array.isArray(e))return f(e)}function f(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function l(t){var o=t.searchClient,a=t.queries,c=t.userAgents,u=void 0===c?[]:c;"function"==typeof o.addAlgoliaAgent&&[{segment:"autocomplete-core",version:r.version}].concat(i(u)).forEach(function(e){var r=e.segment,t=e.version;o.addAlgoliaAgent(r,t)});return o.search(a.map(function(r){var t=r.indexName,o=r.query,i=r.params;return{indexName:t,query:o,params:n({hitsPerPage:5,highlightPreTag:e.HIGHLIGHT_PRE_TAG,highlightPostTag:e.HIGHLIGHT_POST_TAG},i)}}))}
},{"../constants":"P9E7","../version":"Q8BT"}],"wN7Q":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAlgoliaHits=o;var e=require("./search");function r(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function t(e){for(var t=1;t<arguments.length;t++){var o=null!=arguments[t]?arguments[t]:{};t%2?r(Object(o),!0).forEach(function(r){n(e,r,o[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):r(Object(o)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(o,r))})}return e}function n(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function o(r){var n=r.searchClient,o=r.queries,c=r.userAgents;return(0,e.search)({searchClient:n,queries:o,userAgents:c}).then(function(e){return e.results.map(function(e){return e.hits.map(function(r){return t(t({},r),{},{__autocomplete_indexName:e.index,__autocomplete_queryID:e.queryID})})})})}
},{"./search":"mJd7"}],"CSV7":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAlgoliaResults=r;var e=require("./search");function r(r){var s=r.searchClient,t=r.queries,u=r.userAgents;return(0,e.search)({searchClient:s,queries:t,userAgents:u}).then(function(e){return e.results})}
},{"./search":"mJd7"}],"JeyL":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./highlight/HighlightedHit");Object.keys(e).forEach(function(t){"default"!==t&&"__esModule"!==t&&(t in exports&&exports[t]===e[t]||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}}))});var t=require("./highlight/parseAlgoliaHitHighlight");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var r=require("./highlight/parseAlgoliaHitReverseHighlight");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var i=require("./highlight/parseAlgoliaHitReverseSnippet");Object.keys(i).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===i[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return i[e]}}))});var o=require("./highlight/parseAlgoliaHitSnippet");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});var n=require("./highlight/SnippetedHit");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===n[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return n[e]}}))});var u=require("./search/getAlgoliaFacetHits");Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===u[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return u[e]}}))});var s=require("./search/getAlgoliaHits");Object.keys(s).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===s[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return s[e]}}))});var l=require("./search/getAlgoliaResults");Object.keys(l).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===l[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return l[e]}}))});
},{"./highlight/HighlightedHit":"DMuU","./highlight/parseAlgoliaHitHighlight":"jOox","./highlight/parseAlgoliaHitReverseHighlight":"u5Dm","./highlight/parseAlgoliaHitReverseSnippet":"ALfz","./highlight/parseAlgoliaHitSnippet":"if6D","./highlight/SnippetedHit":"DMuU","./search/getAlgoliaFacetHits":"A6P2","./search/getAlgoliaHits":"wN7Q","./search/getAlgoliaResults":"CSV7"}],"GhYF":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAlgoliaFacetHits=r;var e=require("@algolia/autocomplete-preset-algolia"),t=require("./version");function r(r){var s=r.searchClient,i=r.queries;return(0,e.getAlgoliaFacetHits)({searchClient:s,queries:i,userAgents:[{segment:"autocomplete-js",version:t.version}]})}
},{"@algolia/autocomplete-preset-algolia":"JeyL","./version":"Q8BT"}],"dqIM":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAlgoliaHits=t;var e=require("@algolia/autocomplete-preset-algolia"),r=require("./version");function t(t){var s=t.searchClient,i=t.queries;return(0,e.getAlgoliaHits)({searchClient:s,queries:i,userAgents:[{segment:"autocomplete-js",version:r.version}]})}
},{"@algolia/autocomplete-preset-algolia":"JeyL","./version":"Q8BT"}],"KqIo":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getAlgoliaResults=s;var e=require("@algolia/autocomplete-preset-algolia"),r=require("./version");function s(s){var t=s.searchClient,i=s.queries;return(0,e.getAlgoliaResults)({searchClient:t,queries:i,userAgents:[{segment:"autocomplete-js",version:r.version}]})}
},{"@algolia/autocomplete-preset-algolia":"JeyL","./version":"Q8BT"}],"RDhL":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.highlightHit=i,exports.reverseHighlightHit=r,exports.snippetHit=a,exports.reverseSnippetHit=l;var e=require("@algolia/autocomplete-preset-algolia"),t=require("preact");function i(i){var r=i.hit,a=i.attribute,l=i.tagName,u=void 0===l?"mark":l,n=i.createElement,o=void 0===n?t.createElement:n;return(0,e.parseAlgoliaHitHighlight)({hit:r,attribute:a}).map(function(e,t){return e.isHighlighted?o(u,{key:t},e.value):e.value})}function r(i){var r=i.hit,a=i.attribute,l=i.tagName,u=void 0===l?"mark":l,n=i.createElement,o=void 0===n?t.createElement:n;return(0,e.parseAlgoliaHitReverseHighlight)({hit:r,attribute:a}).map(function(e,t){return e.isHighlighted?o(u,{key:t},e.value):e.value})}function a(i){var r=i.hit,a=i.attribute,l=i.tagName,u=void 0===l?"mark":l,n=i.createElement,o=void 0===n?t.createElement:n;return(0,e.parseAlgoliaHitSnippet)({hit:r,attribute:a}).map(function(e,t){return e.isHighlighted?o(u,{key:t},e.value):e.value})}function l(i){var r=i.hit,a=i.attribute,l=i.tagName,u=void 0===l?"mark":l,n=i.createElement,o=void 0===n?t.createElement:n;return(0,e.parseAlgoliaHitReverseSnippet)({hit:r,attribute:a}).map(function(e,t){return e.isHighlighted?o(u,{key:t},e.value):e.value})}
},{"@algolia/autocomplete-preset-algolia":"JeyL","preact":"u8ui"}],"kxPg":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./AutocompleteApi");Object.keys(e).forEach(function(t){"default"!==t&&"__esModule"!==t&&(t in exports&&exports[t]===e[t]||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}}))});var t=require("./AutocompleteClassNames");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var r=require("./AutocompleteCollection");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var o=require("./AutocompleteDom");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});var n=require("./AutocompleteOptions");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===n[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return n[e]}}))});var u=require("./AutocompletePlugin");Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===u[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return u[e]}}))});var c=require("./AutocompletePropGetters");Object.keys(c).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===c[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return c[e]}}))});var s=require("./AutocompleteRender");Object.keys(s).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===s[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return s[e]}}))});var i=require("./AutocompleteRenderer");Object.keys(i).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===i[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return i[e]}}))});var p=require("./AutocompleteSource");Object.keys(p).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===p[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return p[e]}}))});var f=require("./AutocompleteState");Object.keys(f).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===f[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return f[e]}}))});
},{"./AutocompleteApi":"DMuU","./AutocompleteClassNames":"DMuU","./AutocompleteCollection":"DMuU","./AutocompleteDom":"DMuU","./AutocompleteOptions":"DMuU","./AutocompletePlugin":"DMuU","./AutocompletePropGetters":"DMuU","./AutocompleteRender":"DMuU","./AutocompleteRenderer":"DMuU","./AutocompleteSource":"DMuU","./AutocompleteState":"DMuU"}],"mF0j":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./autocomplete");Object.keys(e).forEach(function(t){"default"!==t&&"__esModule"!==t&&(t in exports&&exports[t]===e[t]||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return e[t]}}))});var t=require("./getAlgoliaFacetHits");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var r=require("./getAlgoliaHits");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var o=require("./getAlgoliaResults");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});var n=require("./highlight");Object.keys(n).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===n[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return n[e]}}))});var u=require("./types");Object.keys(u).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===u[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return u[e]}}))});
},{"./autocomplete":"lEBK","./getAlgoliaFacetHits":"GhYF","./getAlgoliaHits":"dqIM","./getAlgoliaResults":"KqIo","./highlight":"RDhL","./types":"kxPg"}],"FRly":[function(require,module,exports) {
"use strict";exports.byteLength=u,exports.toByteArray=i,exports.fromByteArray=d;for(var r=[],t=[],e="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=n.length;o<a;++o)r[o]=n[o],t[n.charCodeAt(o)]=o;function h(r){var t=r.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=r.indexOf("=");return-1===e&&(e=t),[e,e===t?0:4-e%4]}function u(r){var t=h(r),e=t[0],n=t[1];return 3*(e+n)/4-n}function c(r,t,e){return 3*(t+e)/4-e}function i(r){var n,o,a=h(r),u=a[0],i=a[1],f=new e(c(r,u,i)),A=0,d=i>0?u-4:u;for(o=0;o<d;o+=4)n=t[r.charCodeAt(o)]<<18|t[r.charCodeAt(o+1)]<<12|t[r.charCodeAt(o+2)]<<6|t[r.charCodeAt(o+3)],f[A++]=n>>16&255,f[A++]=n>>8&255,f[A++]=255&n;return 2===i&&(n=t[r.charCodeAt(o)]<<2|t[r.charCodeAt(o+1)]>>4,f[A++]=255&n),1===i&&(n=t[r.charCodeAt(o)]<<10|t[r.charCodeAt(o+1)]<<4|t[r.charCodeAt(o+2)]>>2,f[A++]=n>>8&255,f[A++]=255&n),f}function f(t){return r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}function A(r,t,e){for(var n,o=[],a=t;a<e;a+=3)n=(r[a]<<16&16711680)+(r[a+1]<<8&65280)+(255&r[a+2]),o.push(f(n));return o.join("")}function d(t){for(var e,n=t.length,o=n%3,a=[],h=0,u=n-o;h<u;h+=16383)a.push(A(t,h,h+16383>u?u:h+16383));return 1===o?(e=t[n-1],a.push(r[e>>2]+r[e<<4&63]+"==")):2===o&&(e=(t[n-2]<<8)+t[n-1],a.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),a.join("")}t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63;
},{}],"Quj6":[function(require,module,exports) {
exports.read=function(a,o,t,r,h){var M,p,w=8*h-r-1,f=(1<<w)-1,e=f>>1,i=-7,N=t?h-1:0,n=t?-1:1,s=a[o+N];for(N+=n,M=s&(1<<-i)-1,s>>=-i,i+=w;i>0;M=256*M+a[o+N],N+=n,i-=8);for(p=M&(1<<-i)-1,M>>=-i,i+=r;i>0;p=256*p+a[o+N],N+=n,i-=8);if(0===M)M=1-e;else{if(M===f)return p?NaN:1/0*(s?-1:1);p+=Math.pow(2,r),M-=e}return(s?-1:1)*p*Math.pow(2,M-r)},exports.write=function(a,o,t,r,h,M){var p,w,f,e=8*M-h-1,i=(1<<e)-1,N=i>>1,n=23===h?Math.pow(2,-24)-Math.pow(2,-77):0,s=r?0:M-1,u=r?1:-1,l=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(w=isNaN(o)?1:0,p=i):(p=Math.floor(Math.log(o)/Math.LN2),o*(f=Math.pow(2,-p))<1&&(p--,f*=2),(o+=p+N>=1?n/f:n*Math.pow(2,1-N))*f>=2&&(p++,f/=2),p+N>=i?(w=0,p=i):p+N>=1?(w=(o*f-1)*Math.pow(2,h),p+=N):(w=o*Math.pow(2,N-1)*Math.pow(2,h),p=0));h>=8;a[t+s]=255&w,s+=u,w/=256,h-=8);for(p=p<<h|w,e+=h;e>0;a[t+s]=255&p,s+=u,p/=256,e-=8);a[t+s-u]|=128*l};
},{}],"aqZJ":[function(require,module,exports) {
var r={}.toString;module.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)};
},{}],"aMB2":[function(require,module,exports) {
var global = arguments[3];
var t=arguments[3],r=require("base64-js"),e=require("ieee754"),n=require("isarray");function i(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(r){return!1}}function o(){return f.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function u(t,r){if(o()<r)throw new RangeError("Invalid typed array length");return f.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(r)).__proto__=f.prototype:(null===t&&(t=new f(r)),t.length=r),t}function f(t,r,e){if(!(f.TYPED_ARRAY_SUPPORT||this instanceof f))return new f(t,r,e);if("number"==typeof t){if("string"==typeof r)throw new Error("If encoding is specified then the first argument must be a string");return c(this,t)}return s(this,t,r,e)}function s(t,r,e,n){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&r instanceof ArrayBuffer?g(t,r,e,n):"string"==typeof r?l(t,r,e):y(t,r)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function a(t,r,e,n){return h(r),r<=0?u(t,r):void 0!==e?"string"==typeof n?u(t,r).fill(e,n):u(t,r).fill(e):u(t,r)}function c(t,r){if(h(r),t=u(t,r<0?0:0|w(r)),!f.TYPED_ARRAY_SUPPORT)for(var e=0;e<r;++e)t[e]=0;return t}function l(t,r,e){if("string"==typeof e&&""!==e||(e="utf8"),!f.isEncoding(e))throw new TypeError('"encoding" must be a valid string encoding');var n=0|v(r,e),i=(t=u(t,n)).write(r,e);return i!==n&&(t=t.slice(0,i)),t}function p(t,r){var e=r.length<0?0:0|w(r.length);t=u(t,e);for(var n=0;n<e;n+=1)t[n]=255&r[n];return t}function g(t,r,e,n){if(r.byteLength,e<0||r.byteLength<e)throw new RangeError("'offset' is out of bounds");if(r.byteLength<e+(n||0))throw new RangeError("'length' is out of bounds");return r=void 0===e&&void 0===n?new Uint8Array(r):void 0===n?new Uint8Array(r,e):new Uint8Array(r,e,n),f.TYPED_ARRAY_SUPPORT?(t=r).__proto__=f.prototype:t=p(t,r),t}function y(t,r){if(f.isBuffer(r)){var e=0|w(r.length);return 0===(t=u(t,e)).length?t:(r.copy(t,0,0,e),t)}if(r){if("undefined"!=typeof ArrayBuffer&&r.buffer instanceof ArrayBuffer||"length"in r)return"number"!=typeof r.length||W(r.length)?u(t,0):p(t,r);if("Buffer"===r.type&&n(r.data))return p(t,r.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function w(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function d(t){return+t!=t&&(t=0),f.alloc(+t)}function v(t,r){if(f.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return $(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return K(t).length;default:if(n)return $(t).length;r=(""+r).toLowerCase(),n=!0}}function E(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return x(this,r,e);case"utf8":case"utf-8":return Y(this,r,e);case"ascii":return L(this,r,e);case"latin1":case"binary":return D(this,r,e);case"base64":return S(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function b(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function R(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=f.from(r,n)),f.isBuffer(r))return 0===r.length?-1:_(t,r,e,n,i);if("number"==typeof r)return r&=255,f.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):_(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function _(t,r,e,n,i){var o,u=1,f=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,f/=2,s/=2,e/=2}function h(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}if(i){var a=-1;for(o=e;o<f;o++)if(h(t,o)===h(r,-1===a?0:o-a)){if(-1===a&&(a=o),o-a+1===s)return a*u}else-1!==a&&(o-=o-a),a=-1}else for(e+s>f&&(e=f-s),o=e;o>=0;o--){for(var c=!0,l=0;l<s;l++)if(h(t,o+l)!==h(r,l)){c=!1;break}if(c)return o}return-1}function A(t,r,e,n){e=Number(e)||0;var i=t.length-e;n?(n=Number(n))>i&&(n=i):n=i;var o=r.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var u=0;u<n;++u){var f=parseInt(r.substr(2*u,2),16);if(isNaN(f))return u;t[e+u]=f}return u}function m(t,r,e,n){return Q($(r,t.length-e),t,e,n)}function P(t,r,e,n){return Q(G(r),t,e,n)}function T(t,r,e,n){return P(t,r,e,n)}function B(t,r,e,n){return Q(K(r),t,e,n)}function U(t,r,e,n){return Q(H(r,t.length-e),t,e,n)}function S(t,e,n){return 0===e&&n===t.length?r.fromByteArray(t):r.fromByteArray(t.slice(e,n))}function Y(t,r,e){e=Math.min(t.length,e);for(var n=[],i=r;i<e;){var o,u,f,s,h=t[i],a=null,c=h>239?4:h>223?3:h>191?2:1;if(i+c<=e)switch(c){case 1:h<128&&(a=h);break;case 2:128==(192&(o=t[i+1]))&&(s=(31&h)<<6|63&o)>127&&(a=s);break;case 3:o=t[i+1],u=t[i+2],128==(192&o)&&128==(192&u)&&(s=(15&h)<<12|(63&o)<<6|63&u)>2047&&(s<55296||s>57343)&&(a=s);break;case 4:o=t[i+1],u=t[i+2],f=t[i+3],128==(192&o)&&128==(192&u)&&128==(192&f)&&(s=(15&h)<<18|(63&o)<<12|(63&u)<<6|63&f)>65535&&s<1114112&&(a=s)}null===a?(a=65533,c=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=c}return O(n)}exports.Buffer=f,exports.SlowBuffer=d,exports.INSPECT_MAX_BYTES=50,f.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),exports.kMaxLength=o(),f.poolSize=8192,f._augment=function(t){return t.__proto__=f.prototype,t},f.from=function(t,r,e){return s(null,t,r,e)},f.TYPED_ARRAY_SUPPORT&&(f.prototype.__proto__=Uint8Array.prototype,f.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&f[Symbol.species]===f&&Object.defineProperty(f,Symbol.species,{value:null,configurable:!0})),f.alloc=function(t,r,e){return a(null,t,r,e)},f.allocUnsafe=function(t){return c(null,t)},f.allocUnsafeSlow=function(t){return c(null,t)},f.isBuffer=function(t){return!(null==t||!t._isBuffer)},f.compare=function(t,r){if(!f.isBuffer(t)||!f.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(t===r)return 0;for(var e=t.length,n=r.length,i=0,o=Math.min(e,n);i<o;++i)if(t[i]!==r[i]){e=t[i],n=r[i];break}return e<n?-1:n<e?1:0},f.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},f.concat=function(t,r){if(!n(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return f.alloc(0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var i=f.allocUnsafe(r),o=0;for(e=0;e<t.length;++e){var u=t[e];if(!f.isBuffer(u))throw new TypeError('"list" argument must be an Array of Buffers');u.copy(i,o),o+=u.length}return i},f.byteLength=v,f.prototype._isBuffer=!0,f.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)b(this,r,r+1);return this},f.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)b(this,r,r+3),b(this,r+1,r+2);return this},f.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)b(this,r,r+7),b(this,r+1,r+6),b(this,r+2,r+5),b(this,r+3,r+4);return this},f.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?Y(this,0,t):E.apply(this,arguments)},f.prototype.equals=function(t){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===f.compare(this,t)},f.prototype.inspect=function(){var t="",r=exports.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),"<Buffer "+t+">"},f.prototype.compare=function(t,r,e,n,i){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),u=(e>>>=0)-(r>>>=0),s=Math.min(o,u),h=this.slice(n,i),a=t.slice(r,e),c=0;c<s;++c)if(h[c]!==a[c]){o=h[c],u=a[c];break}return o<u?-1:u<o?1:0},f.prototype.includes=function(t,r,e){return-1!==this.indexOf(t,r,e)},f.prototype.indexOf=function(t,r,e){return R(this,t,r,e,!0)},f.prototype.lastIndexOf=function(t,r,e){return R(this,t,r,e,!1)},f.prototype.write=function(t,r,e,n){if(void 0===r)n="utf8",e=this.length,r=0;else if(void 0===e&&"string"==typeof r)n=r,e=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(e)?(e|=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var i=this.length-r;if((void 0===e||e>i)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return A(this,t,r,e);case"utf8":case"utf-8":return m(this,t,r,e);case"ascii":return P(this,t,r,e);case"latin1":case"binary":return T(this,t,r,e);case"base64":return B(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;function O(t){var r=t.length;if(r<=I)return String.fromCharCode.apply(String,t);for(var e="",n=0;n<r;)e+=String.fromCharCode.apply(String,t.slice(n,n+=I));return e}function L(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;i<e;++i)n+=String.fromCharCode(127&t[i]);return n}function D(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;i<e;++i)n+=String.fromCharCode(t[i]);return n}function x(t,r,e){var n=t.length;(!r||r<0)&&(r=0),(!e||e<0||e>n)&&(e=n);for(var i="",o=r;o<e;++o)i+=Z(t[o]);return i}function C(t,r,e){for(var n=t.slice(r,e),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function M(t,r,e){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+r>e)throw new RangeError("Trying to access beyond buffer length")}function k(t,r,e,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||r<o)throw new RangeError('"value" argument is out of bounds');if(e+n>t.length)throw new RangeError("Index out of range")}function N(t,r,e,n){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-e,2);i<o;++i)t[e+i]=(r&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function z(t,r,e,n){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-e,4);i<o;++i)t[e+i]=r>>>8*(n?i:3-i)&255}function F(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function j(t,r,n,i,o){return o||F(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),e.write(t,r,n,i,23,4),n+4}function q(t,r,n,i,o){return o||F(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),e.write(t,r,n,i,52,8),n+8}f.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r<t&&(r=t),f.TYPED_ARRAY_SUPPORT)(e=this.subarray(t,r)).__proto__=f.prototype;else{var i=r-t;e=new f(i,void 0);for(var o=0;o<i;++o)e[o]=this[o+t]}return e},f.prototype.readUIntLE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n},f.prototype.readUIntBE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},f.prototype.readUInt8=function(t,r){return r||M(t,1,this.length),this[t]},f.prototype.readUInt16LE=function(t,r){return r||M(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUInt16BE=function(t,r){return r||M(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUInt32LE=function(t,r){return r||M(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUInt32BE=function(t,r){return r||M(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*r)),n},f.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},f.prototype.readInt8=function(t,r){return r||M(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,r){r||M(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt16BE=function(t,r){r||M(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt32LE=function(t,r){return r||M(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,r){return r||M(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readFloatLE=function(t,r){return r||M(t,4,this.length),e.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,r){return r||M(t,4,this.length),e.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,r){return r||M(t,8,this.length),e.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,r){return r||M(t,8,this.length),e.read(this,t,!1,52,8)},f.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||k(this,t,r,e,Math.pow(2,8*e)-1,0);var i=1,o=0;for(this[r]=255&t;++o<e&&(i*=256);)this[r+o]=t/i&255;return r+e},f.prototype.writeUIntBE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||k(this,t,r,e,Math.pow(2,8*e)-1,0);var i=e-1,o=1;for(this[r+i]=255&t;--i>=0&&(o*=256);)this[r+i]=t/o&255;return r+e},f.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,1,255,0),f.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},f.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):N(this,t,r,!0),r+2},f.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):N(this,t,r,!1),r+2},f.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):z(this,t,r,!0),r+4},f.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):z(this,t,r,!1),r+4},f.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);k(this,t,r,e,i-1,-i)}var o=0,u=1,f=0;for(this[r]=255&t;++o<e&&(u*=256);)t<0&&0===f&&0!==this[r+o-1]&&(f=1),this[r+o]=(t/u>>0)-f&255;return r+e},f.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);k(this,t,r,e,i-1,-i)}var o=e-1,u=1,f=0;for(this[r+o]=255&t;--o>=0&&(u*=256);)t<0&&0===f&&0!==this[r+o+1]&&(f=1),this[r+o]=(t/u>>0)-f&255;return r+e},f.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,1,127,-128),f.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},f.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):N(this,t,r,!0),r+2},f.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):N(this,t,r,!1),r+2},f.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,2147483647,-2147483648),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):z(this,t,r,!0),r+4},f.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):z(this,t,r,!1),r+4},f.prototype.writeFloatLE=function(t,r,e){return j(this,t,r,!0,e)},f.prototype.writeFloatBE=function(t,r,e){return j(this,t,r,!1,e)},f.prototype.writeDoubleLE=function(t,r,e){return q(this,t,r,!0,e)},f.prototype.writeDoubleBE=function(t,r,e){return q(this,t,r,!1,e)},f.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-e&&(n=t.length-r+e);var i,o=n-e;if(this===t&&e<r&&r<n)for(i=o-1;i>=0;--i)t[i+r]=this[i+e];else if(o<1e3||!f.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)t[i+r]=this[i+e];else Uint8Array.prototype.set.call(t,this.subarray(e,e+o),r);return o},f.prototype.fill=function(t,r,e,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,e=this.length):"string"==typeof e&&(n=e,e=this.length),1===t.length){var i=t.charCodeAt(0);i<256&&(t=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!f.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var o;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(o=r;o<e;++o)this[o]=t;else{var u=f.isBuffer(t)?t:$(new f(t,n).toString()),s=u.length;for(o=0;o<e-r;++o)this[o+r]=u[o%s]}return this};var V=/[^+\/0-9A-Za-z-_]/g;function X(t){if((t=J(t).replace(V,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}function J(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function Z(t){return t<16?"0"+t.toString(16):t.toString(16)}function $(t,r){var e;r=r||1/0;for(var n=t.length,i=null,o=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function G(t){for(var r=[],e=0;e<t.length;++e)r.push(255&t.charCodeAt(e));return r}function H(t,r){for(var e,n,i,o=[],u=0;u<t.length&&!((r-=2)<0);++u)n=(e=t.charCodeAt(u))>>8,i=e%256,o.push(i),o.push(n);return o}function K(t){return r.toByteArray(X(t))}function Q(t,r,e,n){for(var i=0;i<n&&!(i+e>=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function W(t){return t!=t}
},{"base64-js":"FRly","ieee754":"Quj6","isarray":"aqZJ","buffer":"aMB2"}],"HJaA":[function(require,module,exports) {
var global = arguments[3];
var Buffer = require("buffer").Buffer;
var define;
var n,t=arguments[3],r=require("buffer").Buffer;(function(){var r,e=200,u="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",i="Expected a function",o="Invalid `variable` option passed into `_.template`",f="__lodash_hash_undefined__",a=500,c="__lodash_placeholder__",l=1,s=2,h=4,p=1,v=2,_=1,g=2,y=4,d=8,b=16,w=32,m=64,x=128,j=256,A=512,k=30,O="...",I=800,R=16,E=1,z=2,S=1/0,L=9007199254740991,W=1.7976931348623157e308,C=NaN,B=4294967295,U=B-1,T=B>>>1,D=[["ary",x],["bind",_],["bindKey",g],["curry",d],["curryRight",b],["flip",A],["partial",w],["partialRight",m],["rearg",j]],$="[object Arguments]",M="[object Array]",F="[object AsyncFunction]",N="[object Boolean]",P="[object Date]",q="[object DOMException]",Z="[object Error]",K="[object Function]",V="[object GeneratorFunction]",G="[object Map]",H="[object Number]",J="[object Null]",Y="[object Object]",Q="[object Proxy]",X="[object RegExp]",nn="[object Set]",tn="[object String]",rn="[object Symbol]",en="[object Undefined]",un="[object WeakMap]",on="[object WeakSet]",fn="[object ArrayBuffer]",an="[object DataView]",cn="[object Float32Array]",ln="[object Float64Array]",sn="[object Int8Array]",hn="[object Int16Array]",pn="[object Int32Array]",vn="[object Uint8Array]",_n="[object Uint8ClampedArray]",gn="[object Uint16Array]",yn="[object Uint32Array]",dn=/\b__p \+= '';/g,bn=/\b(__p \+=) '' \+/g,wn=/(__e\(.*?\)|\b__t\)) \+\n'';/g,mn=/&(?:amp|lt|gt|quot|#39);/g,xn=/[&<>"']/g,jn=RegExp(mn.source),An=RegExp(xn.source),kn=/<%-([\s\S]+?)%>/g,On=/<%([\s\S]+?)%>/g,In=/<%=([\s\S]+?)%>/g,Rn=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,En=/^\w*$/,zn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Sn=/[\\^$.*+?()[\]{}|]/g,Ln=RegExp(Sn.source),Wn=/^\s+/,Cn=/\s/,Bn=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,Un=/\{\n\/\* \[wrapped with (.+)\] \*/,Tn=/,? & /,Dn=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,$n=/[()=,{}\[\]\/\s]/,Mn=/\\(\\)?/g,Fn=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Nn=/\w*$/,Pn=/^[-+]0x[0-9a-f]+$/i,qn=/^0b[01]+$/i,Zn=/^\[object .+?Constructor\]$/,Kn=/^0o[0-7]+$/i,Vn=/^(?:0|[1-9]\d*)$/,Gn=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Hn=/($^)/,Jn=/['\n\r\u2028\u2029\\]/g,Yn="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",Qn="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",Xn="[\\ud800-\\udfff]",nt="["+Qn+"]",tt="["+Yn+"]",rt="\\d+",et="[\\u2700-\\u27bf]",ut="[a-z\\xdf-\\xf6\\xf8-\\xff]",it="[^\\ud800-\\udfff"+Qn+rt+"\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde]",ot="\\ud83c[\\udffb-\\udfff]",ft="[^\\ud800-\\udfff]",at="(?:\\ud83c[\\udde6-\\uddff]){2}",ct="[\\ud800-\\udbff][\\udc00-\\udfff]",lt="[A-Z\\xc0-\\xd6\\xd8-\\xde]",st="(?:"+ut+"|"+it+")",ht="(?:"+lt+"|"+it+")",pt="(?:"+tt+"|"+ot+")"+"?",vt="[\\ufe0e\\ufe0f]?"+pt+("(?:\\u200d(?:"+[ft,at,ct].join("|")+")[\\ufe0e\\ufe0f]?"+pt+")*"),_t="(?:"+[et,at,ct].join("|")+")"+vt,gt="(?:"+[ft+tt+"?",tt,at,ct,Xn].join("|")+")",yt=RegExp("['’]","g"),dt=RegExp(tt,"g"),bt=RegExp(ot+"(?="+ot+")|"+gt+vt,"g"),wt=RegExp([lt+"?"+ut+"+(?:['’](?:d|ll|m|re|s|t|ve))?(?="+[nt,lt,"$"].join("|")+")",ht+"+(?:['’](?:D|LL|M|RE|S|T|VE))?(?="+[nt,lt+st,"$"].join("|")+")",lt+"?"+st+"+(?:['’](?:d|ll|m|re|s|t|ve))?",lt+"+(?:['’](?:D|LL|M|RE|S|T|VE))?","\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",rt,_t].join("|"),"g"),mt=RegExp("[\\u200d\\ud800-\\udfff"+Yn+"\\ufe0e\\ufe0f]"),xt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,jt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],At=-1,kt={};kt[cn]=kt[ln]=kt[sn]=kt[hn]=kt[pn]=kt[vn]=kt[_n]=kt[gn]=kt[yn]=!0,kt[$]=kt[M]=kt[fn]=kt[N]=kt[an]=kt[P]=kt[Z]=kt[K]=kt[G]=kt[H]=kt[Y]=kt[X]=kt[nn]=kt[tn]=kt[un]=!1;var Ot={};Ot[$]=Ot[M]=Ot[fn]=Ot[an]=Ot[N]=Ot[P]=Ot[cn]=Ot[ln]=Ot[sn]=Ot[hn]=Ot[pn]=Ot[G]=Ot[H]=Ot[Y]=Ot[X]=Ot[nn]=Ot[tn]=Ot[rn]=Ot[vn]=Ot[_n]=Ot[gn]=Ot[yn]=!0,Ot[Z]=Ot[K]=Ot[un]=!1;var It={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Rt=parseFloat,Et=parseInt,zt="object"==typeof t&&t&&t.Object===Object&&t,St="object"==typeof self&&self&&self.Object===Object&&self,Lt=zt||St||Function("return this")(),Wt="object"==typeof exports&&exports&&!exports.nodeType&&exports,Ct=Wt&&"object"==typeof module&&module&&!module.nodeType&&module,Bt=Ct&&Ct.exports===Wt,Ut=Bt&&zt.process,Tt=function(){try{var n=Ct&&Ct.require&&Ct.require("util").types;return n||Ut&&Ut.binding&&Ut.binding("util")}catch(t){}}(),Dt=Tt&&Tt.isArrayBuffer,$t=Tt&&Tt.isDate,Mt=Tt&&Tt.isMap,Ft=Tt&&Tt.isRegExp,Nt=Tt&&Tt.isSet,Pt=Tt&&Tt.isTypedArray;function qt(n,t,r){switch(r.length){case 0:return n.call(t);case 1:return n.call(t,r[0]);case 2:return n.call(t,r[0],r[1]);case 3:return n.call(t,r[0],r[1],r[2])}return n.apply(t,r)}function Zt(n,t,r,e){for(var u=-1,i=null==n?0:n.length;++u<i;){var o=n[u];t(e,o,r(o),n)}return e}function Kt(n,t){for(var r=-1,e=null==n?0:n.length;++r<e&&!1!==t(n[r],r,n););return n}function Vt(n,t){for(var r=null==n?0:n.length;r--&&!1!==t(n[r],r,n););return n}function Gt(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(!t(n[r],r,n))return!1;return!0}function Ht(n,t){for(var r=-1,e=null==n?0:n.length,u=0,i=[];++r<e;){var o=n[r];t(o,r,n)&&(i[u++]=o)}return i}function Jt(n,t){return!!(null==n?0:n.length)&&or(n,t,0)>-1}function Yt(n,t,r){for(var e=-1,u=null==n?0:n.length;++e<u;)if(r(t,n[e]))return!0;return!1}function Qt(n,t){for(var r=-1,e=null==n?0:n.length,u=Array(e);++r<e;)u[r]=t(n[r],r,n);return u}function Xt(n,t){for(var r=-1,e=t.length,u=n.length;++r<e;)n[u+r]=t[r];return n}function nr(n,t,r,e){var u=-1,i=null==n?0:n.length;for(e&&i&&(r=n[++u]);++u<i;)r=t(r,n[u],u,n);return r}function tr(n,t,r,e){var u=null==n?0:n.length;for(e&&u&&(r=n[--u]);u--;)r=t(r,n[u],u,n);return r}function rr(n,t){for(var r=-1,e=null==n?0:n.length;++r<e;)if(t(n[r],r,n))return!0;return!1}var er=lr("length");function ur(n,t,r){var e;return r(n,function(n,r,u){if(t(n,r,u))return e=r,!1}),e}function ir(n,t,r,e){for(var u=n.length,i=r+(e?1:-1);e?i--:++i<u;)if(t(n[i],i,n))return i;return-1}function or(n,t,r){return t==t?function(n,t,r){var e=r-1,u=n.length;for(;++e<u;)if(n[e]===t)return e;return-1}(n,t,r):ir(n,ar,r)}function fr(n,t,r,e){for(var u=r-1,i=n.length;++u<i;)if(e(n[u],t))return u;return-1}function ar(n){return n!=n}function cr(n,t){var r=null==n?0:n.length;return r?pr(n,t)/r:C}function lr(n){return function(t){return null==t?r:t[n]}}function sr(n){return function(t){return null==n?r:n[t]}}function hr(n,t,r,e,u){return u(n,function(n,u,i){r=e?(e=!1,n):t(r,n,u,i)}),r}function pr(n,t){for(var e,u=-1,i=n.length;++u<i;){var o=t(n[u]);o!==r&&(e=e===r?o:e+o)}return e}function vr(n,t){for(var r=-1,e=Array(n);++r<n;)e[r]=t(r);return e}function _r(n){return n?n.slice(0,Lr(n)+1).replace(Wn,""):n}function gr(n){return function(t){return n(t)}}function yr(n,t){return Qt(t,function(t){return n[t]})}function dr(n,t){return n.has(t)}function br(n,t){for(var r=-1,e=n.length;++r<e&&or(t,n[r],0)>-1;);return r}function wr(n,t){for(var r=n.length;r--&&or(t,n[r],0)>-1;);return r}var mr=sr({"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"}),xr=sr({"&":"&","<":"<",">":">",'"':""","'":"'"});function jr(n){return"\\"+It[n]}function Ar(n){return mt.test(n)}function kr(n){var t=-1,r=Array(n.size);return n.forEach(function(n,e){r[++t]=[e,n]}),r}function Or(n,t){return function(r){return n(t(r))}}function Ir(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r];o!==t&&o!==c||(n[r]=c,i[u++]=r)}return i}function Rr(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=n}),r}function Er(n){var t=-1,r=Array(n.size);return n.forEach(function(n){r[++t]=[n,n]}),r}function zr(n){return Ar(n)?function(n){var t=bt.lastIndex=0;for(;bt.test(n);)++t;return t}(n):er(n)}function Sr(n){return Ar(n)?function(n){return n.match(bt)||[]}(n):function(n){return n.split("")}(n)}function Lr(n){for(var t=n.length;t--&&Cn.test(n.charAt(t)););return t}var Wr=sr({"&":"&","<":"<",">":">",""":'"',"'":"'"});var Cr=function n(t){var Cn,Yn=(t=null==t?Lt:Cr.defaults(Lt.Object(),t,Cr.pick(Lt,jt))).Array,Qn=t.Date,Xn=t.Error,nt=t.Function,tt=t.Math,rt=t.Object,et=t.RegExp,ut=t.String,it=t.TypeError,ot=Yn.prototype,ft=nt.prototype,at=rt.prototype,ct=t["__core-js_shared__"],lt=ft.toString,st=at.hasOwnProperty,ht=0,pt=(Cn=/[^.]+$/.exec(ct&&ct.keys&&ct.keys.IE_PROTO||""))?"Symbol(src)_1."+Cn:"",vt=at.toString,_t=lt.call(rt),gt=Lt._,bt=et("^"+lt.call(st).replace(Sn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),mt=Bt?t.Buffer:r,It=t.Symbol,zt=t.Uint8Array,St=mt?mt.allocUnsafe:r,Wt=Or(rt.getPrototypeOf,rt),Ct=rt.create,Ut=at.propertyIsEnumerable,Tt=ot.splice,er=It?It.isConcatSpreadable:r,sr=It?It.iterator:r,Br=It?It.toStringTag:r,Ur=function(){try{var n=Mi(rt,"defineProperty");return n({},"",{}),n}catch(t){}}(),Tr=t.clearTimeout!==Lt.clearTimeout&&t.clearTimeout,Dr=Qn&&Qn.now!==Lt.Date.now&&Qn.now,$r=t.setTimeout!==Lt.setTimeout&&t.setTimeout,Mr=tt.ceil,Fr=tt.floor,Nr=rt.getOwnPropertySymbols,Pr=mt?mt.isBuffer:r,qr=t.isFinite,Zr=ot.join,Kr=Or(rt.keys,rt),Vr=tt.max,Gr=tt.min,Hr=Qn.now,Jr=t.parseInt,Yr=tt.random,Qr=ot.reverse,Xr=Mi(t,"DataView"),ne=Mi(t,"Map"),te=Mi(t,"Promise"),re=Mi(t,"Set"),ee=Mi(t,"WeakMap"),ue=Mi(rt,"create"),ie=ee&&new ee,oe={},fe=ho(Xr),ae=ho(ne),ce=ho(te),le=ho(re),se=ho(ee),he=It?It.prototype:r,pe=he?he.valueOf:r,ve=he?he.toString:r;function _e(n){if(Sf(n)&&!wf(n)&&!(n instanceof be)){if(n instanceof de)return n;if(st.call(n,"__wrapped__"))return po(n)}return new de(n)}var ge=function(){function n(){}return function(t){if(!zf(t))return{};if(Ct)return Ct(t);n.prototype=t;var e=new n;return n.prototype=r,e}}();function ye(){}function de(n,t){this.__wrapped__=n,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=r}function be(n){this.__wrapped__=n,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=B,this.__views__=[]}function we(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function me(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function xe(n){var t=-1,r=null==n?0:n.length;for(this.clear();++t<r;){var e=n[t];this.set(e[0],e[1])}}function je(n){var t=-1,r=null==n?0:n.length;for(this.__data__=new xe;++t<r;)this.add(n[t])}function Ae(n){var t=this.__data__=new me(n);this.size=t.size}function ke(n,t){var r=wf(n),e=!r&&bf(n),u=!r&&!e&&Af(n),i=!r&&!e&&!u&&$f(n),o=r||e||u||i,f=o?vr(n.length,ut):[],a=f.length;for(var c in n)!t&&!st.call(n,c)||o&&("length"==c||u&&("offset"==c||"parent"==c)||i&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Vi(c,a))||f.push(c);return f}function Oe(n){var t=n.length;return t?n[ju(0,t-1)]:r}function Ie(n,t){return co(ui(n),Ue(t,0,n.length))}function Re(n){return co(ui(n))}function Ee(n,t,e){(e===r||gf(n[t],e))&&(e!==r||t in n)||Ce(n,t,e)}function ze(n,t,e){var u=n[t];st.call(n,t)&&gf(u,e)&&(e!==r||t in n)||Ce(n,t,e)}function Se(n,t){for(var r=n.length;r--;)if(gf(n[r][0],t))return r;return-1}function Le(n,t,r,e){return Fe(n,function(n,u,i){t(e,n,r(n),i)}),e}function We(n,t){return n&&ii(t,fa(t),n)}function Ce(n,t,r){"__proto__"==t&&Ur?Ur(n,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):n[t]=r}function Be(n,t){for(var e=-1,u=t.length,i=Yn(u),o=null==n;++e<u;)i[e]=o?r:ra(n,t[e]);return i}function Ue(n,t,e){return n==n&&(e!==r&&(n=n<=e?n:e),t!==r&&(n=n>=t?n:t)),n}function Te(n,t,e,u,i,o){var f,a=t&l,c=t&s,p=t&h;if(e&&(f=i?e(n,u,i,o):e(n)),f!==r)return f;if(!zf(n))return n;var v=wf(n);if(v){if(f=function(n){var t=n.length,r=new n.constructor(t);return t&&"string"==typeof n[0]&&st.call(n,"index")&&(r.index=n.index,r.input=n.input),r}(n),!a)return ui(n,f)}else{var _=Pi(n),g=_==K||_==V;if(Af(n))return Qu(n,a);if(_==Y||_==$||g&&!i){if(f=c||g?{}:Zi(n),!a)return c?function(n,t){return ii(n,Ni(n),t)}(n,function(n,t){return n&&ii(t,aa(t),n)}(f,n)):function(n,t){return ii(n,Fi(n),t)}(n,We(f,n))}else{if(!Ot[_])return i?n:{};f=function(n,t,r){var e,u,i,o=n.constructor;switch(t){case fn:return Xu(n);case N:case P:return new o(+n);case an:return function(n,t){var r=t?Xu(n.buffer):n.buffer;return new n.constructor(r,n.byteOffset,n.byteLength)}(n,r);case cn:case ln:case sn:case hn:case pn:case vn:case _n:case gn:case yn:return ni(n,r);case G:return new o;case H:case tn:return new o(n);case X:return(i=new(u=n).constructor(u.source,Nn.exec(u))).lastIndex=u.lastIndex,i;case nn:return new o;case rn:return e=n,pe?rt(pe.call(e)):{}}}(n,_,a)}}o||(o=new Ae);var y=o.get(n);if(y)return y;o.set(n,f),Uf(n)?n.forEach(function(r){f.add(Te(r,t,e,r,n,o))}):Lf(n)&&n.forEach(function(r,u){f.set(u,Te(r,t,e,u,n,o))});var d=v?r:(p?c?Wi:Li:c?aa:fa)(n);return Kt(d||n,function(r,u){d&&(r=n[u=r]),ze(f,u,Te(r,t,e,u,n,o))}),f}function De(n,t,e){var u=e.length;if(null==n)return!u;for(n=rt(n);u--;){var i=e[u],o=t[i],f=n[i];if(f===r&&!(i in n)||!o(f))return!1}return!0}function $e(n,t,e){if("function"!=typeof n)throw new it(i);return io(function(){n.apply(r,e)},t)}function Me(n,t,r,u){var i=-1,o=Jt,f=!0,a=n.length,c=[],l=t.length;if(!a)return c;r&&(t=Qt(t,gr(r))),u?(o=Yt,f=!1):t.length>=e&&(o=dr,f=!1,t=new je(t));n:for(;++i<a;){var s=n[i],h=null==r?s:r(s);if(s=u||0!==s?s:0,f&&h==h){for(var p=l;p--;)if(t[p]===h)continue n;c.push(s)}else o(t,h,u)||c.push(s)}return c}_e.templateSettings={escape:kn,evaluate:On,interpolate:In,variable:"",imports:{_:_e}},_e.prototype=ye.prototype,_e.prototype.constructor=_e,de.prototype=ge(ye.prototype),de.prototype.constructor=de,be.prototype=ge(ye.prototype),be.prototype.constructor=be,we.prototype.clear=function(){this.__data__=ue?ue(null):{},this.size=0},we.prototype.delete=function(n){var t=this.has(n)&&delete this.__data__[n];return this.size-=t?1:0,t},we.prototype.get=function(n){var t=this.__data__;if(ue){var e=t[n];return e===f?r:e}return st.call(t,n)?t[n]:r},we.prototype.has=function(n){var t=this.__data__;return ue?t[n]!==r:st.call(t,n)},we.prototype.set=function(n,t){var e=this.__data__;return this.size+=this.has(n)?0:1,e[n]=ue&&t===r?f:t,this},me.prototype.clear=function(){this.__data__=[],this.size=0},me.prototype.delete=function(n){var t=this.__data__,r=Se(t,n);return!(r<0||(r==t.length-1?t.pop():Tt.call(t,r,1),--this.size,0))},me.prototype.get=function(n){var t=this.__data__,e=Se(t,n);return e<0?r:t[e][1]},me.prototype.has=function(n){return Se(this.__data__,n)>-1},me.prototype.set=function(n,t){var r=this.__data__,e=Se(r,n);return e<0?(++this.size,r.push([n,t])):r[e][1]=t,this},xe.prototype.clear=function(){this.size=0,this.__data__={hash:new we,map:new(ne||me),string:new we}},xe.prototype.delete=function(n){var t=Di(this,n).delete(n);return this.size-=t?1:0,t},xe.prototype.get=function(n){return Di(this,n).get(n)},xe.prototype.has=function(n){return Di(this,n).has(n)},xe.prototype.set=function(n,t){var r=Di(this,n),e=r.size;return r.set(n,t),this.size+=r.size==e?0:1,this},je.prototype.add=je.prototype.push=function(n){return this.__data__.set(n,f),this},je.prototype.has=function(n){return this.__data__.has(n)},Ae.prototype.clear=function(){this.__data__=new me,this.size=0},Ae.prototype.delete=function(n){var t=this.__data__,r=t.delete(n);return this.size=t.size,r},Ae.prototype.get=function(n){return this.__data__.get(n)},Ae.prototype.has=function(n){return this.__data__.has(n)},Ae.prototype.set=function(n,t){var r=this.__data__;if(r instanceof me){var u=r.__data__;if(!ne||u.length<e-1)return u.push([n,t]),this.size=++r.size,this;r=this.__data__=new xe(u)}return r.set(n,t),this.size=r.size,this};var Fe=ai(He),Ne=ai(Je,!0);function Pe(n,t){var r=!0;return Fe(n,function(n,e,u){return r=!!t(n,e,u)}),r}function qe(n,t,e){for(var u=-1,i=n.length;++u<i;){var o=n[u],f=t(o);if(null!=f&&(a===r?f==f&&!Df(f):e(f,a)))var a=f,c=o}return c}function Ze(n,t){var r=[];return Fe(n,function(n,e,u){t(n,e,u)&&r.push(n)}),r}function Ke(n,t,r,e,u){var i=-1,o=n.length;for(r||(r=Ki),u||(u=[]);++i<o;){var f=n[i];t>0&&r(f)?t>1?Ke(f,t-1,r,e,u):Xt(u,f):e||(u[u.length]=f)}return u}var Ve=ci(),Ge=ci(!0);function He(n,t){return n&&Ve(n,t,fa)}function Je(n,t){return n&&Ge(n,t,fa)}function Ye(n,t){return Ht(t,function(t){return If(n[t])})}function Qe(n,t){for(var e=0,u=(t=Gu(t,n)).length;null!=n&&e<u;)n=n[so(t[e++])];return e&&e==u?n:r}function Xe(n,t,r){var e=t(n);return wf(n)?e:Xt(e,r(n))}function nu(n){return null==n?n===r?en:J:Br&&Br in rt(n)?function(n){var t=st.call(n,Br),e=n[Br];try{n[Br]=r;var u=!0}catch(o){}var i=vt.call(n);return u&&(t?n[Br]=e:delete n[Br]),i}(n):function(n){return vt.call(n)}(n)}function tu(n,t){return n>t}function ru(n,t){return null!=n&&st.call(n,t)}function eu(n,t){return null!=n&&t in rt(n)}function uu(n,t,e){for(var u=e?Yt:Jt,i=n[0].length,o=n.length,f=o,a=Yn(o),c=1/0,l=[];f--;){var s=n[f];f&&t&&(s=Qt(s,gr(t))),c=Gr(s.length,c),a[f]=!e&&(t||i>=120&&s.length>=120)?new je(f&&s):r}s=n[0];var h=-1,p=a[0];n:for(;++h<i&&l.length<c;){var v=s[h],_=t?t(v):v;if(v=e||0!==v?v:0,!(p?dr(p,_):u(l,_,e))){for(f=o;--f;){var g=a[f];if(!(g?dr(g,_):u(n[f],_,e)))continue n}p&&p.push(_),l.push(v)}}return l}function iu(n,t,e){var u=null==(n=ro(n,t=Gu(t,n)))?n:n[so(ko(t))];return null==u?r:qt(u,n,e)}function ou(n){return Sf(n)&&nu(n)==$}function fu(n,t,e,u,i){return n===t||(null==n||null==t||!Sf(n)&&!Sf(t)?n!=n&&t!=t:function(n,t,e,u,i,o){var f=wf(n),a=wf(t),c=f?M:Pi(n),l=a?M:Pi(t),s=(c=c==$?Y:c)==Y,h=(l=l==$?Y:l)==Y,_=c==l;if(_&&Af(n)){if(!Af(t))return!1;f=!0,s=!1}if(_&&!s)return o||(o=new Ae),f||$f(n)?zi(n,t,e,u,i,o):function(n,t,r,e,u,i,o){switch(r){case an:if(n.byteLength!=t.byteLength||n.byteOffset!=t.byteOffset)return!1;n=n.buffer,t=t.buffer;case fn:return!(n.byteLength!=t.byteLength||!i(new zt(n),new zt(t)));case N:case P:case H:return gf(+n,+t);case Z:return n.name==t.name&&n.message==t.message;case X:case tn:return n==t+"";case G:var f=kr;case nn:var a=e&p;if(f||(f=Rr),n.size!=t.size&&!a)return!1;var c=o.get(n);if(c)return c==t;e|=v,o.set(n,t);var l=zi(f(n),f(t),e,u,i,o);return o.delete(n),l;case rn:if(pe)return pe.call(n)==pe.call(t)}return!1}(n,t,c,e,u,i,o);if(!(e&p)){var g=s&&st.call(n,"__wrapped__"),y=h&&st.call(t,"__wrapped__");if(g||y){var d=g?n.value():n,b=y?t.value():t;return o||(o=new Ae),i(d,b,e,u,o)}}return!!_&&(o||(o=new Ae),function(n,t,e,u,i,o){var f=e&p,a=Li(n),c=a.length,l=Li(t).length;if(c!=l&&!f)return!1;for(var s=c;s--;){var h=a[s];if(!(f?h in t:st.call(t,h)))return!1}var v=o.get(n),_=o.get(t);if(v&&_)return v==t&&_==n;var g=!0;o.set(n,t),o.set(t,n);for(var y=f;++s<c;){h=a[s];var d=n[h],b=t[h];if(u)var w=f?u(b,d,h,t,n,o):u(d,b,h,n,t,o);if(!(w===r?d===b||i(d,b,e,u,o):w)){g=!1;break}y||(y="constructor"==h)}if(g&&!y){var m=n.constructor,x=t.constructor;m!=x&&"constructor"in n&&"constructor"in t&&!("function"==typeof m&&m instanceof m&&"function"==typeof x&&x instanceof x)&&(g=!1)}return o.delete(n),o.delete(t),g}(n,t,e,u,i,o))}(n,t,e,u,fu,i))}function au(n,t,e,u){var i=e.length,o=i,f=!u;if(null==n)return!o;for(n=rt(n);i--;){var a=e[i];if(f&&a[2]?a[1]!==n[a[0]]:!(a[0]in n))return!1}for(;++i<o;){var c=(a=e[i])[0],l=n[c],s=a[1];if(f&&a[2]){if(l===r&&!(c in n))return!1}else{var h=new Ae;if(u)var _=u(l,s,c,n,t,h);if(!(_===r?fu(s,l,p|v,u,h):_))return!1}}return!0}function cu(n){return!(!zf(n)||(t=n,pt&&pt in t))&&(If(n)?bt:Zn).test(ho(n));var t}function lu(n){return"function"==typeof n?n:null==n?Wa:"object"==typeof n?wf(n)?gu(n[0],n[1]):_u(n):Na(n)}function su(n){if(!Qi(n))return Kr(n);var t=[];for(var r in rt(n))st.call(n,r)&&"constructor"!=r&&t.push(r);return t}function hu(n){if(!zf(n))return function(n){var t=[];if(null!=n)for(var r in rt(n))t.push(r);return t}(n);var t=Qi(n),r=[];for(var e in n)("constructor"!=e||!t&&st.call(n,e))&&r.push(e);return r}function pu(n,t){return n<t}function vu(n,t){var r=-1,e=xf(n)?Yn(n.length):[];return Fe(n,function(n,u,i){e[++r]=t(n,u,i)}),e}function _u(n){var t=$i(n);return 1==t.length&&t[0][2]?no(t[0][0],t[0][1]):function(r){return r===n||au(r,n,t)}}function gu(n,t){return Hi(n)&&Xi(t)?no(so(n),t):function(e){var u=ra(e,n);return u===r&&u===t?ea(e,n):fu(t,u,p|v)}}function yu(n,t,e,u,i){n!==t&&Ve(t,function(o,f){if(i||(i=new Ae),zf(o))!function(n,t,e,u,i,o,f){var a=eo(n,e),c=eo(t,e),l=f.get(c);if(l)Ee(n,e,l);else{var s=o?o(a,c,e+"",n,t,f):r,h=s===r;if(h){var p=wf(c),v=!p&&Af(c),_=!p&&!v&&$f(c);s=c,p||v||_?wf(a)?s=a:jf(a)?s=ui(a):v?(h=!1,s=Qu(c,!0)):_?(h=!1,s=ni(c,!0)):s=[]:Cf(c)||bf(c)?(s=a,bf(a)?s=Vf(a):zf(a)&&!If(a)||(s=Zi(c))):h=!1}h&&(f.set(c,s),i(s,c,u,o,f),f.delete(c)),Ee(n,e,s)}}(n,t,f,e,yu,u,i);else{var a=u?u(eo(n,f),o,f+"",n,t,i):r;a===r&&(a=o),Ee(n,f,a)}},aa)}function du(n,t){var e=n.length;if(e)return Vi(t+=t<0?e:0,e)?n[t]:r}function bu(n,t,r){t=t.length?Qt(t,function(n){return wf(n)?function(t){return Qe(t,1===n.length?n[0]:n)}:n}):[Wa];var e=-1;return t=Qt(t,gr(Ti())),function(n,t){var r=n.length;for(n.sort(t);r--;)n[r]=n[r].value;return n}(vu(n,function(n,r,u){return{criteria:Qt(t,function(t){return t(n)}),index:++e,value:n}}),function(n,t){return function(n,t,r){for(var e=-1,u=n.criteria,i=t.criteria,o=u.length,f=r.length;++e<o;){var a=ti(u[e],i[e]);if(a){if(e>=f)return a;var c=r[e];return a*("desc"==c?-1:1)}}return n.index-t.index}(n,t,r)})}function wu(n,t,r){for(var e=-1,u=t.length,i={};++e<u;){var o=t[e],f=Qe(n,o);r(f,o)&&Ru(i,Gu(o,n),f)}return i}function mu(n,t,r,e){var u=e?fr:or,i=-1,o=t.length,f=n;for(n===t&&(t=ui(t)),r&&(f=Qt(n,gr(r)));++i<o;)for(var a=0,c=t[i],l=r?r(c):c;(a=u(f,l,a,e))>-1;)f!==n&&Tt.call(f,a,1),Tt.call(n,a,1);return n}function xu(n,t){for(var r=n?t.length:0,e=r-1;r--;){var u=t[r];if(r==e||u!==i){var i=u;Vi(u)?Tt.call(n,u,1):Mu(n,u)}}return n}function ju(n,t){return n+Fr(Yr()*(t-n+1))}function Au(n,t){var r="";if(!n||t<1||t>L)return r;do{t%2&&(r+=n),(t=Fr(t/2))&&(n+=n)}while(t);return r}function ku(n,t){return oo(to(n,t,Wa),n+"")}function Ou(n){return Oe(ga(n))}function Iu(n,t){var r=ga(n);return co(r,Ue(t,0,r.length))}function Ru(n,t,e,u){if(!zf(n))return n;for(var i=-1,o=(t=Gu(t,n)).length,f=o-1,a=n;null!=a&&++i<o;){var c=so(t[i]),l=e;if("__proto__"===c||"constructor"===c||"prototype"===c)return n;if(i!=f){var s=a[c];(l=u?u(s,c,a):r)===r&&(l=zf(s)?s:Vi(t[i+1])?[]:{})}ze(a,c,l),a=a[c]}return n}var Eu=ie?function(n,t){return ie.set(n,t),n}:Wa,zu=Ur?function(n,t){return Ur(n,"toString",{configurable:!0,enumerable:!1,value:za(t),writable:!0})}:Wa;function Su(n){return co(ga(n))}function Lu(n,t,r){var e=-1,u=n.length;t<0&&(t=-t>u?0:u+t),(r=r>u?u:r)<0&&(r+=u),u=t>r?0:r-t>>>0,t>>>=0;for(var i=Yn(u);++e<u;)i[e]=n[e+t];return i}function Wu(n,t){var r;return Fe(n,function(n,e,u){return!(r=t(n,e,u))}),!!r}function Cu(n,t,r){var e=0,u=null==n?e:n.length;if("number"==typeof t&&t==t&&u<=T){for(;e<u;){var i=e+u>>>1,o=n[i];null!==o&&!Df(o)&&(r?o<=t:o<t)?e=i+1:u=i}return u}return Bu(n,t,Wa,r)}function Bu(n,t,e,u){var i=0,o=null==n?0:n.length;if(0===o)return 0;for(var f=(t=e(t))!=t,a=null===t,c=Df(t),l=t===r;i<o;){var s=Fr((i+o)/2),h=e(n[s]),p=h!==r,v=null===h,_=h==h,g=Df(h);if(f)var y=u||_;else y=l?_&&(u||p):a?_&&p&&(u||!v):c?_&&p&&!v&&(u||!g):!v&&!g&&(u?h<=t:h<t);y?i=s+1:o=s}return Gr(o,U)}function Uu(n,t){for(var r=-1,e=n.length,u=0,i=[];++r<e;){var o=n[r],f=t?t(o):o;if(!r||!gf(f,a)){var a=f;i[u++]=0===o?0:o}}return i}function Tu(n){return"number"==typeof n?n:Df(n)?C:+n}function Du(n){if("string"==typeof n)return n;if(wf(n))return Qt(n,Du)+"";if(Df(n))return ve?ve.call(n):"";var t=n+"";return"0"==t&&1/n==-S?"-0":t}function $u(n,t,r){var u=-1,i=Jt,o=n.length,f=!0,a=[],c=a;if(r)f=!1,i=Yt;else if(o>=e){var l=t?null:Ai(n);if(l)return Rr(l);f=!1,i=dr,c=new je}else c=t?[]:a;n:for(;++u<o;){var s=n[u],h=t?t(s):s;if(s=r||0!==s?s:0,f&&h==h){for(var p=c.length;p--;)if(c[p]===h)continue n;t&&c.push(h),a.push(s)}else i(c,h,r)||(c!==a&&c.push(h),a.push(s))}return a}function Mu(n,t){return null==(n=ro(n,t=Gu(t,n)))||delete n[so(ko(t))]}function Fu(n,t,r,e){return Ru(n,t,r(Qe(n,t)),e)}function Nu(n,t,r,e){for(var u=n.length,i=e?u:-1;(e?i--:++i<u)&&t(n[i],i,n););return r?Lu(n,e?0:i,e?i+1:u):Lu(n,e?i+1:0,e?u:i)}function Pu(n,t){var r=n;return r instanceof be&&(r=r.value()),nr(t,function(n,t){return t.func.apply(t.thisArg,Xt([n],t.args))},r)}function qu(n,t,r){var e=n.length;if(e<2)return e?$u(n[0]):[];for(var u=-1,i=Yn(e);++u<e;)for(var o=n[u],f=-1;++f<e;)f!=u&&(i[u]=Me(i[u]||o,n[f],t,r));return $u(Ke(i,1),t,r)}function Zu(n,t,e){for(var u=-1,i=n.length,o=t.length,f={};++u<i;){var a=u<o?t[u]:r;e(f,n[u],a)}return f}function Ku(n){return jf(n)?n:[]}function Vu(n){return"function"==typeof n?n:Wa}function Gu(n,t){return wf(n)?n:Hi(n,t)?[n]:lo(Gf(n))}var Hu=ku;function Ju(n,t,e){var u=n.length;return e=e===r?u:e,!t&&e>=u?n:Lu(n,t,e)}var Yu=Tr||function(n){return Lt.clearTimeout(n)};function Qu(n,t){if(t)return n.slice();var r=n.length,e=St?St(r):new n.constructor(r);return n.copy(e),e}function Xu(n){var t=new n.constructor(n.byteLength);return new zt(t).set(new zt(n)),t}function ni(n,t){var r=t?Xu(n.buffer):n.buffer;return new n.constructor(r,n.byteOffset,n.length)}function ti(n,t){if(n!==t){var e=n!==r,u=null===n,i=n==n,o=Df(n),f=t!==r,a=null===t,c=t==t,l=Df(t);if(!a&&!l&&!o&&n>t||o&&f&&c&&!a&&!l||u&&f&&c||!e&&c||!i)return 1;if(!u&&!o&&!l&&n<t||l&&e&&i&&!u&&!o||a&&e&&i||!f&&i||!c)return-1}return 0}function ri(n,t,r,e){for(var u=-1,i=n.length,o=r.length,f=-1,a=t.length,c=Vr(i-o,0),l=Yn(a+c),s=!e;++f<a;)l[f]=t[f];for(;++u<o;)(s||u<i)&&(l[r[u]]=n[u]);for(;c--;)l[f++]=n[u++];return l}function ei(n,t,r,e){for(var u=-1,i=n.length,o=-1,f=r.length,a=-1,c=t.length,l=Vr(i-f,0),s=Yn(l+c),h=!e;++u<l;)s[u]=n[u];for(var p=u;++a<c;)s[p+a]=t[a];for(;++o<f;)(h||u<i)&&(s[p+r[o]]=n[u++]);return s}function ui(n,t){var r=-1,e=n.length;for(t||(t=Yn(e));++r<e;)t[r]=n[r];return t}function ii(n,t,e,u){var i=!e;e||(e={});for(var o=-1,f=t.length;++o<f;){var a=t[o],c=u?u(e[a],n[a],a,e,n):r;c===r&&(c=n[a]),i?Ce(e,a,c):ze(e,a,c)}return e}function oi(n,t){return function(r,e){var u=wf(r)?Zt:Le,i=t?t():{};return u(r,n,Ti(e,2),i)}}function fi(n){return ku(function(t,e){var u=-1,i=e.length,o=i>1?e[i-1]:r,f=i>2?e[2]:r;for(o=n.length>3&&"function"==typeof o?(i--,o):r,f&&Gi(e[0],e[1],f)&&(o=i<3?r:o,i=1),t=rt(t);++u<i;){var a=e[u];a&&n(t,a,u,o)}return t})}function ai(n,t){return function(r,e){if(null==r)return r;if(!xf(r))return n(r,e);for(var u=r.length,i=t?u:-1,o=rt(r);(t?i--:++i<u)&&!1!==e(o[i],i,o););return r}}function ci(n){return function(t,r,e){for(var u=-1,i=rt(t),o=e(t),f=o.length;f--;){var a=o[n?f:++u];if(!1===r(i[a],a,i))break}return t}}function li(n){return function(t){var e=Ar(t=Gf(t))?Sr(t):r,u=e?e[0]:t.charAt(0),i=e?Ju(e,1).join(""):t.slice(1);return u[n]()+i}}function si(n){return function(t){return nr(Ia(ba(t).replace(yt,"")),n,"")}}function hi(n){return function(){var t=arguments;switch(t.length){case 0:return new n;case 1:return new n(t[0]);case 2:return new n(t[0],t[1]);case 3:return new n(t[0],t[1],t[2]);case 4:return new n(t[0],t[1],t[2],t[3]);case 5:return new n(t[0],t[1],t[2],t[3],t[4]);case 6:return new n(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new n(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=ge(n.prototype),e=n.apply(r,t);return zf(e)?e:r}}function pi(n){return function(t,e,u){var i=rt(t);if(!xf(t)){var o=Ti(e,3);t=fa(t),e=function(n){return o(i[n],n,i)}}var f=n(t,e,u);return f>-1?i[o?t[f]:f]:r}}function vi(n){return Si(function(t){var e=t.length,u=e,o=de.prototype.thru;for(n&&t.reverse();u--;){var f=t[u];if("function"!=typeof f)throw new it(i);if(o&&!a&&"wrapper"==Bi(f))var a=new de([],!0)}for(u=a?u:e;++u<e;){var c=Bi(f=t[u]),l="wrapper"==c?Ci(f):r;a=l&&Ji(l[0])&&l[1]==(x|d|w|j)&&!l[4].length&&1==l[9]?a[Bi(l[0])].apply(a,l[3]):1==f.length&&Ji(f)?a[c]():a.thru(f)}return function(){var n=arguments,r=n[0];if(a&&1==n.length&&wf(r))return a.plant(r).value();for(var u=0,i=e?t[u].apply(this,n):r;++u<e;)i=t[u].call(this,i);return i}})}function _i(n,t,e,u,i,o,f,a,c,l){var s=t&x,h=t&_,p=t&g,v=t&(d|b),y=t&A,w=p?r:hi(n);return function _(){for(var g=arguments.length,d=Yn(g),b=g;b--;)d[b]=arguments[b];if(v)var m=Ui(_),x=function(n,t){for(var r=n.length,e=0;r--;)n[r]===t&&++e;return e}(d,m);if(u&&(d=ri(d,u,i,v)),o&&(d=ei(d,o,f,v)),g-=x,v&&g<l){var j=Ir(d,m);return xi(n,t,_i,_.placeholder,e,d,j,a,c,l-g)}var A=h?e:this,k=p?A[n]:n;return g=d.length,a?d=function(n,t){for(var e=n.length,u=Gr(t.length,e),i=ui(n);u--;){var o=t[u];n[u]=Vi(o,e)?i[o]:r}return n}(d,a):y&&g>1&&d.reverse(),s&&c<g&&(d.length=c),this&&this!==Lt&&this instanceof _&&(k=w||hi(k)),k.apply(A,d)}}function gi(n,t){return function(r,e){return function(n,t,r,e){return He(n,function(n,u,i){t(e,r(n),u,i)}),e}(r,n,t(e),{})}}function yi(n,t){return function(e,u){var i;if(e===r&&u===r)return t;if(e!==r&&(i=e),u!==r){if(i===r)return u;"string"==typeof e||"string"==typeof u?(e=Du(e),u=Du(u)):(e=Tu(e),u=Tu(u)),i=n(e,u)}return i}}function di(n){return Si(function(t){return t=Qt(t,gr(Ti())),ku(function(r){var e=this;return n(t,function(n){return qt(n,e,r)})})})}function bi(n,t){var e=(t=t===r?" ":Du(t)).length;if(e<2)return e?Au(t,n):t;var u=Au(t,Mr(n/zr(t)));return Ar(t)?Ju(Sr(u),0,n).join(""):u.slice(0,n)}function wi(n){return function(t,e,u){return u&&"number"!=typeof u&&Gi(t,e,u)&&(e=u=r),t=Pf(t),e===r?(e=t,t=0):e=Pf(e),function(n,t,r,e){for(var u=-1,i=Vr(Mr((t-n)/(r||1)),0),o=Yn(i);i--;)o[e?i:++u]=n,n+=r;return o}(t,e,u=u===r?t<e?1:-1:Pf(u),n)}}function mi(n){return function(t,r){return"string"==typeof t&&"string"==typeof r||(t=Kf(t),r=Kf(r)),n(t,r)}}function xi(n,t,e,u,i,o,f,a,c,l){var s=t&d;t|=s?w:m,(t&=~(s?m:w))&y||(t&=~(_|g));var h=[n,t,i,s?o:r,s?f:r,s?r:o,s?r:f,a,c,l],p=e.apply(r,h);return Ji(n)&&uo(p,h),p.placeholder=u,fo(p,n,t)}function ji(n){var t=tt[n];return function(n,r){if(n=Kf(n),(r=null==r?0:Gr(qf(r),292))&&qr(n)){var e=(Gf(n)+"e").split("e");return+((e=(Gf(t(e[0]+"e"+(+e[1]+r)))+"e").split("e"))[0]+"e"+(+e[1]-r))}return t(n)}}var Ai=re&&1/Rr(new re([,-0]))[1]==S?function(n){return new re(n)}:Da;function ki(n){return function(t){var r=Pi(t);return r==G?kr(t):r==nn?Er(t):function(n,t){return Qt(t,function(t){return[t,n[t]]})}(t,n(t))}}function Oi(n,t,e,u,o,f,a,l){var s=t&g;if(!s&&"function"!=typeof n)throw new it(i);var h=u?u.length:0;if(h||(t&=~(w|m),u=o=r),a=a===r?a:Vr(qf(a),0),l=l===r?l:qf(l),h-=o?o.length:0,t&m){var p=u,v=o;u=o=r}var A=s?r:Ci(n),k=[n,t,e,u,o,p,v,f,a,l];if(A&&function(n,t){var r=n[1],e=t[1],u=r|e,i=u<(_|g|x),o=e==x&&r==d||e==x&&r==j&&n[7].length<=t[8]||e==(x|j)&&t[7].length<=t[8]&&r==d;if(!i&&!o)return n;e&_&&(n[2]=t[2],u|=r&_?0:y);var f=t[3];if(f){var a=n[3];n[3]=a?ri(a,f,t[4]):f,n[4]=a?Ir(n[3],c):t[4]}(f=t[5])&&(a=n[5],n[5]=a?ei(a,f,t[6]):f,n[6]=a?Ir(n[5],c):t[6]),(f=t[7])&&(n[7]=f),e&x&&(n[8]=null==n[8]?t[8]:Gr(n[8],t[8])),null==n[9]&&(n[9]=t[9]),n[0]=t[0],n[1]=u}(k,A),n=k[0],t=k[1],e=k[2],u=k[3],o=k[4],!(l=k[9]=k[9]===r?s?0:n.length:Vr(k[9]-h,0))&&t&(d|b)&&(t&=~(d|b)),t&&t!=_)O=t==d||t==b?function(n,t,e){var u=hi(n);return function i(){for(var o=arguments.length,f=Yn(o),a=o,c=Ui(i);a--;)f[a]=arguments[a];var l=o<3&&f[0]!==c&&f[o-1]!==c?[]:Ir(f,c);return(o-=l.length)<e?xi(n,t,_i,i.placeholder,r,f,l,r,r,e-o):qt(this&&this!==Lt&&this instanceof i?u:n,this,f)}}(n,t,l):t!=w&&t!=(_|w)||o.length?_i.apply(r,k):function(n,t,r,e){var u=t&_,i=hi(n);return function t(){for(var o=-1,f=arguments.length,a=-1,c=e.length,l=Yn(c+f),s=this&&this!==Lt&&this instanceof t?i:n;++a<c;)l[a]=e[a];for(;f--;)l[a++]=arguments[++o];return qt(s,u?r:this,l)}}(n,t,e,u);else var O=function(n,t,r){var e=t&_,u=hi(n);return function t(){return(this&&this!==Lt&&this instanceof t?u:n).apply(e?r:this,arguments)}}(n,t,e);return fo((A?Eu:uo)(O,k),n,t)}function Ii(n,t,e,u){return n===r||gf(n,at[e])&&!st.call(u,e)?t:n}function Ri(n,t,e,u,i,o){return zf(n)&&zf(t)&&(o.set(t,n),yu(n,t,r,Ri,o),o.delete(t)),n}function Ei(n){return Cf(n)?r:n}function zi(n,t,e,u,i,o){var f=e&p,a=n.length,c=t.length;if(a!=c&&!(f&&c>a))return!1;var l=o.get(n),s=o.get(t);if(l&&s)return l==t&&s==n;var h=-1,_=!0,g=e&v?new je:r;for(o.set(n,t),o.set(t,n);++h<a;){var y=n[h],d=t[h];if(u)var b=f?u(d,y,h,t,n,o):u(y,d,h,n,t,o);if(b!==r){if(b)continue;_=!1;break}if(g){if(!rr(t,function(n,t){if(!dr(g,t)&&(y===n||i(y,n,e,u,o)))return g.push(t)})){_=!1;break}}else if(y!==d&&!i(y,d,e,u,o)){_=!1;break}}return o.delete(n),o.delete(t),_}function Si(n){return oo(to(n,r,wo),n+"")}function Li(n){return Xe(n,fa,Fi)}function Wi(n){return Xe(n,aa,Ni)}var Ci=ie?function(n){return ie.get(n)}:Da;function Bi(n){for(var t=n.name+"",r=oe[t],e=st.call(oe,t)?r.length:0;e--;){var u=r[e],i=u.func;if(null==i||i==n)return u.name}return t}function Ui(n){return(st.call(_e,"placeholder")?_e:n).placeholder}function Ti(){var n=_e.iteratee||Ca;return n=n===Ca?lu:n,arguments.length?n(arguments[0],arguments[1]):n}function Di(n,t){var r,e,u=n.__data__;return("string"==(e=typeof(r=t))||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==r:null===r)?u["string"==typeof t?"string":"hash"]:u.map}function $i(n){for(var t=fa(n),r=t.length;r--;){var e=t[r],u=n[e];t[r]=[e,u,Xi(u)]}return t}function Mi(n,t){var e=function(n,t){return null==n?r:n[t]}(n,t);return cu(e)?e:r}var Fi=Nr?function(n){return null==n?[]:(n=rt(n),Ht(Nr(n),function(t){return Ut.call(n,t)}))}:Za,Ni=Nr?function(n){for(var t=[];n;)Xt(t,Fi(n)),n=Wt(n);return t}:Za,Pi=nu;function qi(n,t,r){for(var e=-1,u=(t=Gu(t,n)).length,i=!1;++e<u;){var o=so(t[e]);if(!(i=null!=n&&r(n,o)))break;n=n[o]}return i||++e!=u?i:!!(u=null==n?0:n.length)&&Ef(u)&&Vi(o,u)&&(wf(n)||bf(n))}function Zi(n){return"function"!=typeof n.constructor||Qi(n)?{}:ge(Wt(n))}function Ki(n){return wf(n)||bf(n)||!!(er&&n&&n[er])}function Vi(n,t){var r=typeof n;return!!(t=null==t?L:t)&&("number"==r||"symbol"!=r&&Vn.test(n))&&n>-1&&n%1==0&&n<t}function Gi(n,t,r){if(!zf(r))return!1;var e=typeof t;return!!("number"==e?xf(r)&&Vi(t,r.length):"string"==e&&t in r)&&gf(r[t],n)}function Hi(n,t){if(wf(n))return!1;var r=typeof n;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=n&&!Df(n))||En.test(n)||!Rn.test(n)||null!=t&&n in rt(t)}function Ji(n){var t=Bi(n),r=_e[t];if("function"!=typeof r||!(t in be.prototype))return!1;if(n===r)return!0;var e=Ci(r);return!!e&&n===e[0]}(Xr&&Pi(new Xr(new ArrayBuffer(1)))!=an||ne&&Pi(new ne)!=G||te&&"[object Promise]"!=Pi(te.resolve())||re&&Pi(new re)!=nn||ee&&Pi(new ee)!=un)&&(Pi=function(n){var t=nu(n),e=t==Y?n.constructor:r,u=e?ho(e):"";if(u)switch(u){case fe:return an;case ae:return G;case ce:return"[object Promise]";case le:return nn;case se:return un}return t});var Yi=ct?If:Ka;function Qi(n){var t=n&&n.constructor;return n===("function"==typeof t&&t.prototype||at)}function Xi(n){return n==n&&!zf(n)}function no(n,t){return function(e){return null!=e&&e[n]===t&&(t!==r||n in rt(e))}}function to(n,t,e){return t=Vr(t===r?n.length-1:t,0),function(){for(var r=arguments,u=-1,i=Vr(r.length-t,0),o=Yn(i);++u<i;)o[u]=r[t+u];u=-1;for(var f=Yn(t+1);++u<t;)f[u]=r[u];return f[t]=e(o),qt(n,this,f)}}function ro(n,t){return t.length<2?n:Qe(n,Lu(t,0,-1))}function eo(n,t){if(("constructor"!==t||"function"!=typeof n[t])&&"__proto__"!=t)return n[t]}var uo=ao(Eu),io=$r||function(n,t){return Lt.setTimeout(n,t)},oo=ao(zu);function fo(n,t,r){var e=t+"";return oo(n,function(n,t){var r=t.length;if(!r)return n;var e=r-1;return t[e]=(r>1?"& ":"")+t[e],t=t.join(r>2?", ":" "),n.replace(Bn,"{\n/* [wrapped with "+t+"] */\n")}(e,function(n,t){return Kt(D,function(r){var e="_."+r[0];t&r[1]&&!Jt(n,e)&&n.push(e)}),n.sort()}(function(n){var t=n.match(Un);return t?t[1].split(Tn):[]}(e),r)))}function ao(n){var t=0,e=0;return function(){var u=Hr(),i=R-(u-e);if(e=u,i>0){if(++t>=I)return arguments[0]}else t=0;return n.apply(r,arguments)}}function co(n,t){var e=-1,u=n.length,i=u-1;for(t=t===r?u:t;++e<t;){var o=ju(e,i),f=n[o];n[o]=n[e],n[e]=f}return n.length=t,n}var lo=function(n){var t=lf(n,function(n){return r.size===a&&r.clear(),n}),r=t.cache;return t}(function(n){var t=[];return 46===n.charCodeAt(0)&&t.push(""),n.replace(zn,function(n,r,e,u){t.push(e?u.replace(Mn,"$1"):r||n)}),t});function so(n){if("string"==typeof n||Df(n))return n;var t=n+"";return"0"==t&&1/n==-S?"-0":t}function ho(n){if(null!=n){try{return lt.call(n)}catch(t){}try{return n+""}catch(t){}}return""}function po(n){if(n instanceof be)return n.clone();var t=new de(n.__wrapped__,n.__chain__);return t.__actions__=ui(n.__actions__),t.__index__=n.__index__,t.__values__=n.__values__,t}var vo=ku(function(n,t){return jf(n)?Me(n,Ke(t,1,jf,!0)):[]}),_o=ku(function(n,t){var e=ko(t);return jf(e)&&(e=r),jf(n)?Me(n,Ke(t,1,jf,!0),Ti(e,2)):[]}),go=ku(function(n,t){var e=ko(t);return jf(e)&&(e=r),jf(n)?Me(n,Ke(t,1,jf,!0),r,e):[]});function yo(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:qf(r);return u<0&&(u=Vr(e+u,0)),ir(n,Ti(t,3),u)}function bo(n,t,e){var u=null==n?0:n.length;if(!u)return-1;var i=u-1;return e!==r&&(i=qf(e),i=e<0?Vr(u+i,0):Gr(i,u-1)),ir(n,Ti(t,3),i,!0)}function wo(n){return null!=n&&n.length?Ke(n,1):[]}function mo(n){return n&&n.length?n[0]:r}var xo=ku(function(n){var t=Qt(n,Ku);return t.length&&t[0]===n[0]?uu(t):[]}),jo=ku(function(n){var t=ko(n),e=Qt(n,Ku);return t===ko(e)?t=r:e.pop(),e.length&&e[0]===n[0]?uu(e,Ti(t,2)):[]}),Ao=ku(function(n){var t=ko(n),e=Qt(n,Ku);return(t="function"==typeof t?t:r)&&e.pop(),e.length&&e[0]===n[0]?uu(e,r,t):[]});function ko(n){var t=null==n?0:n.length;return t?n[t-1]:r}var Oo=ku(Io);function Io(n,t){return n&&n.length&&t&&t.length?mu(n,t):n}var Ro=Si(function(n,t){var r=null==n?0:n.length,e=Be(n,t);return xu(n,Qt(t,function(n){return Vi(n,r)?+n:n}).sort(ti)),e});function Eo(n){return null==n?n:Qr.call(n)}var zo=ku(function(n){return $u(Ke(n,1,jf,!0))}),So=ku(function(n){var t=ko(n);return jf(t)&&(t=r),$u(Ke(n,1,jf,!0),Ti(t,2))}),Lo=ku(function(n){var t=ko(n);return t="function"==typeof t?t:r,$u(Ke(n,1,jf,!0),r,t)});function Wo(n){if(!n||!n.length)return[];var t=0;return n=Ht(n,function(n){if(jf(n))return t=Vr(n.length,t),!0}),vr(t,function(t){return Qt(n,lr(t))})}function Co(n,t){if(!n||!n.length)return[];var e=Wo(n);return null==t?e:Qt(e,function(n){return qt(t,r,n)})}var Bo=ku(function(n,t){return jf(n)?Me(n,t):[]}),Uo=ku(function(n){return qu(Ht(n,jf))}),To=ku(function(n){var t=ko(n);return jf(t)&&(t=r),qu(Ht(n,jf),Ti(t,2))}),Do=ku(function(n){var t=ko(n);return t="function"==typeof t?t:r,qu(Ht(n,jf),r,t)}),$o=ku(Wo);var Mo=ku(function(n){var t=n.length,e=t>1?n[t-1]:r;return e="function"==typeof e?(n.pop(),e):r,Co(n,e)});function Fo(n){var t=_e(n);return t.__chain__=!0,t}function No(n,t){return t(n)}var Po=Si(function(n){var t=n.length,e=t?n[0]:0,u=this.__wrapped__,i=function(t){return Be(t,n)};return!(t>1||this.__actions__.length)&&u instanceof be&&Vi(e)?((u=u.slice(e,+e+(t?1:0))).__actions__.push({func:No,args:[i],thisArg:r}),new de(u,this.__chain__).thru(function(n){return t&&!n.length&&n.push(r),n})):this.thru(i)});var qo=oi(function(n,t,r){st.call(n,r)?++n[r]:Ce(n,r,1)});var Zo=pi(yo),Ko=pi(bo);function Vo(n,t){return(wf(n)?Kt:Fe)(n,Ti(t,3))}function Go(n,t){return(wf(n)?Vt:Ne)(n,Ti(t,3))}var Ho=oi(function(n,t,r){st.call(n,r)?n[r].push(t):Ce(n,r,[t])});var Jo=ku(function(n,t,r){var e=-1,u="function"==typeof t,i=xf(n)?Yn(n.length):[];return Fe(n,function(n){i[++e]=u?qt(t,n,r):iu(n,t,r)}),i}),Yo=oi(function(n,t,r){Ce(n,r,t)});function Qo(n,t){return(wf(n)?Qt:vu)(n,Ti(t,3))}var Xo=oi(function(n,t,r){n[r?0:1].push(t)},function(){return[[],[]]});var nf=ku(function(n,t){if(null==n)return[];var r=t.length;return r>1&&Gi(n,t[0],t[1])?t=[]:r>2&&Gi(t[0],t[1],t[2])&&(t=[t[0]]),bu(n,Ke(t,1),[])}),tf=Dr||function(){return Lt.Date.now()};function rf(n,t,e){return t=e?r:t,t=n&&null==t?n.length:t,Oi(n,x,r,r,r,r,t)}function ef(n,t){var e;if("function"!=typeof t)throw new it(i);return n=qf(n),function(){return--n>0&&(e=t.apply(this,arguments)),n<=1&&(t=r),e}}var uf=ku(function(n,t,r){var e=_;if(r.length){var u=Ir(r,Ui(uf));e|=w}return Oi(n,e,t,r,u)}),of=ku(function(n,t,r){var e=_|g;if(r.length){var u=Ir(r,Ui(of));e|=w}return Oi(t,e,n,r,u)});function ff(n,t,e){var u,o,f,a,c,l,s=0,h=!1,p=!1,v=!0;if("function"!=typeof n)throw new it(i);function _(t){var e=u,i=o;return u=o=r,s=t,a=n.apply(i,e)}function g(n){var e=n-l;return l===r||e>=t||e<0||p&&n-s>=f}function y(){var n=tf();if(g(n))return d(n);c=io(y,function(n){var r=t-(n-l);return p?Gr(r,f-(n-s)):r}(n))}function d(n){return c=r,v&&u?_(n):(u=o=r,a)}function b(){var n=tf(),e=g(n);if(u=arguments,o=this,l=n,e){if(c===r)return function(n){return s=n,c=io(y,t),h?_(n):a}(l);if(p)return Yu(c),c=io(y,t),_(l)}return c===r&&(c=io(y,t)),a}return t=Kf(t)||0,zf(e)&&(h=!!e.leading,f=(p="maxWait"in e)?Vr(Kf(e.maxWait)||0,t):f,v="trailing"in e?!!e.trailing:v),b.cancel=function(){c!==r&&Yu(c),s=0,u=l=o=c=r},b.flush=function(){return c===r?a:d(tf())},b}var af=ku(function(n,t){return $e(n,1,t)}),cf=ku(function(n,t,r){return $e(n,Kf(t)||0,r)});function lf(n,t){if("function"!=typeof n||null!=t&&"function"!=typeof t)throw new it(i);var r=function(){var e=arguments,u=t?t.apply(this,e):e[0],i=r.cache;if(i.has(u))return i.get(u);var o=n.apply(this,e);return r.cache=i.set(u,o)||i,o};return r.cache=new(lf.Cache||xe),r}function sf(n){if("function"!=typeof n)throw new it(i);return function(){var t=arguments;switch(t.length){case 0:return!n.call(this);case 1:return!n.call(this,t[0]);case 2:return!n.call(this,t[0],t[1]);case 3:return!n.call(this,t[0],t[1],t[2])}return!n.apply(this,t)}}lf.Cache=xe;var hf=Hu(function(n,t){var r=(t=1==t.length&&wf(t[0])?Qt(t[0],gr(Ti())):Qt(Ke(t,1),gr(Ti()))).length;return ku(function(e){for(var u=-1,i=Gr(e.length,r);++u<i;)e[u]=t[u].call(this,e[u]);return qt(n,this,e)})}),pf=ku(function(n,t){var e=Ir(t,Ui(pf));return Oi(n,w,r,t,e)}),vf=ku(function(n,t){var e=Ir(t,Ui(vf));return Oi(n,m,r,t,e)}),_f=Si(function(n,t){return Oi(n,j,r,r,r,t)});function gf(n,t){return n===t||n!=n&&t!=t}var yf=mi(tu),df=mi(function(n,t){return n>=t}),bf=ou(function(){return arguments}())?ou:function(n){return Sf(n)&&st.call(n,"callee")&&!Ut.call(n,"callee")},wf=Yn.isArray,mf=Dt?gr(Dt):function(n){return Sf(n)&&nu(n)==fn};function xf(n){return null!=n&&Ef(n.length)&&!If(n)}function jf(n){return Sf(n)&&xf(n)}var Af=Pr||Ka,kf=$t?gr($t):function(n){return Sf(n)&&nu(n)==P};function Of(n){if(!Sf(n))return!1;var t=nu(n);return t==Z||t==q||"string"==typeof n.message&&"string"==typeof n.name&&!Cf(n)}function If(n){if(!zf(n))return!1;var t=nu(n);return t==K||t==V||t==F||t==Q}function Rf(n){return"number"==typeof n&&n==qf(n)}function Ef(n){return"number"==typeof n&&n>-1&&n%1==0&&n<=L}function zf(n){var t=typeof n;return null!=n&&("object"==t||"function"==t)}function Sf(n){return null!=n&&"object"==typeof n}var Lf=Mt?gr(Mt):function(n){return Sf(n)&&Pi(n)==G};function Wf(n){return"number"==typeof n||Sf(n)&&nu(n)==H}function Cf(n){if(!Sf(n)||nu(n)!=Y)return!1;var t=Wt(n);if(null===t)return!0;var r=st.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&<.call(r)==_t}var Bf=Ft?gr(Ft):function(n){return Sf(n)&&nu(n)==X};var Uf=Nt?gr(Nt):function(n){return Sf(n)&&Pi(n)==nn};function Tf(n){return"string"==typeof n||!wf(n)&&Sf(n)&&nu(n)==tn}function Df(n){return"symbol"==typeof n||Sf(n)&&nu(n)==rn}var $f=Pt?gr(Pt):function(n){return Sf(n)&&Ef(n.length)&&!!kt[nu(n)]};var Mf=mi(pu),Ff=mi(function(n,t){return n<=t});function Nf(n){if(!n)return[];if(xf(n))return Tf(n)?Sr(n):ui(n);if(sr&&n[sr])return function(n){for(var t,r=[];!(t=n.next()).done;)r.push(t.value);return r}(n[sr]());var t=Pi(n);return(t==G?kr:t==nn?Rr:ga)(n)}function Pf(n){return n?(n=Kf(n))===S||n===-S?(n<0?-1:1)*W:n==n?n:0:0===n?n:0}function qf(n){var t=Pf(n),r=t%1;return t==t?r?t-r:t:0}function Zf(n){return n?Ue(qf(n),0,B):0}function Kf(n){if("number"==typeof n)return n;if(Df(n))return C;if(zf(n)){var t="function"==typeof n.valueOf?n.valueOf():n;n=zf(t)?t+"":t}if("string"!=typeof n)return 0===n?n:+n;n=_r(n);var r=qn.test(n);return r||Kn.test(n)?Et(n.slice(2),r?2:8):Pn.test(n)?C:+n}function Vf(n){return ii(n,aa(n))}function Gf(n){return null==n?"":Du(n)}var Hf=fi(function(n,t){if(Qi(t)||xf(t))ii(t,fa(t),n);else for(var r in t)st.call(t,r)&&ze(n,r,t[r])}),Jf=fi(function(n,t){ii(t,aa(t),n)}),Yf=fi(function(n,t,r,e){ii(t,aa(t),n,e)}),Qf=fi(function(n,t,r,e){ii(t,fa(t),n,e)}),Xf=Si(Be);var na=ku(function(n,t){n=rt(n);var e=-1,u=t.length,i=u>2?t[2]:r;for(i&&Gi(t[0],t[1],i)&&(u=1);++e<u;)for(var o=t[e],f=aa(o),a=-1,c=f.length;++a<c;){var l=f[a],s=n[l];(s===r||gf(s,at[l])&&!st.call(n,l))&&(n[l]=o[l])}return n}),ta=ku(function(n){return n.push(r,Ri),qt(la,r,n)});function ra(n,t,e){var u=null==n?r:Qe(n,t);return u===r?e:u}function ea(n,t){return null!=n&&qi(n,t,eu)}var ua=gi(function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=vt.call(t)),n[t]=r},za(Wa)),ia=gi(function(n,t,r){null!=t&&"function"!=typeof t.toString&&(t=vt.call(t)),st.call(n,t)?n[t].push(r):n[t]=[r]},Ti),oa=ku(iu);function fa(n){return xf(n)?ke(n):su(n)}function aa(n){return xf(n)?ke(n,!0):hu(n)}var ca=fi(function(n,t,r){yu(n,t,r)}),la=fi(function(n,t,r,e){yu(n,t,r,e)}),sa=Si(function(n,t){var r={};if(null==n)return r;var e=!1;t=Qt(t,function(t){return t=Gu(t,n),e||(e=t.length>1),t}),ii(n,Wi(n),r),e&&(r=Te(r,l|s|h,Ei));for(var u=t.length;u--;)Mu(r,t[u]);return r});var ha=Si(function(n,t){return null==n?{}:function(n,t){return wu(n,t,function(t,r){return ea(n,r)})}(n,t)});function pa(n,t){if(null==n)return{};var r=Qt(Wi(n),function(n){return[n]});return t=Ti(t),wu(n,r,function(n,r){return t(n,r[0])})}var va=ki(fa),_a=ki(aa);function ga(n){return null==n?[]:yr(n,fa(n))}var ya=si(function(n,t,r){return t=t.toLowerCase(),n+(r?da(t):t)});function da(n){return Oa(Gf(n).toLowerCase())}function ba(n){return(n=Gf(n))&&n.replace(Gn,mr).replace(dt,"")}var wa=si(function(n,t,r){return n+(r?"-":"")+t.toLowerCase()}),ma=si(function(n,t,r){return n+(r?" ":"")+t.toLowerCase()}),xa=li("toLowerCase");var ja=si(function(n,t,r){return n+(r?"_":"")+t.toLowerCase()});var Aa=si(function(n,t,r){return n+(r?" ":"")+Oa(t)});var ka=si(function(n,t,r){return n+(r?" ":"")+t.toUpperCase()}),Oa=li("toUpperCase");function Ia(n,t,e){return n=Gf(n),(t=e?r:t)===r?function(n){return xt.test(n)}(n)?function(n){return n.match(wt)||[]}(n):function(n){return n.match(Dn)||[]}(n):n.match(t)||[]}var Ra=ku(function(n,t){try{return qt(n,r,t)}catch(e){return Of(e)?e:new Xn(e)}}),Ea=Si(function(n,t){return Kt(t,function(t){t=so(t),Ce(n,t,uf(n[t],n))}),n});function za(n){return function(){return n}}var Sa=vi(),La=vi(!0);function Wa(n){return n}function Ca(n){return lu("function"==typeof n?n:Te(n,l))}var Ba=ku(function(n,t){return function(r){return iu(r,n,t)}}),Ua=ku(function(n,t){return function(r){return iu(n,r,t)}});function Ta(n,t,r){var e=fa(t),u=Ye(t,e);null!=r||zf(t)&&(u.length||!e.length)||(r=t,t=n,n=this,u=Ye(t,fa(t)));var i=!(zf(r)&&"chain"in r&&!r.chain),o=If(n);return Kt(u,function(r){var e=t[r];n[r]=e,o&&(n.prototype[r]=function(){var t=this.__chain__;if(i||t){var r=n(this.__wrapped__);return(r.__actions__=ui(this.__actions__)).push({func:e,args:arguments,thisArg:n}),r.__chain__=t,r}return e.apply(n,Xt([this.value()],arguments))})}),n}function Da(){}var $a=di(Qt),Ma=di(Gt),Fa=di(rr);function Na(n){return Hi(n)?lr(so(n)):function(n){return function(t){return Qe(t,n)}}(n)}var Pa=wi(),qa=wi(!0);function Za(){return[]}function Ka(){return!1}var Va=yi(function(n,t){return n+t},0),Ga=ji("ceil"),Ha=yi(function(n,t){return n/t},1),Ja=ji("floor");var Ya,Qa=yi(function(n,t){return n*t},1),Xa=ji("round"),nc=yi(function(n,t){return n-t},0);return _e.after=function(n,t){if("function"!=typeof t)throw new it(i);return n=qf(n),function(){if(--n<1)return t.apply(this,arguments)}},_e.ary=rf,_e.assign=Hf,_e.assignIn=Jf,_e.assignInWith=Yf,_e.assignWith=Qf,_e.at=Xf,_e.before=ef,_e.bind=uf,_e.bindAll=Ea,_e.bindKey=of,_e.castArray=function(){if(!arguments.length)return[];var n=arguments[0];return wf(n)?n:[n]},_e.chain=Fo,_e.chunk=function(n,t,e){t=(e?Gi(n,t,e):t===r)?1:Vr(qf(t),0);var u=null==n?0:n.length;if(!u||t<1)return[];for(var i=0,o=0,f=Yn(Mr(u/t));i<u;)f[o++]=Lu(n,i,i+=t);return f},_e.compact=function(n){for(var t=-1,r=null==n?0:n.length,e=0,u=[];++t<r;){var i=n[t];i&&(u[e++]=i)}return u},_e.concat=function(){var n=arguments.length;if(!n)return[];for(var t=Yn(n-1),r=arguments[0],e=n;e--;)t[e-1]=arguments[e];return Xt(wf(r)?ui(r):[r],Ke(t,1))},_e.cond=function(n){var t=null==n?0:n.length,r=Ti();return n=t?Qt(n,function(n){if("function"!=typeof n[1])throw new it(i);return[r(n[0]),n[1]]}):[],ku(function(r){for(var e=-1;++e<t;){var u=n[e];if(qt(u[0],this,r))return qt(u[1],this,r)}})},_e.conforms=function(n){return function(n){var t=fa(n);return function(r){return De(r,n,t)}}(Te(n,l))},_e.constant=za,_e.countBy=qo,_e.create=function(n,t){var r=ge(n);return null==t?r:We(r,t)},_e.curry=function n(t,e,u){var i=Oi(t,d,r,r,r,r,r,e=u?r:e);return i.placeholder=n.placeholder,i},_e.curryRight=function n(t,e,u){var i=Oi(t,b,r,r,r,r,r,e=u?r:e);return i.placeholder=n.placeholder,i},_e.debounce=ff,_e.defaults=na,_e.defaultsDeep=ta,_e.defer=af,_e.delay=cf,_e.difference=vo,_e.differenceBy=_o,_e.differenceWith=go,_e.drop=function(n,t,e){var u=null==n?0:n.length;return u?Lu(n,(t=e||t===r?1:qf(t))<0?0:t,u):[]},_e.dropRight=function(n,t,e){var u=null==n?0:n.length;return u?Lu(n,0,(t=u-(t=e||t===r?1:qf(t)))<0?0:t):[]},_e.dropRightWhile=function(n,t){return n&&n.length?Nu(n,Ti(t,3),!0,!0):[]},_e.dropWhile=function(n,t){return n&&n.length?Nu(n,Ti(t,3),!0):[]},_e.fill=function(n,t,e,u){var i=null==n?0:n.length;return i?(e&&"number"!=typeof e&&Gi(n,t,e)&&(e=0,u=i),function(n,t,e,u){var i=n.length;for((e=qf(e))<0&&(e=-e>i?0:i+e),(u=u===r||u>i?i:qf(u))<0&&(u+=i),u=e>u?0:Zf(u);e<u;)n[e++]=t;return n}(n,t,e,u)):[]},_e.filter=function(n,t){return(wf(n)?Ht:Ze)(n,Ti(t,3))},_e.flatMap=function(n,t){return Ke(Qo(n,t),1)},_e.flatMapDeep=function(n,t){return Ke(Qo(n,t),S)},_e.flatMapDepth=function(n,t,e){return e=e===r?1:qf(e),Ke(Qo(n,t),e)},_e.flatten=wo,_e.flattenDeep=function(n){return null!=n&&n.length?Ke(n,S):[]},_e.flattenDepth=function(n,t){return null!=n&&n.length?Ke(n,t=t===r?1:qf(t)):[]},_e.flip=function(n){return Oi(n,A)},_e.flow=Sa,_e.flowRight=La,_e.fromPairs=function(n){for(var t=-1,r=null==n?0:n.length,e={};++t<r;){var u=n[t];e[u[0]]=u[1]}return e},_e.functions=function(n){return null==n?[]:Ye(n,fa(n))},_e.functionsIn=function(n){return null==n?[]:Ye(n,aa(n))},_e.groupBy=Ho,_e.initial=function(n){return null!=n&&n.length?Lu(n,0,-1):[]},_e.intersection=xo,_e.intersectionBy=jo,_e.intersectionWith=Ao,_e.invert=ua,_e.invertBy=ia,_e.invokeMap=Jo,_e.iteratee=Ca,_e.keyBy=Yo,_e.keys=fa,_e.keysIn=aa,_e.map=Qo,_e.mapKeys=function(n,t){var r={};return t=Ti(t,3),He(n,function(n,e,u){Ce(r,t(n,e,u),n)}),r},_e.mapValues=function(n,t){var r={};return t=Ti(t,3),He(n,function(n,e,u){Ce(r,e,t(n,e,u))}),r},_e.matches=function(n){return _u(Te(n,l))},_e.matchesProperty=function(n,t){return gu(n,Te(t,l))},_e.memoize=lf,_e.merge=ca,_e.mergeWith=la,_e.method=Ba,_e.methodOf=Ua,_e.mixin=Ta,_e.negate=sf,_e.nthArg=function(n){return n=qf(n),ku(function(t){return du(t,n)})},_e.omit=sa,_e.omitBy=function(n,t){return pa(n,sf(Ti(t)))},_e.once=function(n){return ef(2,n)},_e.orderBy=function(n,t,e,u){return null==n?[]:(wf(t)||(t=null==t?[]:[t]),wf(e=u?r:e)||(e=null==e?[]:[e]),bu(n,t,e))},_e.over=$a,_e.overArgs=hf,_e.overEvery=Ma,_e.overSome=Fa,_e.partial=pf,_e.partialRight=vf,_e.partition=Xo,_e.pick=ha,_e.pickBy=pa,_e.property=Na,_e.propertyOf=function(n){return function(t){return null==n?r:Qe(n,t)}},_e.pull=Oo,_e.pullAll=Io,_e.pullAllBy=function(n,t,r){return n&&n.length&&t&&t.length?mu(n,t,Ti(r,2)):n},_e.pullAllWith=function(n,t,e){return n&&n.length&&t&&t.length?mu(n,t,r,e):n},_e.pullAt=Ro,_e.range=Pa,_e.rangeRight=qa,_e.rearg=_f,_e.reject=function(n,t){return(wf(n)?Ht:Ze)(n,sf(Ti(t,3)))},_e.remove=function(n,t){var r=[];if(!n||!n.length)return r;var e=-1,u=[],i=n.length;for(t=Ti(t,3);++e<i;){var o=n[e];t(o,e,n)&&(r.push(o),u.push(e))}return xu(n,u),r},_e.rest=function(n,t){if("function"!=typeof n)throw new it(i);return ku(n,t=t===r?t:qf(t))},_e.reverse=Eo,_e.sampleSize=function(n,t,e){return t=(e?Gi(n,t,e):t===r)?1:qf(t),(wf(n)?Ie:Iu)(n,t)},_e.set=function(n,t,r){return null==n?n:Ru(n,t,r)},_e.setWith=function(n,t,e,u){return u="function"==typeof u?u:r,null==n?n:Ru(n,t,e,u)},_e.shuffle=function(n){return(wf(n)?Re:Su)(n)},_e.slice=function(n,t,e){var u=null==n?0:n.length;return u?(e&&"number"!=typeof e&&Gi(n,t,e)?(t=0,e=u):(t=null==t?0:qf(t),e=e===r?u:qf(e)),Lu(n,t,e)):[]},_e.sortBy=nf,_e.sortedUniq=function(n){return n&&n.length?Uu(n):[]},_e.sortedUniqBy=function(n,t){return n&&n.length?Uu(n,Ti(t,2)):[]},_e.split=function(n,t,e){return e&&"number"!=typeof e&&Gi(n,t,e)&&(t=e=r),(e=e===r?B:e>>>0)?(n=Gf(n))&&("string"==typeof t||null!=t&&!Bf(t))&&!(t=Du(t))&&Ar(n)?Ju(Sr(n),0,e):n.split(t,e):[]},_e.spread=function(n,t){if("function"!=typeof n)throw new it(i);return t=null==t?0:Vr(qf(t),0),ku(function(r){var e=r[t],u=Ju(r,0,t);return e&&Xt(u,e),qt(n,this,u)})},_e.tail=function(n){var t=null==n?0:n.length;return t?Lu(n,1,t):[]},_e.take=function(n,t,e){return n&&n.length?Lu(n,0,(t=e||t===r?1:qf(t))<0?0:t):[]},_e.takeRight=function(n,t,e){var u=null==n?0:n.length;return u?Lu(n,(t=u-(t=e||t===r?1:qf(t)))<0?0:t,u):[]},_e.takeRightWhile=function(n,t){return n&&n.length?Nu(n,Ti(t,3),!1,!0):[]},_e.takeWhile=function(n,t){return n&&n.length?Nu(n,Ti(t,3)):[]},_e.tap=function(n,t){return t(n),n},_e.throttle=function(n,t,r){var e=!0,u=!0;if("function"!=typeof n)throw new it(i);return zf(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),ff(n,t,{leading:e,maxWait:t,trailing:u})},_e.thru=No,_e.toArray=Nf,_e.toPairs=va,_e.toPairsIn=_a,_e.toPath=function(n){return wf(n)?Qt(n,so):Df(n)?[n]:ui(lo(Gf(n)))},_e.toPlainObject=Vf,_e.transform=function(n,t,r){var e=wf(n),u=e||Af(n)||$f(n);if(t=Ti(t,4),null==r){var i=n&&n.constructor;r=u?e?new i:[]:zf(n)&&If(i)?ge(Wt(n)):{}}return(u?Kt:He)(n,function(n,e,u){return t(r,n,e,u)}),r},_e.unary=function(n){return rf(n,1)},_e.union=zo,_e.unionBy=So,_e.unionWith=Lo,_e.uniq=function(n){return n&&n.length?$u(n):[]},_e.uniqBy=function(n,t){return n&&n.length?$u(n,Ti(t,2)):[]},_e.uniqWith=function(n,t){return t="function"==typeof t?t:r,n&&n.length?$u(n,r,t):[]},_e.unset=function(n,t){return null==n||Mu(n,t)},_e.unzip=Wo,_e.unzipWith=Co,_e.update=function(n,t,r){return null==n?n:Fu(n,t,Vu(r))},_e.updateWith=function(n,t,e,u){return u="function"==typeof u?u:r,null==n?n:Fu(n,t,Vu(e),u)},_e.values=ga,_e.valuesIn=function(n){return null==n?[]:yr(n,aa(n))},_e.without=Bo,_e.words=Ia,_e.wrap=function(n,t){return pf(Vu(t),n)},_e.xor=Uo,_e.xorBy=To,_e.xorWith=Do,_e.zip=$o,_e.zipObject=function(n,t){return Zu(n||[],t||[],ze)},_e.zipObjectDeep=function(n,t){return Zu(n||[],t||[],Ru)},_e.zipWith=Mo,_e.entries=va,_e.entriesIn=_a,_e.extend=Jf,_e.extendWith=Yf,Ta(_e,_e),_e.add=Va,_e.attempt=Ra,_e.camelCase=ya,_e.capitalize=da,_e.ceil=Ga,_e.clamp=function(n,t,e){return e===r&&(e=t,t=r),e!==r&&(e=(e=Kf(e))==e?e:0),t!==r&&(t=(t=Kf(t))==t?t:0),Ue(Kf(n),t,e)},_e.clone=function(n){return Te(n,h)},_e.cloneDeep=function(n){return Te(n,l|h)},_e.cloneDeepWith=function(n,t){return Te(n,l|h,t="function"==typeof t?t:r)},_e.cloneWith=function(n,t){return Te(n,h,t="function"==typeof t?t:r)},_e.conformsTo=function(n,t){return null==t||De(n,t,fa(t))},_e.deburr=ba,_e.defaultTo=function(n,t){return null==n||n!=n?t:n},_e.divide=Ha,_e.endsWith=function(n,t,e){n=Gf(n),t=Du(t);var u=n.length,i=e=e===r?u:Ue(qf(e),0,u);return(e-=t.length)>=0&&n.slice(e,i)==t},_e.eq=gf,_e.escape=function(n){return(n=Gf(n))&&An.test(n)?n.replace(xn,xr):n},_e.escapeRegExp=function(n){return(n=Gf(n))&&Ln.test(n)?n.replace(Sn,"\\$&"):n},_e.every=function(n,t,e){var u=wf(n)?Gt:Pe;return e&&Gi(n,t,e)&&(t=r),u(n,Ti(t,3))},_e.find=Zo,_e.findIndex=yo,_e.findKey=function(n,t){return ur(n,Ti(t,3),He)},_e.findLast=Ko,_e.findLastIndex=bo,_e.findLastKey=function(n,t){return ur(n,Ti(t,3),Je)},_e.floor=Ja,_e.forEach=Vo,_e.forEachRight=Go,_e.forIn=function(n,t){return null==n?n:Ve(n,Ti(t,3),aa)},_e.forInRight=function(n,t){return null==n?n:Ge(n,Ti(t,3),aa)},_e.forOwn=function(n,t){return n&&He(n,Ti(t,3))},_e.forOwnRight=function(n,t){return n&&Je(n,Ti(t,3))},_e.get=ra,_e.gt=yf,_e.gte=df,_e.has=function(n,t){return null!=n&&qi(n,t,ru)},_e.hasIn=ea,_e.head=mo,_e.identity=Wa,_e.includes=function(n,t,r,e){n=xf(n)?n:ga(n),r=r&&!e?qf(r):0;var u=n.length;return r<0&&(r=Vr(u+r,0)),Tf(n)?r<=u&&n.indexOf(t,r)>-1:!!u&&or(n,t,r)>-1},_e.indexOf=function(n,t,r){var e=null==n?0:n.length;if(!e)return-1;var u=null==r?0:qf(r);return u<0&&(u=Vr(e+u,0)),or(n,t,u)},_e.inRange=function(n,t,e){return t=Pf(t),e===r?(e=t,t=0):e=Pf(e),function(n,t,r){return n>=Gr(t,r)&&n<Vr(t,r)}(n=Kf(n),t,e)},_e.invoke=oa,_e.isArguments=bf,_e.isArray=wf,_e.isArrayBuffer=mf,_e.isArrayLike=xf,_e.isArrayLikeObject=jf,_e.isBoolean=function(n){return!0===n||!1===n||Sf(n)&&nu(n)==N},_e.isBuffer=Af,_e.isDate=kf,_e.isElement=function(n){return Sf(n)&&1===n.nodeType&&!Cf(n)},_e.isEmpty=function(n){if(null==n)return!0;if(xf(n)&&(wf(n)||"string"==typeof n||"function"==typeof n.splice||Af(n)||$f(n)||bf(n)))return!n.length;var t=Pi(n);if(t==G||t==nn)return!n.size;if(Qi(n))return!su(n).length;for(var r in n)if(st.call(n,r))return!1;return!0},_e.isEqual=function(n,t){return fu(n,t)},_e.isEqualWith=function(n,t,e){var u=(e="function"==typeof e?e:r)?e(n,t):r;return u===r?fu(n,t,r,e):!!u},_e.isError=Of,_e.isFinite=function(n){return"number"==typeof n&&qr(n)},_e.isFunction=If,_e.isInteger=Rf,_e.isLength=Ef,_e.isMap=Lf,_e.isMatch=function(n,t){return n===t||au(n,t,$i(t))},_e.isMatchWith=function(n,t,e){return e="function"==typeof e?e:r,au(n,t,$i(t),e)},_e.isNaN=function(n){return Wf(n)&&n!=+n},_e.isNative=function(n){if(Yi(n))throw new Xn(u);return cu(n)},_e.isNil=function(n){return null==n},_e.isNull=function(n){return null===n},_e.isNumber=Wf,_e.isObject=zf,_e.isObjectLike=Sf,_e.isPlainObject=Cf,_e.isRegExp=Bf,_e.isSafeInteger=function(n){return Rf(n)&&n>=-L&&n<=L},_e.isSet=Uf,_e.isString=Tf,_e.isSymbol=Df,_e.isTypedArray=$f,_e.isUndefined=function(n){return n===r},_e.isWeakMap=function(n){return Sf(n)&&Pi(n)==un},_e.isWeakSet=function(n){return Sf(n)&&nu(n)==on},_e.join=function(n,t){return null==n?"":Zr.call(n,t)},_e.kebabCase=wa,_e.last=ko,_e.lastIndexOf=function(n,t,e){var u=null==n?0:n.length;if(!u)return-1;var i=u;return e!==r&&(i=(i=qf(e))<0?Vr(u+i,0):Gr(i,u-1)),t==t?function(n,t,r){for(var e=r+1;e--;)if(n[e]===t)return e;return e}(n,t,i):ir(n,ar,i,!0)},_e.lowerCase=ma,_e.lowerFirst=xa,_e.lt=Mf,_e.lte=Ff,_e.max=function(n){return n&&n.length?qe(n,Wa,tu):r},_e.maxBy=function(n,t){return n&&n.length?qe(n,Ti(t,2),tu):r},_e.mean=function(n){return cr(n,Wa)},_e.meanBy=function(n,t){return cr(n,Ti(t,2))},_e.min=function(n){return n&&n.length?qe(n,Wa,pu):r},_e.minBy=function(n,t){return n&&n.length?qe(n,Ti(t,2),pu):r},_e.stubArray=Za,_e.stubFalse=Ka,_e.stubObject=function(){return{}},_e.stubString=function(){return""},_e.stubTrue=function(){return!0},_e.multiply=Qa,_e.nth=function(n,t){return n&&n.length?du(n,qf(t)):r},_e.noConflict=function(){return Lt._===this&&(Lt._=gt),this},_e.noop=Da,_e.now=tf,_e.pad=function(n,t,r){n=Gf(n);var e=(t=qf(t))?zr(n):0;if(!t||e>=t)return n;var u=(t-e)/2;return bi(Fr(u),r)+n+bi(Mr(u),r)},_e.padEnd=function(n,t,r){n=Gf(n);var e=(t=qf(t))?zr(n):0;return t&&e<t?n+bi(t-e,r):n},_e.padStart=function(n,t,r){n=Gf(n);var e=(t=qf(t))?zr(n):0;return t&&e<t?bi(t-e,r)+n:n},_e.parseInt=function(n,t,r){return r||null==t?t=0:t&&(t=+t),Jr(Gf(n).replace(Wn,""),t||0)},_e.random=function(n,t,e){if(e&&"boolean"!=typeof e&&Gi(n,t,e)&&(t=e=r),e===r&&("boolean"==typeof t?(e=t,t=r):"boolean"==typeof n&&(e=n,n=r)),n===r&&t===r?(n=0,t=1):(n=Pf(n),t===r?(t=n,n=0):t=Pf(t)),n>t){var u=n;n=t,t=u}if(e||n%1||t%1){var i=Yr();return Gr(n+i*(t-n+Rt("1e-"+((i+"").length-1))),t)}return ju(n,t)},_e.reduce=function(n,t,r){var e=wf(n)?nr:hr,u=arguments.length<3;return e(n,Ti(t,4),r,u,Fe)},_e.reduceRight=function(n,t,r){var e=wf(n)?tr:hr,u=arguments.length<3;return e(n,Ti(t,4),r,u,Ne)},_e.repeat=function(n,t,e){return t=(e?Gi(n,t,e):t===r)?1:qf(t),Au(Gf(n),t)},_e.replace=function(){var n=arguments,t=Gf(n[0]);return n.length<3?t:t.replace(n[1],n[2])},_e.result=function(n,t,e){var u=-1,i=(t=Gu(t,n)).length;for(i||(i=1,n=r);++u<i;){var o=null==n?r:n[so(t[u])];o===r&&(u=i,o=e),n=If(o)?o.call(n):o}return n},_e.round=Xa,_e.runInContext=n,_e.sample=function(n){return(wf(n)?Oe:Ou)(n)},_e.size=function(n){if(null==n)return 0;if(xf(n))return Tf(n)?zr(n):n.length;var t=Pi(n);return t==G||t==nn?n.size:su(n).length},_e.snakeCase=ja,_e.some=function(n,t,e){var u=wf(n)?rr:Wu;return e&&Gi(n,t,e)&&(t=r),u(n,Ti(t,3))},_e.sortedIndex=function(n,t){return Cu(n,t)},_e.sortedIndexBy=function(n,t,r){return Bu(n,t,Ti(r,2))},_e.sortedIndexOf=function(n,t){var r=null==n?0:n.length;if(r){var e=Cu(n,t);if(e<r&&gf(n[e],t))return e}return-1},_e.sortedLastIndex=function(n,t){return Cu(n,t,!0)},_e.sortedLastIndexBy=function(n,t,r){return Bu(n,t,Ti(r,2),!0)},_e.sortedLastIndexOf=function(n,t){if(null!=n&&n.length){var r=Cu(n,t,!0)-1;if(gf(n[r],t))return r}return-1},_e.startCase=Aa,_e.startsWith=function(n,t,r){return n=Gf(n),r=null==r?0:Ue(qf(r),0,n.length),t=Du(t),n.slice(r,r+t.length)==t},_e.subtract=nc,_e.sum=function(n){return n&&n.length?pr(n,Wa):0},_e.sumBy=function(n,t){return n&&n.length?pr(n,Ti(t,2)):0},_e.template=function(n,t,e){var u=_e.templateSettings;e&&Gi(n,t,e)&&(t=r),n=Gf(n),t=Yf({},t,u,Ii);var i,f,a=Yf({},t.imports,u.imports,Ii),c=fa(a),l=yr(a,c),s=0,h=t.interpolate||Hn,p="__p += '",v=et((t.escape||Hn).source+"|"+h.source+"|"+(h===In?Fn:Hn).source+"|"+(t.evaluate||Hn).source+"|$","g"),_="//# sourceURL="+(st.call(t,"sourceURL")?(t.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++At+"]")+"\n";n.replace(v,function(t,r,e,u,o,a){return e||(e=u),p+=n.slice(s,a).replace(Jn,jr),r&&(i=!0,p+="' +\n__e("+r+") +\n'"),o&&(f=!0,p+="';\n"+o+";\n__p += '"),e&&(p+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"),s=a+t.length,t}),p+="';\n";var g=st.call(t,"variable")&&t.variable;if(g){if($n.test(g))throw new Xn(o)}else p="with (obj) {\n"+p+"\n}\n";p=(f?p.replace(dn,""):p).replace(bn,"$1").replace(wn,"$1;"),p="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(i?", __e = _.escape":"")+(f?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var y=Ra(function(){return nt(c,_+"return "+p).apply(r,l)});if(y.source=p,Of(y))throw y;return y},_e.times=function(n,t){if((n=qf(n))<1||n>L)return[];var r=B,e=Gr(n,B);t=Ti(t),n-=B;for(var u=vr(e,t);++r<n;)t(r);return u},_e.toFinite=Pf,_e.toInteger=qf,_e.toLength=Zf,_e.toLower=function(n){return Gf(n).toLowerCase()},_e.toNumber=Kf,_e.toSafeInteger=function(n){return n?Ue(qf(n),-L,L):0===n?n:0},_e.toString=Gf,_e.toUpper=function(n){return Gf(n).toUpperCase()},_e.trim=function(n,t,e){if((n=Gf(n))&&(e||t===r))return _r(n);if(!n||!(t=Du(t)))return n;var u=Sr(n),i=Sr(t);return Ju(u,br(u,i),wr(u,i)+1).join("")},_e.trimEnd=function(n,t,e){if((n=Gf(n))&&(e||t===r))return n.slice(0,Lr(n)+1);if(!n||!(t=Du(t)))return n;var u=Sr(n);return Ju(u,0,wr(u,Sr(t))+1).join("")},_e.trimStart=function(n,t,e){if((n=Gf(n))&&(e||t===r))return n.replace(Wn,"");if(!n||!(t=Du(t)))return n;var u=Sr(n);return Ju(u,br(u,Sr(t))).join("")},_e.truncate=function(n,t){var e=k,u=O;if(zf(t)){var i="separator"in t?t.separator:i;e="length"in t?qf(t.length):e,u="omission"in t?Du(t.omission):u}var o=(n=Gf(n)).length;if(Ar(n)){var f=Sr(n);o=f.length}if(e>=o)return n;var a=e-zr(u);if(a<1)return u;var c=f?Ju(f,0,a).join(""):n.slice(0,a);if(i===r)return c+u;if(f&&(a+=c.length-a),Bf(i)){if(n.slice(a).search(i)){var l,s=c;for(i.global||(i=et(i.source,Gf(Nn.exec(i))+"g")),i.lastIndex=0;l=i.exec(s);)var h=l.index;c=c.slice(0,h===r?a:h)}}else if(n.indexOf(Du(i),a)!=a){var p=c.lastIndexOf(i);p>-1&&(c=c.slice(0,p))}return c+u},_e.unescape=function(n){return(n=Gf(n))&&jn.test(n)?n.replace(mn,Wr):n},_e.uniqueId=function(n){var t=++ht;return Gf(n)+t},_e.upperCase=ka,_e.upperFirst=Oa,_e.each=Vo,_e.eachRight=Go,_e.first=mo,Ta(_e,(Ya={},He(_e,function(n,t){st.call(_e.prototype,t)||(Ya[t]=n)}),Ya),{chain:!1}),_e.VERSION="4.17.21",Kt(["bind","bindKey","curry","curryRight","partial","partialRight"],function(n){_e[n].placeholder=_e}),Kt(["drop","take"],function(n,t){be.prototype[n]=function(e){e=e===r?1:Vr(qf(e),0);var u=this.__filtered__&&!t?new be(this):this.clone();return u.__filtered__?u.__takeCount__=Gr(e,u.__takeCount__):u.__views__.push({size:Gr(e,B),type:n+(u.__dir__<0?"Right":"")}),u},be.prototype[n+"Right"]=function(t){return this.reverse()[n](t).reverse()}}),Kt(["filter","map","takeWhile"],function(n,t){var r=t+1,e=r==E||3==r;be.prototype[n]=function(n){var t=this.clone();return t.__iteratees__.push({iteratee:Ti(n,3),type:r}),t.__filtered__=t.__filtered__||e,t}}),Kt(["head","last"],function(n,t){var r="take"+(t?"Right":"");be.prototype[n]=function(){return this[r](1).value()[0]}}),Kt(["initial","tail"],function(n,t){var r="drop"+(t?"":"Right");be.prototype[n]=function(){return this.__filtered__?new be(this):this[r](1)}}),be.prototype.compact=function(){return this.filter(Wa)},be.prototype.find=function(n){return this.filter(n).head()},be.prototype.findLast=function(n){return this.reverse().find(n)},be.prototype.invokeMap=ku(function(n,t){return"function"==typeof n?new be(this):this.map(function(r){return iu(r,n,t)})}),be.prototype.reject=function(n){return this.filter(sf(Ti(n)))},be.prototype.slice=function(n,t){n=qf(n);var e=this;return e.__filtered__&&(n>0||t<0)?new be(e):(n<0?e=e.takeRight(-n):n&&(e=e.drop(n)),t!==r&&(e=(t=qf(t))<0?e.dropRight(-t):e.take(t-n)),e)},be.prototype.takeRightWhile=function(n){return this.reverse().takeWhile(n).reverse()},be.prototype.toArray=function(){return this.take(B)},He(be.prototype,function(n,t){var e=/^(?:filter|find|map|reject)|While$/.test(t),u=/^(?:head|last)$/.test(t),i=_e[u?"take"+("last"==t?"Right":""):t],o=u||/^find/.test(t);i&&(_e.prototype[t]=function(){var t=this.__wrapped__,f=u?[1]:arguments,a=t instanceof be,c=f[0],l=a||wf(t),s=function(n){var t=i.apply(_e,Xt([n],f));return u&&h?t[0]:t};l&&e&&"function"==typeof c&&1!=c.length&&(a=l=!1);var h=this.__chain__,p=!!this.__actions__.length,v=o&&!h,_=a&&!p;if(!o&&l){t=_?t:new be(this);var g=n.apply(t,f);return g.__actions__.push({func:No,args:[s],thisArg:r}),new de(g,h)}return v&&_?n.apply(this,f):(g=this.thru(s),v?u?g.value()[0]:g.value():g)})}),Kt(["pop","push","shift","sort","splice","unshift"],function(n){var t=ot[n],r=/^(?:push|sort|unshift)$/.test(n)?"tap":"thru",e=/^(?:pop|shift)$/.test(n);_e.prototype[n]=function(){var n=arguments;if(e&&!this.__chain__){var u=this.value();return t.apply(wf(u)?u:[],n)}return this[r](function(r){return t.apply(wf(r)?r:[],n)})}}),He(be.prototype,function(n,t){var r=_e[t];if(r){var e=r.name+"";st.call(oe,e)||(oe[e]=[]),oe[e].push({name:t,func:r})}}),oe[_i(r,g).name]=[{name:"wrapper",func:r}],be.prototype.clone=function(){var n=new be(this.__wrapped__);return n.__actions__=ui(this.__actions__),n.__dir__=this.__dir__,n.__filtered__=this.__filtered__,n.__iteratees__=ui(this.__iteratees__),n.__takeCount__=this.__takeCount__,n.__views__=ui(this.__views__),n},be.prototype.reverse=function(){if(this.__filtered__){var n=new be(this);n.__dir__=-1,n.__filtered__=!0}else(n=this.clone()).__dir__*=-1;return n},be.prototype.value=function(){var n=this.__wrapped__.value(),t=this.__dir__,r=wf(n),e=t<0,u=r?n.length:0,i=function(n,t,r){for(var e=-1,u=r.length;++e<u;){var i=r[e],o=i.size;switch(i.type){case"drop":n+=o;break;case"dropRight":t-=o;break;case"take":t=Gr(t,n+o);break;case"takeRight":n=Vr(n,t-o)}}return{start:n,end:t}}(0,u,this.__views__),o=i.start,f=i.end,a=f-o,c=e?f:o-1,l=this.__iteratees__,s=l.length,h=0,p=Gr(a,this.__takeCount__);if(!r||!e&&u==a&&p==a)return Pu(n,this.__actions__);var v=[];n:for(;a--&&h<p;){for(var _=-1,g=n[c+=t];++_<s;){var y=l[_],d=y.iteratee,b=y.type,w=d(g);if(b==z)g=w;else if(!w){if(b==E)continue n;break n}}v[h++]=g}return v},_e.prototype.at=Po,_e.prototype.chain=function(){return Fo(this)},_e.prototype.commit=function(){return new de(this.value(),this.__chain__)},_e.prototype.next=function(){this.__values__===r&&(this.__values__=Nf(this.value()));var n=this.__index__>=this.__values__.length;return{done:n,value:n?r:this.__values__[this.__index__++]}},_e.prototype.plant=function(n){for(var t,e=this;e instanceof ye;){var u=po(e);u.__index__=0,u.__values__=r,t?i.__wrapped__=u:t=u;var i=u;e=e.__wrapped__}return i.__wrapped__=n,t},_e.prototype.reverse=function(){var n=this.__wrapped__;if(n instanceof be){var t=n;return this.__actions__.length&&(t=new be(this)),(t=t.reverse()).__actions__.push({func:No,args:[Eo],thisArg:r}),new de(t,this.__chain__)}return this.thru(Eo)},_e.prototype.toJSON=_e.prototype.valueOf=_e.prototype.value=function(){return Pu(this.__wrapped__,this.__actions__)},_e.prototype.first=_e.prototype.head,sr&&(_e.prototype[sr]=function(){return this}),_e}();"function"==typeof n&&"object"==typeof n.amd&&n.amd?(Lt._=Cr,n(function(){return Cr})):Ct?((Ct.exports=Cr)._=Cr,Wt._=Cr):Lt._=Cr}).call(this);
},{"buffer":"aMB2"}],"G7NL":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=r;var n={"ar-eg":"ar","de-at":"de","de-ch":"de","en-au":"en","en-ca":"en","en-gb":"en","en-us":"en","en-ie":"en","es-es":"es","es-419":"es","fr-be":"fr","fr-ca":"fr","fr-ch":"fr","fr-fr":"fr","nl-be":"nl","pt-br":"pt"},t=function(n){return n.toString().replace(/\B(?=(\d{3})+(?!\d))/g," ")},c={nbResults:{ar:function(n){return n>1?"".concat(t(n)," نتيجة"):"نتيجة واحدة"},bg:function(n){return"".concat(t(n)," резултат").concat(n>1?"а":"")},cs:function(n){var c="ek";return n>1&&(c="ky"),n>4&&(c="ků"),"".concat(t(n)," výsled").concat(c)},da:function(n){return"".concat(t(n)," resultat").concat(n>1?"er":"")},de:function(n){return"".concat(t(n)," Ergebnis").concat(n>1?"se":"")},el:function(n){return"".concat(t(n)," αποτέλεσμα").concat(n>1?"τα":"")},en:function(n){return"".concat(t(n)," result").concat(n>1?"s":"")},es:function(n){return"".concat(t(n)," resultado").concat(n>1?"s":"")},fi:function(n){return"".concat(t(n)," tulos").concat(n>1?"ta":"")},fr:function(n){return"".concat(t(n)," résultat").concat(n>1?"s":"")},hu:function(n){return"".concat(t(n)," találat")},id:function(n){return"".concat(t(n)," hasil")},it:function(n){return"".concat(t(n)," risultat").concat(n>1?"i":"o")},ja:function(n){return"".concat(t(n),"個の結果")},ko:function(n){return"".concat(t(n),"건의")},nl:function(n){return"".concat(t(n)," resulta").concat(n>1?"ten":"at")},no:function(n){return"".concat(t(n)," resultat").concat(n>1?"er":"")},pl:function(n){return"".concat(t(n)," wynik").concat(n>1?"ów":"")},pt:function(n){return"".concat(t(n)," resultado").concat(n>1?"s":"")},ro:function(n){return"".concat(t(n)," rezultat").concat(n>1?"e":"")},ru:function(n){var c="";return c=n%10==1&&n%100!=11?"":n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?"а":"ов","".concat(t(n)," результат").concat(c)},sk:function(n){var c="ok";return n>1&&(c="ky"),n>4&&(c="kov"),"".concat(t(n)," výsled").concat(c)},sv:function(n){return"".concat(t(n)," träff").concat(n>1?"ar":"")},th:function(n){return"".concat(t(n)," ผลลัพธ์ใน")},tr:function(n){return"".concat(t(n)," sonuç")},uk:function(n){var c="";return c=n%10==1&&n%100!=11?"":n%10>=2&&n%10<=4&&(n%100<10||n%100>=20)?"и":"","".concat(t(n)," результат").concat(c)},vi:function(n){return"".concat(t(n)," kết quả được tìm")},"zh-cn":function(n){return"".concat(t(n),"个结果")},"zh-tw":function(n){return"".concat(t(n)," 項結果")}},noResultsFor:{ar:function(n){return'لم يتم العثور على نتائج لصالح "'.concat(n,'"')},bg:function(n){return'Няма намерен резултат за "'.concat(n,'"')},cs:function(n){return"Pro dotaz „".concat(n,"“ nebyly nalezeny žádné výsledky")},da:function(n){return'Ingen resultater fundet for "'.concat(n,'"')},de:function(n){return'Keine Ergebnisse für "'.concat(n,'" gefunden')},el:function(n){return"Δεν βρέθηκε αποτέλεσμα για «".concat(n,"»")},en:function(n){return'No result found for "'.concat(n,'"')},es:function(n){return'No se han encontrado resultados para "'.concat(n,'"')},fi:function(n){return"Tuloksia hakusanalla ”".concat(n,"” ei löytynyt")},fr:function(n){return'Aucun résultat pour "'.concat(n,'"')},hu:function(n){return'Nicns találat erre: "'.concat(n,'"')},id:function(n){return'Tak ditemukan hasil untuk "'.concat(n,'"')},it:function(n){return'Nessun risultato trovato per "'.concat(n,'"')},ja:function(n){return'"'.concat(n,'"の結果が見つかりませんでした。')},ko:function(n){return'"'.concat(n,'"에 대한 검색 결과가 없습니다')},nl:function(n){return'Geen resultaten voor "'.concat(n,'"')},no:function(n){return'Ingen resultater funnet for "'.concat(n,'"')},pl:function(n){return'Nie znaleziono wyników dla "'.concat(n,'"')},pt:function(n){return'Não foram encontrados resultados para "'.concat(n,'"')},"pt-br":function(n){return'Nenhum resultado encontrado para "'.concat(n,'"')},ro:function(n){return'Niciun rezultat pentru "'.concat(n,'"')},ru:function(n){return'По запросу "'.concat(n,'" ничего не найдено')},sk:function(n){return'Pre "'.concat(n,'" nebol nájdený žiadny výsledok')},sv:function(n){return'Inget resultat hittades för "'.concat(n,'"')},th:function(n){return'ไม่พบผลลัพธ์สำหรับ "'.concat(n,'"')},tr:function(n){return'"'.concat(n,'" için sonuç bulunamadı')},uk:function(n){return'Не знайдено результатів для "'.concat(n,'"')},vi:function(n){return'Không có kết quả được tìm thấy cho "'.concat(n,'"')},"zh-cn":function(n){return"未找到 “".concat(n,"” 的结果")},"zh-tw":function(n){return"查無 「".concat(n,"」 相關結果")}},placeholder:{ar:"البحث في مقالاتنا",bg:"Търсене в нашите статии",cs:"Hledat v našich článcích",da:"Søg i vores artikler",de:"In unseren Artikeln suchen",el:"Κάντε αναζήτηση στα άρθρα μας",en:"Search our articles",es:"Buscar en nuestros artículos",fi:"Etsi artikkeleista",fr:"Recherchez dans nos articles",hu:"Keresés a cikkeink között",id:"Cari di artikel kami",it:"Cerca nei nostri articoli",ja:"私たちの記事を検索します。",ko:"기사에서 검색",nl:"Zoeken in onze artikelen",no:"Søk i våre artikler",pl:"Szukaj w naszych artykułach",pt:"Pesquisar nos nossos artigos","pt-br":"Pesquise em nossos artigos",ro:"Căutați în articolele noastre",ru:"Найти в наших статьях",sk:"Vyhľadávať v našich článkoch",sv:"Sök bland våra artiklar",th:"ค้นหาในบทความของเรา",tr:"Yazılarımızda ara",uk:"Пошук у наших статтях",vi:"Tìm kiếm trong các bài viết của chúng tôi","zh-cn":"在我们的文章中搜索","zh-tw":"在文章中搜尋"},searchByAlgolia:{ar:function(n){return"البحث بواسطة ".concat(n)},bg:function(n){return"Търсене по ".concat(n)},cs:function(n){return"Vyhledávat s využitím služby ".concat(n)},da:function(n){return"Søg med ".concat(n)},de:function(n){return"Suche über ".concat(n)},el:function(n){return"Αναζήτηση κατά ".concat(n)},en:function(n){return"Search by ".concat(n)},es:function(n){return"Búsqueda por ".concat(n)},fi:function(n){return"Haun tarjoaa ".concat(n)},fr:function(n){return"Recherche par ".concat(n)},hu:function(n){return"Keresés az ".concat(n,"-val")},id:function(n){return"Cari menggunakan ".concat(n)},it:function(n){return"Cerca per ".concat(n)},ja:function(n){return"".concat(n,"で検索します。")},ko:function(n){return"".concat(n,"로 검색")},nl:function(n){return"Zoeken op ".concat(n)},no:function(n){return"Søk av ".concat(n)},pl:function(n){return"Szukaj przez ".concat(n)},pt:function(n){return"Pesquisar por ".concat(n)},"pt-br":function(n){return"Pesquise por ".concat(n)},ro:function(n){return"Căutați după ".concat(n)},ru:function(n){return"Найти в ".concat(n)},sk:function(n){return"Vyhľadávať podľa ".concat(n)},sv:function(n){return"Sök genom ".concat(n)},th:function(n){return"ค้นหาโดย ".concat(n)},tr:function(n){return"".concat(n,"'ya göre ara")},uk:function(n){return"Пошук за допомогою ".concat(n)},vi:function(n){return"Tìm kiếm theo ".concat(n)},"zh-cn":function(n){return"根据 ".concat(n," 搜索")},"zh-tw":function(n){return"使用 ".concat(n," 搜尋")}}};function r(t,r,o){var e=n[r]||"en",u=t[o]||c[o];if(null===u)throw new Error("Unknown translation key '".concat(o,"'."));if(null===u[e])throw new Error("No '".concat(e,"' (locale '").concat(r,"') entry for translation key '").concat(o,"'."));if("function"==typeof u[e]){for(var a=arguments.length,i=new Array(a>3?a-3:0),f=3;f<a;f++)i[f-3]=arguments[f];return u[e].apply(u,i)}return u[e]}
},{}],"qEIK":[function(require,module,exports) {
"use strict";function e(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function t(t){for(var n=1;n<arguments.length;n++){var o=null!=arguments[n]?arguments[n]:{};n%2?e(Object(o),!0).forEach(function(e){r(t,e,o[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(o)):e(Object(o)).forEach(function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(o,e))})}return t}function r(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function n(e,r,n,o,i){e.findAnswers(r,[n],{attributesForPrediction:["title","category","section","body_safe"],threshold:50,nbHits:1,params:t(t({},o),{},{highlightPreTag:"__aa-highlight__",highlightPostTag:"__/aa-highlight__"})}).then(i).catch(console.error)}function o(e,t){var r=void 0;return function(){for(var n=arguments.length,o=new Array(n),i=0;i<n;i++)o[i]=arguments[i];r&&clearTimeout(r),r=setTimeout(function(){return e.apply(null,o)},t)}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.debounceGetAnswers=void 0;var i=o(n,400);exports.debounceGetAnswers=i;
},{}],"lMlK":[function(require,module,exports) {
var define;
var e;!function(n){var t;if("function"==typeof e&&e.amd&&(e(n),t=!0),"object"==typeof exports&&(module.exports=n(),t=!0),!t){var o=window.Cookies,r=window.Cookies=n();r.noConflict=function(){return window.Cookies=o,r}}}(function(){function e(){for(var e=0,n={};e<arguments.length;e++){var t=arguments[e];for(var o in t)n[o]=t[o]}return n}function n(e){return e.replace(/(%[0-9A-Z]{2})+/g,decodeURIComponent)}return function t(o){function r(){}function i(n,t,i){if("undefined"!=typeof document){"number"==typeof(i=e({path:"/"},r.defaults,i)).expires&&(i.expires=new Date(1*new Date+864e5*i.expires)),i.expires=i.expires?i.expires.toUTCString():"";try{var c=JSON.stringify(t);/^[\{\[]/.test(c)&&(t=c)}catch(a){}t=o.write?o.write(t,n):encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g,decodeURIComponent),n=encodeURIComponent(String(n)).replace(/%(23|24|26|2B|5E|60|7C)/g,decodeURIComponent).replace(/[\(\)]/g,escape);var f="";for(var u in i)i[u]&&(f+="; "+u,!0!==i[u]&&(f+="="+i[u].split(";")[0]));return document.cookie=n+"="+t+f}}function c(e,t){if("undefined"!=typeof document){for(var r={},i=document.cookie?document.cookie.split("; "):[],c=0;c<i.length;c++){var f=i[c].split("="),u=f.slice(1).join("=");t||'"'!==u.charAt(0)||(u=u.slice(1,-1));try{var a=n(f[0]);if(u=(o.read||o)(u,a)||n(u),t)try{u=JSON.parse(u)}catch(p){}if(r[a]=u,e===a)break}catch(p){}}return e?r[e]:r}}return r.set=i,r.get=function(e){return c(e,!1)},r.getJSON=function(e){return c(e,!0)},r.remove=function(n,t){i(n,"",e(t,{expires:-1}))},r.defaults={},r.withConverter=t,r}(function(){})});
},{}],"MtmI":[function(require,module,exports) {
var global = arguments[3];
var r,e=arguments[3];exports.fetch=s(e.fetch)&&s(e.ReadableStream),exports.writableStream=s(e.WritableStream),exports.abortController=s(e.AbortController),exports.blobConstructor=!1;try{new Blob([new ArrayBuffer(1)]),exports.blobConstructor=!0}catch(f){}function t(){if(void 0!==r)return r;if(e.XMLHttpRequest){r=new e.XMLHttpRequest;try{r.open("GET",e.XDomainRequest?"/":"https://example.com")}catch(f){r=null}}else r=null;return r}function o(r){var e=t();if(!e)return!1;try{return e.responseType=r,e.responseType===r}catch(f){}return!1}var a=void 0!==e.ArrayBuffer,n=a&&s(e.ArrayBuffer.prototype.slice);function s(r){return"function"==typeof r}exports.arraybuffer=exports.fetch||a&&o("arraybuffer"),exports.msstream=!exports.fetch&&n&&o("ms-stream"),exports.mozchunkedarraybuffer=!exports.fetch&&a&&o("moz-chunked-arraybuffer"),exports.overrideMimeType=exports.fetch||!!t()&&s(t().overrideMimeType),exports.vbArray=s(e.VBArray),r=null;
},{}],"oxwV":[function(require,module,exports) {
"function"==typeof Object.create?module.exports=function(t,e){e&&(t.super_=e,t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:module.exports=function(t,e){if(e){t.super_=e;var o=function(){};o.prototype=e.prototype,t.prototype=new o,t.prototype.constructor=t}};
},{}],"g5IB":[function(require,module,exports) {
var t,e,n=module.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(t===setTimeout)return setTimeout(e,0);if((t===r||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}function u(t){if(e===clearTimeout)return clearTimeout(t);if((e===o||!e)&&clearTimeout)return e=clearTimeout,clearTimeout(t);try{return e(t)}catch(n){try{return e.call(null,t)}catch(n){return e.call(this,t)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:r}catch(n){t=r}try{e="function"==typeof clearTimeout?clearTimeout:o}catch(n){e=o}}();var c,s=[],l=!1,a=-1;function f(){l&&c&&(l=!1,c.length?s=c.concat(s):a=-1,s.length&&h())}function h(){if(!l){var t=i(f);l=!0;for(var e=s.length;e;){for(c=s,s=[];++a<e;)c&&c[a].run();a=-1,e=s.length}c=null,l=!1,u(t)}}function m(t,e){this.fun=t,this.array=e}function p(){}n.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];s.push(new m(t,e)),1!==s.length||l||i(h)},m.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.env={},n.argv=[],n.version="",n.versions={},n.on=p,n.addListener=p,n.once=p,n.off=p,n.removeListener=p,n.removeAllListeners=p,n.emit=p,n.prependListener=p,n.prependOnceListener=p,n.listeners=function(t){return[]},n.binding=function(t){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(t){throw new Error("process.chdir is not supported")},n.umask=function(){return 0};
},{}],"iFTO":[function(require,module,exports) {
var process = require("process");
var n=require("process");function e(e,r,t,c){if("function"!=typeof e)throw new TypeError('"callback" argument must be a function');var i,l,u=arguments.length;switch(u){case 0:case 1:return n.nextTick(e);case 2:return n.nextTick(function(){e.call(null,r)});case 3:return n.nextTick(function(){e.call(null,r,t)});case 4:return n.nextTick(function(){e.call(null,r,t,c)});default:for(i=new Array(u-1),l=0;l<i.length;)i[l++]=arguments[l];return n.nextTick(function(){e.apply(null,i)})}}void 0===n||!n.version||0===n.version.indexOf("v0.")||0===n.version.indexOf("v1.")&&0!==n.version.indexOf("v1.8.")?module.exports={nextTick:e}:module.exports=n;
},{"process":"g5IB"}],"wIHY":[function(require,module,exports) {
"use strict";var e,t="object"==typeof Reflect?Reflect:null,n=t&&"function"==typeof t.apply?t.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};function r(e){console&&console.warn&&console.warn(e)}e=t&&"function"==typeof t.ownKeys?t.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}module.exports=o,module.exports.once=m,o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var s=10;function u(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function f(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function v(e,t,n,i){var o,s,v;if(u(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),v=s[t]),void 0===v)v=s[t]=n,++e._eventsCount;else if("function"==typeof v?v=s[t]=i?[n,v]:[v,n]:i?v.unshift(n):v.push(n),(o=f(e))>0&&v.length>o&&!v.warned){v.warned=!0;var l=new Error("Possible EventEmitter memory leak detected. "+v.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");l.name="MaxListenersExceededWarning",l.emitter=e,l.type=t,l.count=v.length,r(l)}return e}function l(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function c(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=l.bind(r);return i.listener=n,r.wrapFn=i,i}function a(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?d(i):p(i,i.length)}function h(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function p(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function y(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function d(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function m(e,t){return new Promise(function(n,r){function i(){void 0!==o&&e.removeListener("error",o),n([].slice.call(arguments))}var o;"error"!==t&&(o=function(n){e.removeListener(t,i),r(n)},e.once("error",o)),e.once(t,i)})}Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return s},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");s=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return f(this)},o.prototype.emit=function(e){for(var t=[],r=1;r<arguments.length;r++)t.push(arguments[r]);var i="error"===e,o=this._events;if(void 0!==o)i=i&&void 0===o.error;else if(!i)return!1;if(i){var s;if(t.length>0&&(s=t[0]),s instanceof Error)throw s;var u=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw u.context=s,u}var f=o[e];if(void 0===f)return!1;if("function"==typeof f)n(f,this,t);else{var v=f.length,l=p(f,v);for(r=0;r<v;++r)n(l[r],this,t)}return!0},o.prototype.addListener=function(e,t){return v(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return v(this,e,t,!0)},o.prototype.once=function(e,t){return u(t),this.on(e,c(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return u(t),this.prependListener(e,c(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,r,i,o,s;if(u(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){s=n[o].listener,i=o;break}if(i<0)return this;0===i?n.shift():y(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,s||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,o=Object.keys(n);for(r=0;r<o.length;++r)"removeListener"!==(i=o[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return a(this,e,!0)},o.prototype.rawListeners=function(e){return a(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},o.prototype.listenerCount=h,o.prototype.eventNames=function(){return this._eventsCount>0?e(this._events):[]};
},{}],"o232":[function(require,module,exports) {
module.exports=require("events").EventEmitter;
},{"events":"wIHY"}],"gIYa":[function(require,module,exports) {
var r=require("buffer"),e=r.Buffer;function n(r,e){for(var n in r)e[n]=r[n]}function o(r,n,o){return e(r,n,o)}e.from&&e.alloc&&e.allocUnsafe&&e.allocUnsafeSlow?module.exports=r:(n(r,exports),exports.Buffer=o),n(e,o),o.from=function(r,n,o){if("number"==typeof r)throw new TypeError("Argument must not be a number");return e(r,n,o)},o.alloc=function(r,n,o){if("number"!=typeof r)throw new TypeError("Argument must be a number");var f=e(r);return void 0!==n?"string"==typeof o?f.fill(n,o):f.fill(n):f.fill(0),f},o.allocUnsafe=function(r){if("number"!=typeof r)throw new TypeError("Argument must be a number");return e(r)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)};
},{"buffer":"aMB2"}],"kj8s":[function(require,module,exports) {
var Buffer = require("buffer").Buffer;
var r=require("buffer").Buffer;function t(r){return Array.isArray?Array.isArray(r):"[object Array]"===a(r)}function e(r){return"boolean"==typeof r}function n(r){return null===r}function o(r){return null==r}function i(r){return"number"==typeof r}function u(r){return"string"==typeof r}function s(r){return"symbol"==typeof r}function f(r){return void 0===r}function p(r){return"[object RegExp]"===a(r)}function c(r){return"object"==typeof r&&null!==r}function l(r){return"[object Date]"===a(r)}function y(r){return"[object Error]"===a(r)||r instanceof Error}function x(r){return"function"==typeof r}function b(r){return null===r||"boolean"==typeof r||"number"==typeof r||"string"==typeof r||"symbol"==typeof r||void 0===r}function a(r){return Object.prototype.toString.call(r)}exports.isArray=t,exports.isBoolean=e,exports.isNull=n,exports.isNullOrUndefined=o,exports.isNumber=i,exports.isString=u,exports.isSymbol=s,exports.isUndefined=f,exports.isRegExp=p,exports.isObject=c,exports.isDate=l,exports.isError=y,exports.isFunction=x,exports.isPrimitive=b,exports.isBuffer=r.isBuffer;
},{"buffer":"aMB2"}],"m362":[function(require,module,exports) {
"use strict";function t(t,n){if(!(t instanceof n))throw new TypeError("Cannot call a class as a function")}var n=require("safe-buffer").Buffer,e=require("util");function i(t,n,e){t.copy(n,e)}module.exports=function(){function e(){t(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(t){var n={data:t,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},e.prototype.unshift=function(t){var n={data:t,next:this.head};0===this.length&&(this.tail=n),this.head=n,++this.length},e.prototype.shift=function(){if(0!==this.length){var t=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,t}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(t){if(0===this.length)return"";for(var n=this.head,e=""+n.data;n=n.next;)e+=t+n.data;return e},e.prototype.concat=function(t){if(0===this.length)return n.alloc(0);if(1===this.length)return this.head.data;for(var e=n.allocUnsafe(t>>>0),h=this.head,a=0;h;)i(h.data,e,a),a+=h.data.length,h=h.next;return e},e}(),e&&e.inspect&&e.inspect.custom&&(module.exports.prototype[e.inspect.custom]=function(){var t=e.inspect({length:this.length});return this.constructor.name+" "+t});
},{"safe-buffer":"gIYa","util":"DMuU"}],"Umu5":[function(require,module,exports) {
"use strict";var t=require("process-nextick-args");function e(e,a){var r=this,s=this._readableState&&this._readableState.destroyed,d=this._writableState&&this._writableState.destroyed;return s||d?(a?a(e):!e||this._writableState&&this._writableState.errorEmitted||t.nextTick(i,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!a&&e?(t.nextTick(i,r,e),r._writableState&&(r._writableState.errorEmitted=!0)):a&&a(e)}),this)}function a(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function i(t,e){t.emit("error",e)}module.exports={destroy:e,undestroy:a};
},{"process-nextick-args":"iFTO"}],"hQaz":[function(require,module,exports) {
var global = arguments[3];
var r=arguments[3];function t(r,t){if(e("noDeprecation"))return r;var n=!1;return function(){if(!n){if(e("throwDeprecation"))throw new Error(t);e("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return r.apply(this,arguments)}}function e(t){try{if(!r.localStorage)return!1}catch(n){return!1}var e=r.localStorage[t];return null!=e&&"true"===String(e).toLowerCase()}module.exports=t;
},{}],"pX9p":[function(require,module,exports) {
var process = require("process");
var global = arguments[3];
var e=require("process"),t=arguments[3],n=require("process-nextick-args");function r(e,t,n){this.chunk=e,this.encoding=t,this.callback=n,this.next=null}function i(e){var t=this;this.next=null,this.entry=null,this.finish=function(){W(t,e)}}module.exports=g;var o,s=n.nextTick;g.WritableState=y;var f=Object.create(require("core-util-is"));f.inherits=require("inherits");var u={deprecate:require("util-deprecate")},a=require("./internal/streams/stream"),c=require("safe-buffer").Buffer,l=t.Uint8Array||function(){};function d(e){return c.from(e)}function h(e){return c.isBuffer(e)||e instanceof l}var b,p=require("./internal/streams/destroy");function w(){}function y(e,t){o=o||require("./_stream_duplex"),e=e||{};var n=t instanceof o;this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var r=e.highWaterMark,s=e.writableHighWaterMark,f=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:n&&(s||0===s)?s:f,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var u=!1===e.decodeStrings;this.decodeStrings=!u,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){S(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new i(this)}function g(e){if(o=o||require("./_stream_duplex"),!(b.call(g,this)||this instanceof o))return new g(e);this._writableState=new y(e,this),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),a.call(this)}function k(e,t){var r=new Error("write after end");e.emit("error",r),n.nextTick(t,r)}function v(e,t,r,i){var o=!0,s=!1;return null===r?s=new TypeError("May not write null values to stream"):"string"==typeof r||void 0===r||t.objectMode||(s=new TypeError("Invalid non-string/buffer chunk")),s&&(e.emit("error",s),n.nextTick(i,s),o=!1),o}function q(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}function _(e,t,n,r,i,o){if(!n){var s=q(t,r,i);r!==s&&(n=!0,i="buffer",r=s)}var f=t.objectMode?1:r.length;t.length+=f;var u=t.length<t.highWaterMark;if(u||(t.needDrain=!0),t.writing||t.corked){var a=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:o,next:null},a?a.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else m(e,t,!1,f,r,i,o);return u}function m(e,t,n,r,i,o,s){t.writelen=r,t.writecb=s,t.writing=!0,t.sync=!0,n?e._writev(i,t.onwrite):e._write(i,o,t.onwrite),t.sync=!1}function R(e,t,r,i,o){--t.pendingcb,r?(n.nextTick(o,i),n.nextTick(T,e,t),e._writableState.errorEmitted=!0,e.emit("error",i)):(o(i),e._writableState.errorEmitted=!0,e.emit("error",i),T(e,t))}function x(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function S(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if(x(n),t)R(e,n,r,t,i);else{var o=E(n);o||n.corked||n.bufferProcessing||!n.bufferedRequest||B(e,n),r?s(M,e,n,o,i):M(e,n,o,i)}}function M(e,t,n,r){n||j(e,t),t.pendingcb--,r(),T(e,t)}function j(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function B(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var r=t.bufferedRequestCount,o=new Array(r),s=t.corkedRequestsFree;s.entry=n;for(var f=0,u=!0;n;)o[f]=n,n.isBuf||(u=!1),n=n.next,f+=1;o.allBuffers=u,m(e,t,!0,t.length,o,"",s.finish),t.pendingcb++,t.lastBufferedRequest=null,s.next?(t.corkedRequestsFree=s.next,s.next=null):t.corkedRequestsFree=new i(t),t.bufferedRequestCount=0}else{for(;n;){var a=n.chunk,c=n.encoding,l=n.callback;if(m(e,t,!1,t.objectMode?1:a.length,a,c,l),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function E(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function C(e,t){e._final(function(n){t.pendingcb--,n&&e.emit("error",n),t.prefinished=!0,e.emit("prefinish"),T(e,t)})}function P(e,t){t.prefinished||t.finalCalled||("function"==typeof e._final?(t.pendingcb++,t.finalCalled=!0,n.nextTick(C,e,t)):(t.prefinished=!0,e.emit("prefinish")))}function T(e,t){var n=E(t);return n&&(P(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"))),n}function F(e,t,r){t.ending=!0,T(e,t),r&&(t.finished?n.nextTick(r):e.once("finish",r)),t.ended=!0,e.writable=!1}function W(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(n),r=r.next}t.corkedRequestsFree?t.corkedRequestsFree.next=e:t.corkedRequestsFree=e}f.inherits(g,a),y.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(y.prototype,"buffer",{get:u.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(b=Function.prototype[Symbol.hasInstance],Object.defineProperty(g,Symbol.hasInstance,{value:function(e){return!!b.call(this,e)||this===g&&(e&&e._writableState instanceof y)}})):b=function(e){return e instanceof this},g.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))},g.prototype.write=function(e,t,n){var r=this._writableState,i=!1,o=!r.objectMode&&h(e);return o&&!c.isBuffer(e)&&(e=d(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":t||(t=r.defaultEncoding),"function"!=typeof n&&(n=w),r.ended?k(this,n):(o||v(this,r,e,n))&&(r.pendingcb++,i=_(this,r,o,e,t,n)),i},g.prototype.cork=function(){this._writableState.corked++},g.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.finished||e.bufferProcessing||!e.bufferedRequest||B(this,e))},g.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(g.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),g.prototype._write=function(e,t,n){n(new Error("_write() is not implemented"))},g.prototype._writev=null,g.prototype.end=function(e,t,n){var r=this._writableState;"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||r.finished||F(this,r,n)},Object.defineProperty(g.prototype,"destroyed",{get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),g.prototype.destroy=p.destroy,g.prototype._undestroy=p.undestroy,g.prototype._destroy=function(e,t){this.end(),t(e)};
},{"process-nextick-args":"iFTO","core-util-is":"kj8s","inherits":"oxwV","util-deprecate":"hQaz","./internal/streams/stream":"o232","safe-buffer":"gIYa","./internal/streams/destroy":"Umu5","./_stream_duplex":"gYn1","process":"g5IB"}],"gYn1":[function(require,module,exports) {
"use strict";var e=require("process-nextick-args"),t=Object.keys||function(e){var t=[];for(var r in e)t.push(r);return t};module.exports=l;var r=Object.create(require("core-util-is"));r.inherits=require("inherits");var i=require("./_stream_readable"),a=require("./_stream_writable");r.inherits(l,i);for(var o=t(a.prototype),s=0;s<o.length;s++){var n=o[s];l.prototype[n]||(l.prototype[n]=a.prototype[n])}function l(e){if(!(this instanceof l))return new l(e);i.call(this,e),a.call(this,e),e&&!1===e.readable&&(this.readable=!1),e&&!1===e.writable&&(this.writable=!1),this.allowHalfOpen=!0,e&&!1===e.allowHalfOpen&&(this.allowHalfOpen=!1),this.once("end",h)}function h(){this.allowHalfOpen||this._writableState.ended||e.nextTick(d,this)}function d(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed&&this._writableState.destroyed)},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}}),l.prototype._destroy=function(t,r){this.push(null),this.end(),e.nextTick(r,t)};
},{"process-nextick-args":"iFTO","core-util-is":"kj8s","inherits":"oxwV","./_stream_readable":"KTao","./_stream_writable":"pX9p"}],"ikue":[function(require,module,exports) {
"use strict";var t=require("safe-buffer").Buffer,e=t.isEncoding||function(t){switch((t=""+t)&&t.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!0;default:return!1}};function s(t){if(!t)return"utf8";for(var e;;)switch(t){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return t;default:if(e)return;t=(""+t).toLowerCase(),e=!0}}function i(i){var a=s(i);if("string"!=typeof a&&(t.isEncoding===e||!e(i)))throw new Error("Unknown encoding: "+i);return a||i}function a(e){var s;switch(this.encoding=i(e),this.encoding){case"utf16le":this.text=c,this.end=f,s=4;break;case"utf8":this.fillLast=l,s=4;break;case"base64":this.text=d,this.end=g,s=3;break;default:return this.write=N,void(this.end=v)}this.lastNeed=0,this.lastTotal=0,this.lastChar=t.allocUnsafe(s)}function r(t){return t<=127?0:t>>5==6?2:t>>4==14?3:t>>3==30?4:t>>6==2?-1:-2}function n(t,e,s){var i=e.length-1;if(i<s)return 0;var a=r(e[i]);return a>=0?(a>0&&(t.lastNeed=a-1),a):--i<s||-2===a?0:(a=r(e[i]))>=0?(a>0&&(t.lastNeed=a-2),a):--i<s||-2===a?0:(a=r(e[i]))>=0?(a>0&&(2===a?a=0:t.lastNeed=a-3),a):0}function h(t,e,s){if(128!=(192&e[0]))return t.lastNeed=0,"�";if(t.lastNeed>1&&e.length>1){if(128!=(192&e[1]))return t.lastNeed=1,"�";if(t.lastNeed>2&&e.length>2&&128!=(192&e[2]))return t.lastNeed=2,"�"}}function l(t){var e=this.lastTotal-this.lastNeed,s=h(this,t,e);return void 0!==s?s:this.lastNeed<=t.length?(t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(t.copy(this.lastChar,e,0,t.length),void(this.lastNeed-=t.length))}function u(t,e){var s=n(this,t,e);if(!this.lastNeed)return t.toString("utf8",e);this.lastTotal=s;var i=t.length-(s-this.lastNeed);return t.copy(this.lastChar,0,i),t.toString("utf8",e,i)}function o(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+"�":e}function c(t,e){if((t.length-e)%2==0){var s=t.toString("utf16le",e);if(s){var i=s.charCodeAt(s.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],s.slice(0,-1)}return s}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString("utf16le",e,t.length-1)}function f(t){var e=t&&t.length?this.write(t):"";if(this.lastNeed){var s=this.lastTotal-this.lastNeed;return e+this.lastChar.toString("utf16le",0,s)}return e}function d(t,e){var s=(t.length-e)%3;return 0===s?t.toString("base64",e):(this.lastNeed=3-s,this.lastTotal=3,1===s?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString("base64",e,t.length-s))}function g(t){var e=t&&t.length?this.write(t):"";return this.lastNeed?e+this.lastChar.toString("base64",0,3-this.lastNeed):e}function N(t){return t.toString(this.encoding)}function v(t){return t&&t.length?this.write(t):""}exports.StringDecoder=a,a.prototype.write=function(t){if(0===t.length)return"";var e,s;if(this.lastNeed){if(void 0===(e=this.fillLast(t)))return"";s=this.lastNeed,this.lastNeed=0}else s=0;return s<t.length?e?e+this.text(t,s):this.text(t,s):e||""},a.prototype.end=o,a.prototype.text=u,a.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};
},{"safe-buffer":"gIYa"}],"KTao":[function(require,module,exports) {
var global = arguments[3];
var process = require("process");
var e=arguments[3],t=require("process"),n=require("process-nextick-args");module.exports=_;var r,i=require("isarray");_.ReadableState=w;var a=require("events").EventEmitter,d=function(e,t){return e.listeners(t).length},o=require("./internal/streams/stream"),s=require("safe-buffer").Buffer,u=e.Uint8Array||function(){};function l(e){return s.from(e)}function h(e){return s.isBuffer(e)||e instanceof u}var p=Object.create(require("core-util-is"));p.inherits=require("inherits");var f=require("util"),c=void 0;c=f&&f.debuglog?f.debuglog("stream"):function(){};var g,b=require("./internal/streams/BufferList"),m=require("./internal/streams/destroy");p.inherits(_,o);var v=["error","close","destroy","pause","resume"];function y(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?i(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}function w(e,t){e=e||{};var n=t instanceof(r=r||require("./_stream_duplex"));this.objectMode=!!e.objectMode,n&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var i=e.highWaterMark,a=e.readableHighWaterMark,d=this.objectMode?16:16384;this.highWaterMark=i||0===i?i:n&&(a||0===a)?a:d,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new b,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(g||(g=require("string_decoder/").StringDecoder),this.decoder=new g(e.encoding),this.encoding=e.encoding)}function _(e){if(r=r||require("./_stream_duplex"),!(this instanceof _))return new _(e);this._readableState=new w(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),o.call(this)}function M(e,t,n,r,i){var a,d=e._readableState;null===t?(d.reading=!1,x(e,d)):(i||(a=k(d,t)),a?e.emit("error",a):d.objectMode||t&&t.length>0?("string"==typeof t||d.objectMode||Object.getPrototypeOf(t)===s.prototype||(t=l(t)),r?d.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):S(e,d,t,!0):d.ended?e.emit("error",new Error("stream.push() after EOF")):(d.reading=!1,d.decoder&&!n?(t=d.decoder.write(t),d.objectMode||0!==t.length?S(e,d,t,!1):C(e,d)):S(e,d,t,!1))):r||(d.reading=!1));return j(d)}function S(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(e.emit("data",n),e.read(0)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&q(e)),C(e,t)}function k(e,t){var n;return h(t)||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk")),n}function j(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||0===e.length)}Object.defineProperty(_.prototype,"destroyed",{get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),_.prototype.destroy=m.destroy,_.prototype._undestroy=m.undestroy,_.prototype._destroy=function(e,t){this.push(null),t(e)},_.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=s.from(e,t),t=""),n=!0),M(this,e,t,!1,n)},_.prototype.unshift=function(e){return M(this,e,null,!0,!1)},_.prototype.isPaused=function(){return!1===this._readableState.flowing},_.prototype.setEncoding=function(e){return g||(g=require("string_decoder/").StringDecoder),this._readableState.decoder=new g(e),this._readableState.encoding=e,this};var R=8388608;function E(e){return e>=R?e=R:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function L(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=E(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function x(e,t){if(!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,q(e)}}function q(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(c("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?n.nextTick(W,e):W(e))}function W(e){c("emit readable"),e.emit("readable"),B(e)}function C(e,t){t.readingMore||(t.readingMore=!0,n.nextTick(D,e,t))}function D(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&(c("maybeReadMore read 0"),e.read(0),n!==t.length);)n=t.length;t.readingMore=!1}function O(e){return function(){var t=e._readableState;c("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&d(e,"data")&&(t.flowing=!0,B(e))}}function T(e){c("readable nexttick read 0"),e.read(0)}function U(e,t){t.resumeScheduled||(t.resumeScheduled=!0,n.nextTick(P,e,t))}function P(e,t){t.reading||(c("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),B(e),t.flowing&&!t.reading&&e.read(0)}function B(e){var t=e._readableState;for(c("flow",t.flowing);t.flowing&&null!==e.read(););}function H(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=I(e,t.buffer,t.decoder),n);var n}function I(e,t,n){var r;return e<t.head.data.length?(r=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):r=e===t.head.data.length?t.shift():n?A(e,t):F(e,t),r}function A(e,t){var n=t.head,r=1,i=n.data;for(e-=i.length;n=n.next;){var a=n.data,d=e>a.length?a.length:e;if(d===a.length?i+=a:i+=a.slice(0,e),0===(e-=d)){d===a.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(d));break}++r}return t.length-=r,i}function F(e,t){var n=s.allocUnsafe(e),r=t.head,i=1;for(r.data.copy(n),e-=r.data.length;r=r.next;){var a=r.data,d=e>a.length?a.length:e;if(a.copy(n,n.length-e,0,d),0===(e-=d)){d===a.length?(++i,r.next?t.head=r.next:t.head=t.tail=null):(t.head=r,r.data=a.slice(d));break}++i}return t.length-=i,n}function z(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,n.nextTick(G,t,e))}function G(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function J(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}_.prototype.read=function(e){c("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return c("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?z(this):q(this),null;if(0===(e=L(e,t))&&t.ended)return 0===t.length&&z(this),null;var r,i=t.needReadable;return c("need readable",i),(0===t.length||t.length-e<t.highWaterMark)&&c("length less than watermark",i=!0),t.ended||t.reading?c("reading or ended",i=!1):i&&(c("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=L(n,t))),null===(r=e>0?H(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&z(this)),null!==r&&this.emit("data",r),r},_.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},_.prototype.pipe=function(e,r){var i=this,a=this._readableState;switch(a.pipesCount){case 0:a.pipes=e;break;case 1:a.pipes=[a.pipes,e];break;default:a.pipes.push(e)}a.pipesCount+=1,c("pipe count=%d opts=%j",a.pipesCount,r);var o=(!r||!1!==r.end)&&e!==t.stdout&&e!==t.stderr?u:v;function s(t,n){c("onunpipe"),t===i&&n&&!1===n.hasUnpiped&&(n.hasUnpiped=!0,c("cleanup"),e.removeListener("close",b),e.removeListener("finish",m),e.removeListener("drain",l),e.removeListener("error",g),e.removeListener("unpipe",s),i.removeListener("end",u),i.removeListener("end",v),i.removeListener("data",f),h=!0,!a.awaitDrain||e._writableState&&!e._writableState.needDrain||l())}function u(){c("onend"),e.end()}a.endEmitted?n.nextTick(o):i.once("end",o),e.on("unpipe",s);var l=O(i);e.on("drain",l);var h=!1;var p=!1;function f(t){c("ondata"),p=!1,!1!==e.write(t)||p||((1===a.pipesCount&&a.pipes===e||a.pipesCount>1&&-1!==J(a.pipes,e))&&!h&&(c("false write response, pause",i._readableState.awaitDrain),i._readableState.awaitDrain++,p=!0),i.pause())}function g(t){c("onerror",t),v(),e.removeListener("error",g),0===d(e,"error")&&e.emit("error",t)}function b(){e.removeListener("finish",m),v()}function m(){c("onfinish"),e.removeListener("close",b),v()}function v(){c("unpipe"),i.unpipe(e)}return i.on("data",f),y(e,"error",g),e.once("close",b),e.once("finish",m),e.emit("pipe",i),a.flowing||(c("pipe resume"),i.resume()),e},_.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<i;a++)r[a].emit("unpipe",this,n);return this}var d=J(t.pipes,e);return-1===d?this:(t.pipes.splice(d,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n),this)},_.prototype.on=function(e,t){var r=o.prototype.on.call(this,e,t);if("data"===e)!1!==this._readableState.flowing&&this.resume();else if("readable"===e){var i=this._readableState;i.endEmitted||i.readableListening||(i.readableListening=i.needReadable=!0,i.emittedReadable=!1,i.reading?i.length&&q(this):n.nextTick(T,this))}return r},_.prototype.addListener=_.prototype.on,_.prototype.resume=function(){var e=this._readableState;return e.flowing||(c("resume"),e.flowing=!0,U(this,e)),this},_.prototype.pause=function(){return c("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(c("pause"),this._readableState.flowing=!1,this.emit("pause")),this},_.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var i in e.on("end",function(){if(c("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)}),e.on("data",function(i){(c("wrapped data"),n.decoder&&(i=n.decoder.write(i)),n.objectMode&&null==i)||(n.objectMode||i&&i.length)&&(t.push(i)||(r=!0,e.pause()))}),e)void 0===this[i]&&"function"==typeof e[i]&&(this[i]=function(t){return function(){return e[t].apply(e,arguments)}}(i));for(var a=0;a<v.length;a++)e.on(v[a],this.emit.bind(this,v[a]));return this._read=function(t){c("wrapped _read",t),r&&(r=!1,e.resume())},this},Object.defineProperty(_.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),_._fromList=H;
},{"process-nextick-args":"iFTO","isarray":"aqZJ","events":"wIHY","./internal/streams/stream":"o232","safe-buffer":"gIYa","core-util-is":"kj8s","inherits":"oxwV","util":"DMuU","./internal/streams/BufferList":"m362","./internal/streams/destroy":"Umu5","./_stream_duplex":"gYn1","string_decoder/":"ikue","process":"g5IB"}],"PxOV":[function(require,module,exports) {
"use strict";module.exports=n;var t=require("./_stream_duplex"),r=Object.create(require("core-util-is"));function e(t,r){var e=this._transformState;e.transforming=!1;var n=e.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));e.writechunk=null,e.writecb=null,null!=r&&this.push(r),n(t);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function n(r){if(!(this instanceof n))return new n(r);t.call(this,r),this._transformState={afterTransform:e.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,r&&("function"==typeof r.transform&&(this._transform=r.transform),"function"==typeof r.flush&&(this._flush=r.flush)),this.on("prefinish",i)}function i(){var t=this;"function"==typeof this._flush?this._flush(function(r,e){a(t,r,e)}):a(this,null,null)}function a(t,r,e){if(r)return t.emit("error",r);if(null!=e&&t.push(e),t._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(t._transformState.transforming)throw new Error("Calling transform done when still transforming");return t.push(null)}r.inherits=require("inherits"),r.inherits(n,t),n.prototype.push=function(r,e){return this._transformState.needTransform=!1,t.prototype.push.call(this,r,e)},n.prototype._transform=function(t,r,e){throw new Error("_transform() is not implemented")},n.prototype._write=function(t,r,e){var n=this._transformState;if(n.writecb=e,n.writechunk=t,n.writeencoding=r,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},n.prototype._read=function(t){var r=this._transformState;null!==r.writechunk&&r.writecb&&!r.transforming?(r.transforming=!0,this._transform(r.writechunk,r.writeencoding,r.afterTransform)):r.needTransform=!0},n.prototype._destroy=function(r,e){var n=this;t.prototype._destroy.call(this,r,function(t){e(t),n.emit("close")})};
},{"./_stream_duplex":"gYn1","core-util-is":"kj8s","inherits":"oxwV"}],"pumY":[function(require,module,exports) {
"use strict";module.exports=t;var r=require("./_stream_transform"),e=Object.create(require("core-util-is"));function t(e){if(!(this instanceof t))return new t(e);r.call(this,e)}e.inherits=require("inherits"),e.inherits(t,r),t.prototype._transform=function(r,e,t){t(null,r)};
},{"./_stream_transform":"PxOV","core-util-is":"kj8s","inherits":"oxwV"}],"YvpY":[function(require,module,exports) {
exports=module.exports=require("./lib/_stream_readable.js"),exports.Stream=exports,exports.Readable=exports,exports.Writable=require("./lib/_stream_writable.js"),exports.Duplex=require("./lib/_stream_duplex.js"),exports.Transform=require("./lib/_stream_transform.js"),exports.PassThrough=require("./lib/_stream_passthrough.js");
},{"./lib/_stream_readable.js":"KTao","./lib/_stream_writable.js":"pX9p","./lib/_stream_duplex.js":"gYn1","./lib/_stream_transform.js":"PxOV","./lib/_stream_passthrough.js":"pumY"}],"K8Qe":[function(require,module,exports) {
var process = require("process");
var Buffer = require("buffer").Buffer;
var global = arguments[3];
var e=require("process"),r=require("buffer").Buffer,t=arguments[3],s=require("./capability"),a=require("inherits"),o=require("readable-stream"),n=exports.readyStates={UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4},u=exports.IncomingMessage=function(a,n,u,i){var c=this;if(o.Readable.call(c),c._mode=u,c.headers={},c.rawHeaders=[],c.trailers={},c.rawTrailers=[],c.on("end",function(){e.nextTick(function(){c.emit("close")})}),"fetch"===u){if(c._fetchResponse=n,c.url=n.url,c.statusCode=n.status,c.statusMessage=n.statusText,n.headers.forEach(function(e,r){c.headers[r.toLowerCase()]=e,c.rawHeaders.push(r,e)}),s.writableStream){var d=new WritableStream({write:function(e){return new Promise(function(t,s){c._destroyed?s():c.push(new r(e))?t():c._resumeFetch=t})},close:function(){t.clearTimeout(i),c._destroyed||c.push(null)},abort:function(e){c._destroyed||c.emit("error",e)}});try{return void n.body.pipeTo(d).catch(function(e){t.clearTimeout(i),c._destroyed||c.emit("error",e)})}catch(p){}}var h=n.body.getReader();!function e(){h.read().then(function(s){if(!c._destroyed){if(s.done)return t.clearTimeout(i),void c.push(null);c.push(new r(s.value)),e()}}).catch(function(e){t.clearTimeout(i),c._destroyed||c.emit("error",e)})}()}else{if(c._xhr=a,c._pos=0,c.url=a.responseURL,c.statusCode=a.status,c.statusMessage=a.statusText,a.getAllResponseHeaders().split(/\r?\n/).forEach(function(e){var r=e.match(/^([^:]+):\s*(.*)/);if(r){var t=r[1].toLowerCase();"set-cookie"===t?(void 0===c.headers[t]&&(c.headers[t]=[]),c.headers[t].push(r[2])):void 0!==c.headers[t]?c.headers[t]+=", "+r[2]:c.headers[t]=r[2],c.rawHeaders.push(r[1],r[2])}}),c._charset="x-user-defined",!s.overrideMimeType){var f=c.rawHeaders["mime-type"];if(f){var l=f.match(/;\s*charset=([^;])(;|$)/);l&&(c._charset=l[1].toLowerCase())}c._charset||(c._charset="utf-8")}}};a(u,o.Readable),u.prototype._read=function(){var e=this._resumeFetch;e&&(this._resumeFetch=null,e())},u.prototype._onXHRProgress=function(){var e=this,s=e._xhr,a=null;switch(e._mode){case"text:vbarray":if(s.readyState!==n.DONE)break;try{a=new t.VBArray(s.responseBody).toArray()}catch(d){}if(null!==a){e.push(new r(a));break}case"text":try{a=s.responseText}catch(d){e._mode="text:vbarray";break}if(a.length>e._pos){var o=a.substr(e._pos);if("x-user-defined"===e._charset){for(var u=new r(o.length),i=0;i<o.length;i++)u[i]=255&o.charCodeAt(i);e.push(u)}else e.push(o,e._charset);e._pos=a.length}break;case"arraybuffer":if(s.readyState!==n.DONE||!s.response)break;a=s.response,e.push(new r(new Uint8Array(a)));break;case"moz-chunked-arraybuffer":if(a=s.response,s.readyState!==n.LOADING||!a)break;e.push(new r(new Uint8Array(a)));break;case"ms-stream":if(a=s.response,s.readyState!==n.LOADING)break;var c=new t.MSStreamReader;c.onprogress=function(){c.result.byteLength>e._pos&&(e.push(new r(new Uint8Array(c.result.slice(e._pos)))),e._pos=c.result.byteLength)},c.onload=function(){e.push(null)},c.readAsArrayBuffer(a)}e._xhr.readyState===n.DONE&&"ms-stream"!==e._mode&&e.push(null)};
},{"./capability":"MtmI","inherits":"oxwV","readable-stream":"YvpY","process":"g5IB","buffer":"aMB2"}],"xHkA":[function(require,module,exports) {
var e=require("buffer").Buffer;module.exports=function(f){if(f instanceof Uint8Array){if(0===f.byteOffset&&f.byteLength===f.buffer.byteLength)return f.buffer;if("function"==typeof f.buffer.slice)return f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength)}if(e.isBuffer(f)){for(var r=new Uint8Array(f.length),t=f.length,n=0;n<t;n++)r[n]=f[n];return r.buffer}throw new Error("Argument must be a Buffer")};
},{"buffer":"aMB2"}],"p71p":[function(require,module,exports) {
var Buffer = require("buffer").Buffer;
var global = arguments[3];
var process = require("process");
var e=require("buffer").Buffer,t=arguments[3],r=require("process"),o=require("./capability"),n=require("inherits"),i=require("./response"),s=require("readable-stream"),a=require("to-arraybuffer"),c=i.IncomingMessage,u=i.readyStates;function d(e,t){return o.fetch&&t?"fetch":o.mozchunkedarraybuffer?"moz-chunked-arraybuffer":o.msstream?"ms-stream":o.arraybuffer&&e?"arraybuffer":o.vbArray&&e?"text:vbarray":"text"}var f=module.exports=function(t){var r,n=this;s.Writable.call(n),n._opts=t,n._body=[],n._headers={},t.auth&&n.setHeader("Authorization","Basic "+new e(t.auth).toString("base64")),Object.keys(t.headers).forEach(function(e){n.setHeader(e,t.headers[e])});var i=!0;if("disable-fetch"===t.mode||"requestTimeout"in t&&!o.abortController)i=!1,r=!0;else if("prefer-streaming"===t.mode)r=!1;else if("allow-wrong-content-type"===t.mode)r=!o.overrideMimeType;else{if(t.mode&&"default"!==t.mode&&"prefer-fast"!==t.mode)throw new Error("Invalid value for opts.mode");r=!0}n._mode=d(r,i),n._fetchTimer=null,n.on("finish",function(){n._onFinish()})};function h(e){try{var t=e.status;return null!==t&&0!==t}catch(r){return!1}}n(f,s.Writable),f.prototype.setHeader=function(e,t){var r=e.toLowerCase();-1===p.indexOf(r)&&(this._headers[r]={name:e,value:t})},f.prototype.getHeader=function(e){var t=this._headers[e.toLowerCase()];return t?t.value:null},f.prototype.removeHeader=function(e){delete this._headers[e.toLowerCase()]},f.prototype._onFinish=function(){var n=this;if(!n._destroyed){var i=n._opts,s=n._headers,c=null;"GET"!==i.method&&"HEAD"!==i.method&&(c=o.arraybuffer?a(e.concat(n._body)):o.blobConstructor?new t.Blob(n._body.map(function(e){return a(e)}),{type:(s["content-type"]||{}).value||""}):e.concat(n._body).toString());var d=[];if(Object.keys(s).forEach(function(e){var t=s[e].name,r=s[e].value;Array.isArray(r)?r.forEach(function(e){d.push([t,e])}):d.push([t,r])}),"fetch"===n._mode){var f=null;if(o.abortController){var h=new AbortController;f=h.signal,n._fetchAbortController=h,"requestTimeout"in i&&0!==i.requestTimeout&&(n._fetchTimer=t.setTimeout(function(){n.emit("requestTimeout"),n._fetchAbortController&&n._fetchAbortController.abort()},i.requestTimeout))}t.fetch(n._opts.url,{method:n._opts.method,headers:d,body:c||void 0,mode:"cors",credentials:i.withCredentials?"include":"same-origin",signal:f}).then(function(e){n._fetchResponse=e,n._connect()},function(e){t.clearTimeout(n._fetchTimer),n._destroyed||n.emit("error",e)})}else{var p=n._xhr=new t.XMLHttpRequest;try{p.open(n._opts.method,n._opts.url,!0)}catch(l){return void r.nextTick(function(){n.emit("error",l)})}"responseType"in p&&(p.responseType=n._mode.split(":")[0]),"withCredentials"in p&&(p.withCredentials=!!i.withCredentials),"text"===n._mode&&"overrideMimeType"in p&&p.overrideMimeType("text/plain; charset=x-user-defined"),"requestTimeout"in i&&(p.timeout=i.requestTimeout,p.ontimeout=function(){n.emit("requestTimeout")}),d.forEach(function(e){p.setRequestHeader(e[0],e[1])}),n._response=null,p.onreadystatechange=function(){switch(p.readyState){case u.LOADING:case u.DONE:n._onXHRProgress()}},"moz-chunked-arraybuffer"===n._mode&&(p.onprogress=function(){n._onXHRProgress()}),p.onerror=function(){n._destroyed||n.emit("error",new Error("XHR error"))};try{p.send(c)}catch(l){return void r.nextTick(function(){n.emit("error",l)})}}}},f.prototype._onXHRProgress=function(){h(this._xhr)&&!this._destroyed&&(this._response||this._connect(),this._response._onXHRProgress())},f.prototype._connect=function(){var e=this;e._destroyed||(e._response=new c(e._xhr,e._fetchResponse,e._mode,e._fetchTimer),e._response.on("error",function(t){e.emit("error",t)}),e.emit("response",e._response))},f.prototype._write=function(e,t,r){this._body.push(e),r()},f.prototype.abort=f.prototype.destroy=function(){this._destroyed=!0,t.clearTimeout(this._fetchTimer),this._response&&(this._response._destroyed=!0),this._xhr?this._xhr.abort():this._fetchAbortController&&this._fetchAbortController.abort()},f.prototype.end=function(e,t,r){"function"==typeof e&&(r=e,e=void 0),s.Writable.prototype.end.call(this,e,t,r)},f.prototype.flushHeaders=function(){},f.prototype.setTimeout=function(){},f.prototype.setNoDelay=function(){},f.prototype.setSocketKeepAlive=function(){};var p=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","cookie","cookie2","date","dnt","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"];
},{"./capability":"MtmI","inherits":"oxwV","./response":"K8Qe","readable-stream":"YvpY","to-arraybuffer":"xHkA","buffer":"aMB2","process":"g5IB"}],"YxsI":[function(require,module,exports) {
module.exports=o;var r=Object.prototype.hasOwnProperty;function o(){for(var o={},t=0;t<arguments.length;t++){var e=arguments[t];for(var a in e)r.call(e,a)&&(o[a]=e[a])}return o}
},{}],"XmSl":[function(require,module,exports) {
module.exports={100:"Continue",101:"Switching Protocols",102:"Processing",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Unordered Collection",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"};
},{}],"GVK8":[function(require,module,exports) {
var global = arguments[3];
var define;
var o,e=arguments[3];!function(n){var r="object"==typeof exports&&exports&&!exports.nodeType&&exports,t="object"==typeof module&&module&&!module.nodeType&&module,u="object"==typeof e&&e;u.global!==u&&u.window!==u&&u.self!==u||(n=u);var i,f,c=2147483647,l=36,s=1,p=26,a=38,d=700,h=72,v=128,g="-",w=/^xn--/,x=/[^\x20-\x7E]/,y=/[\x2E\u3002\uFF0E\uFF61]/g,m={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},C=l-s,b=Math.floor,j=String.fromCharCode;function A(o){throw new RangeError(m[o])}function I(o,e){for(var n=o.length,r=[];n--;)r[n]=e(o[n]);return r}function E(o,e){var n=o.split("@"),r="";return n.length>1&&(r=n[0]+"@",o=n[1]),r+I((o=o.replace(y,".")).split("."),e).join(".")}function F(o){for(var e,n,r=[],t=0,u=o.length;t<u;)(e=o.charCodeAt(t++))>=55296&&e<=56319&&t<u?56320==(64512&(n=o.charCodeAt(t++)))?r.push(((1023&e)<<10)+(1023&n)+65536):(r.push(e),t--):r.push(e);return r}function O(o){return I(o,function(o){var e="";return o>65535&&(e+=j((o-=65536)>>>10&1023|55296),o=56320|1023&o),e+=j(o)}).join("")}function S(o,e){return o+22+75*(o<26)-((0!=e)<<5)}function T(o,e,n){var r=0;for(o=n?b(o/d):o>>1,o+=b(o/e);o>C*p>>1;r+=l)o=b(o/C);return b(r+(C+1)*o/(o+a))}function L(o){var e,n,r,t,u,i,f,a,d,w,x,y=[],m=o.length,C=0,j=v,I=h;for((n=o.lastIndexOf(g))<0&&(n=0),r=0;r<n;++r)o.charCodeAt(r)>=128&&A("not-basic"),y.push(o.charCodeAt(r));for(t=n>0?n+1:0;t<m;){for(u=C,i=1,f=l;t>=m&&A("invalid-input"),((a=(x=o.charCodeAt(t++))-48<10?x-22:x-65<26?x-65:x-97<26?x-97:l)>=l||a>b((c-C)/i))&&A("overflow"),C+=a*i,!(a<(d=f<=I?s:f>=I+p?p:f-I));f+=l)i>b(c/(w=l-d))&&A("overflow"),i*=w;I=T(C-u,e=y.length+1,0==u),b(C/e)>c-j&&A("overflow"),j+=b(C/e),C%=e,y.splice(C++,0,j)}return O(y)}function M(o){var e,n,r,t,u,i,f,a,d,w,x,y,m,C,I,E=[];for(y=(o=F(o)).length,e=v,n=0,u=h,i=0;i<y;++i)(x=o[i])<128&&E.push(j(x));for(r=t=E.length,t&&E.push(g);r<y;){for(f=c,i=0;i<y;++i)(x=o[i])>=e&&x<f&&(f=x);for(f-e>b((c-n)/(m=r+1))&&A("overflow"),n+=(f-e)*m,e=f,i=0;i<y;++i)if((x=o[i])<e&&++n>c&&A("overflow"),x==e){for(a=n,d=l;!(a<(w=d<=u?s:d>=u+p?p:d-u));d+=l)I=a-w,C=l-w,E.push(j(S(w+I%C,0))),a=b(I/C);E.push(j(S(a,0))),u=T(n,m,r==t),n=0,++r}++n,++e}return E.join("")}if(i={version:"1.4.1",ucs2:{decode:F,encode:O},decode:L,encode:M,toASCII:function(o){return E(o,function(o){return x.test(o)?"xn--"+M(o):o})},toUnicode:function(o){return E(o,function(o){return w.test(o)?L(o.slice(4).toLowerCase()):o})}},"function"==typeof o&&"object"==typeof o.amd&&o.amd)o("punycode",function(){return i});else if(r&&t)if(module.exports==r)t.exports=i;else for(f in i)i.hasOwnProperty(f)&&(r[f]=i[f]);else n.punycode=i}(this);
},{}],"oHuK":[function(require,module,exports) {
"use strict";module.exports={isString:function(n){return"string"==typeof n},isObject:function(n){return"object"==typeof n&&null!==n},isNull:function(n){return null===n},isNullOrUndefined:function(n){return null==n}};
},{}],"ObZ4":[function(require,module,exports) {
"use strict";function r(r,e){return Object.prototype.hasOwnProperty.call(r,e)}module.exports=function(t,n,o,a){n=n||"&",o=o||"=";var s={};if("string"!=typeof t||0===t.length)return s;var p=/\+/g;t=t.split(n);var u=1e3;a&&"number"==typeof a.maxKeys&&(u=a.maxKeys);var c=t.length;u>0&&c>u&&(c=u);for(var i=0;i<c;++i){var y,l,f,v,b=t[i].replace(p,"%20"),d=b.indexOf(o);d>=0?(y=b.substr(0,d),l=b.substr(d+1)):(y=b,l=""),f=decodeURIComponent(y),v=decodeURIComponent(l),r(s,f)?e(s[f])?s[f].push(v):s[f]=[s[f],v]:s[f]=v}return s};var e=Array.isArray||function(r){return"[object Array]"===Object.prototype.toString.call(r)};
},{}],"XK8a":[function(require,module,exports) {
"use strict";var n=function(n){switch(typeof n){case"string":return n;case"boolean":return n?"true":"false";case"number":return isFinite(n)?n:"";default:return""}};module.exports=function(o,u,c,a){return u=u||"&",c=c||"=",null===o&&(o=void 0),"object"==typeof o?r(t(o),function(t){var a=encodeURIComponent(n(t))+c;return e(o[t])?r(o[t],function(e){return a+encodeURIComponent(n(e))}).join(u):a+encodeURIComponent(n(o[t]))}).join(u):a?encodeURIComponent(n(a))+c+encodeURIComponent(n(o)):""};var e=Array.isArray||function(n){return"[object Array]"===Object.prototype.toString.call(n)};function r(n,e){if(n.map)return n.map(e);for(var r=[],t=0;t<n.length;t++)r.push(e(n[t],t));return r}var t=Object.keys||function(n){var e=[];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&e.push(r);return e};
},{}],"SF0R":[function(require,module,exports) {
"use strict";exports.decode=exports.parse=require("./decode"),exports.encode=exports.stringify=require("./encode");
},{"./decode":"ObZ4","./encode":"XK8a"}],"j37I":[function(require,module,exports) {
"use strict";var t=require("punycode"),s=require("./util");function h(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}exports.parse=b,exports.resolve=O,exports.resolveObject=d,exports.format=q,exports.Url=h;var e=/^([a-z0-9.+-]+:)/i,a=/:[0-9]*$/,r=/^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,o=["<",">",'"',"`"," ","\r","\n","\t"],n=["{","}","|","\\","^","`"].concat(o),i=["'"].concat(n),l=["%","/","?",";","#"].concat(i),p=["/","?","#"],c=255,u=/^[+a-z0-9A-Z_-]{0,63}$/,f=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,m={javascript:!0,"javascript:":!0},v={javascript:!0,"javascript:":!0},g={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},y=require("querystring");function b(t,e,a){if(t&&s.isObject(t)&&t instanceof h)return t;var r=new h;return r.parse(t,e,a),r}function q(t){return s.isString(t)&&(t=b(t)),t instanceof h?t.format():h.prototype.format.call(t)}function O(t,s){return b(t,!1,!0).resolve(s)}function d(t,s){return t?b(t,!1,!0).resolveObject(s):s}h.prototype.parse=function(h,a,o){if(!s.isString(h))throw new TypeError("Parameter 'url' must be a string, not "+typeof h);var n=h.indexOf("?"),b=-1!==n&&n<h.indexOf("#")?"?":"#",q=h.split(b);q[0]=q[0].replace(/\\/g,"/");var O=h=q.join(b);if(O=O.trim(),!o&&1===h.split("#").length){var d=r.exec(O);if(d)return this.path=O,this.href=O,this.pathname=d[1],d[2]?(this.search=d[2],this.query=a?y.parse(this.search.substr(1)):this.search.substr(1)):a&&(this.search="",this.query={}),this}var j=e.exec(O);if(j){var x=(j=j[0]).toLowerCase();this.protocol=x,O=O.substr(j.length)}if(o||j||O.match(/^\/\/[^@\/]+@[^@\/]+/)){var A="//"===O.substr(0,2);!A||j&&v[j]||(O=O.substr(2),this.slashes=!0)}if(!v[j]&&(A||j&&!g[j])){for(var C,I,w=-1,U=0;U<p.length;U++){-1!==(k=O.indexOf(p[U]))&&(-1===w||k<w)&&(w=k)}-1!==(I=-1===w?O.lastIndexOf("@"):O.lastIndexOf("@",w))&&(C=O.slice(0,I),O=O.slice(I+1),this.auth=decodeURIComponent(C)),w=-1;for(U=0;U<l.length;U++){var k;-1!==(k=O.indexOf(l[U]))&&(-1===w||k<w)&&(w=k)}-1===w&&(w=O.length),this.host=O.slice(0,w),O=O.slice(w),this.parseHost(),this.hostname=this.hostname||"";var N="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!N)for(var R=this.hostname.split(/\./),S=(U=0,R.length);U<S;U++){var $=R[U];if($&&!$.match(u)){for(var z="",H=0,L=$.length;H<L;H++)$.charCodeAt(H)>127?z+="x":z+=$[H];if(!z.match(u)){var Z=R.slice(0,U),_=R.slice(U+1),E=$.match(f);E&&(Z.push(E[1]),_.unshift(E[2])),_.length&&(O="/"+_.join(".")+O),this.hostname=Z.join(".");break}}}this.hostname.length>c?this.hostname="":this.hostname=this.hostname.toLowerCase(),N||(this.hostname=t.toASCII(this.hostname));var P=this.port?":"+this.port:"",T=this.hostname||"";this.host=T+P,this.href+=this.host,N&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==O[0]&&(O="/"+O))}if(!m[x])for(U=0,S=i.length;U<S;U++){var B=i[U];if(-1!==O.indexOf(B)){var D=encodeURIComponent(B);D===B&&(D=escape(B)),O=O.split(B).join(D)}}var F=O.indexOf("#");-1!==F&&(this.hash=O.substr(F),O=O.slice(0,F));var G=O.indexOf("?");if(-1!==G?(this.search=O.substr(G),this.query=O.substr(G+1),a&&(this.query=y.parse(this.query)),O=O.slice(0,G)):a&&(this.search="",this.query={}),O&&(this.pathname=O),g[x]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){P=this.pathname||"";var J=this.search||"";this.path=P+J}return this.href=this.format(),this},h.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var h=this.protocol||"",e=this.pathname||"",a=this.hash||"",r=!1,o="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&s.isObject(this.query)&&Object.keys(this.query).length&&(o=y.stringify(this.query));var n=this.search||o&&"?"+o||"";return h&&":"!==h.substr(-1)&&(h+=":"),this.slashes||(!h||g[h])&&!1!==r?(r="//"+(r||""),e&&"/"!==e.charAt(0)&&(e="/"+e)):r||(r=""),a&&"#"!==a.charAt(0)&&(a="#"+a),n&&"?"!==n.charAt(0)&&(n="?"+n),h+r+(e=e.replace(/[?#]/g,function(t){return encodeURIComponent(t)}))+(n=n.replace("#","%23"))+a},h.prototype.resolve=function(t){return this.resolveObject(b(t,!1,!0)).format()},h.prototype.resolveObject=function(t){if(s.isString(t)){var e=new h;e.parse(t,!1,!0),t=e}for(var a=new h,r=Object.keys(this),o=0;o<r.length;o++){var n=r[o];a[n]=this[n]}if(a.hash=t.hash,""===t.href)return a.href=a.format(),a;if(t.slashes&&!t.protocol){for(var i=Object.keys(t),l=0;l<i.length;l++){var p=i[l];"protocol"!==p&&(a[p]=t[p])}return g[a.protocol]&&a.hostname&&!a.pathname&&(a.path=a.pathname="/"),a.href=a.format(),a}if(t.protocol&&t.protocol!==a.protocol){if(!g[t.protocol]){for(var c=Object.keys(t),u=0;u<c.length;u++){var f=c[u];a[f]=t[f]}return a.href=a.format(),a}if(a.protocol=t.protocol,t.host||v[t.protocol])a.pathname=t.pathname;else{for(var m=(t.pathname||"").split("/");m.length&&!(t.host=m.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==m[0]&&m.unshift(""),m.length<2&&m.unshift(""),a.pathname=m.join("/")}if(a.search=t.search,a.query=t.query,a.host=t.host||"",a.auth=t.auth,a.hostname=t.hostname||t.host,a.port=t.port,a.pathname||a.search){var y=a.pathname||"",b=a.search||"";a.path=y+b}return a.slashes=a.slashes||t.slashes,a.href=a.format(),a}var q=a.pathname&&"/"===a.pathname.charAt(0),O=t.host||t.pathname&&"/"===t.pathname.charAt(0),d=O||q||a.host&&t.pathname,j=d,x=a.pathname&&a.pathname.split("/")||[],A=(m=t.pathname&&t.pathname.split("/")||[],a.protocol&&!g[a.protocol]);if(A&&(a.hostname="",a.port=null,a.host&&(""===x[0]?x[0]=a.host:x.unshift(a.host)),a.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===m[0]?m[0]=t.host:m.unshift(t.host)),t.host=null),d=d&&(""===m[0]||""===x[0])),O)a.host=t.host||""===t.host?t.host:a.host,a.hostname=t.hostname||""===t.hostname?t.hostname:a.hostname,a.search=t.search,a.query=t.query,x=m;else if(m.length)x||(x=[]),x.pop(),x=x.concat(m),a.search=t.search,a.query=t.query;else if(!s.isNullOrUndefined(t.search)){if(A)a.hostname=a.host=x.shift(),(k=!!(a.host&&a.host.indexOf("@")>0)&&a.host.split("@"))&&(a.auth=k.shift(),a.host=a.hostname=k.shift());return a.search=t.search,a.query=t.query,s.isNull(a.pathname)&&s.isNull(a.search)||(a.path=(a.pathname?a.pathname:"")+(a.search?a.search:"")),a.href=a.format(),a}if(!x.length)return a.pathname=null,a.search?a.path="/"+a.search:a.path=null,a.href=a.format(),a;for(var C=x.slice(-1)[0],I=(a.host||t.host||x.length>1)&&("."===C||".."===C)||""===C,w=0,U=x.length;U>=0;U--)"."===(C=x[U])?x.splice(U,1):".."===C?(x.splice(U,1),w++):w&&(x.splice(U,1),w--);if(!d&&!j)for(;w--;w)x.unshift("..");!d||""===x[0]||x[0]&&"/"===x[0].charAt(0)||x.unshift(""),I&&"/"!==x.join("/").substr(-1)&&x.push("");var k,N=""===x[0]||x[0]&&"/"===x[0].charAt(0);A&&(a.hostname=a.host=N?"":x.length?x.shift():"",(k=!!(a.host&&a.host.indexOf("@")>0)&&a.host.split("@"))&&(a.auth=k.shift(),a.host=a.hostname=k.shift()));return(d=d||a.host&&x.length)&&!N&&x.unshift(""),x.length?a.pathname=x.join("/"):(a.pathname=null,a.path=null),s.isNull(a.pathname)&&s.isNull(a.search)||(a.path=(a.pathname?a.pathname:"")+(a.search?a.search:"")),a.auth=t.auth||a.auth,a.slashes=a.slashes||t.slashes,a.href=a.format(),a},h.prototype.parseHost=function(){var t=this.host,s=a.exec(t);s&&(":"!==(s=s[0])&&(this.port=s.substr(1)),t=t.substr(0,t.length-s.length)),t&&(this.hostname=t)};
},{"punycode":"GVK8","./util":"oHuK","querystring":"SF0R"}],"f2Kk":[function(require,module,exports) {
var global = arguments[3];
var e=arguments[3],t=require("./lib/request"),r=require("./lib/response"),n=require("xtend"),o=require("builtin-status-codes"),s=require("url"),u=exports;u.request=function(r,o){r="string"==typeof r?s.parse(r):n(r);var u=-1===e.location.protocol.search(/^https?:$/)?"http:":"",E=r.protocol||u,a=r.hostname||r.host,C=r.port,i=r.path||"/";a&&-1!==a.indexOf(":")&&(a="["+a+"]"),r.url=(a?E+"//"+a:"")+(C?":"+C:"")+i,r.method=(r.method||"GET").toUpperCase(),r.headers=r.headers||{};var T=new t(r);return o&&T.on("response",o),T},u.get=function(e,t){var r=u.request(e,t);return r.end(),r},u.ClientRequest=t,u.IncomingMessage=r.IncomingMessage,u.Agent=function(){},u.Agent.defaultMaxSockets=4,u.globalAgent=new u.Agent,u.STATUS_CODES=o,u.METHODS=["CHECKOUT","CONNECT","COPY","DELETE","GET","HEAD","LOCK","M-SEARCH","MERGE","MKACTIVITY","MKCOL","MOVE","NOTIFY","OPTIONS","PATCH","POST","PROPFIND","PROPPATCH","PURGE","PUT","REPORT","SEARCH","SUBSCRIBE","TRACE","UNLOCK","UNSUBSCRIBE"];
},{"./lib/request":"p71p","./lib/response":"K8Qe","xtend":"YxsI","builtin-status-codes":"XmSl","url":"j37I"}],"AHs6":[function(require,module,exports) {
var t=require("http"),r=require("url"),o=module.exports;for(var e in t)t.hasOwnProperty(e)&&(o[e]=t[e]);function p(t){if("string"==typeof t&&(t=r.parse(t)),t.protocol||(t.protocol="https:"),"https:"!==t.protocol)throw new Error('Protocol "'+t.protocol+'" not supported. Expected "https:"');return t}o.request=function(r,o){return r=p(r),t.request.call(this,r,o)},o.get=function(r,o){return r=p(r),t.get.call(this,r,o)};
},{"http":"f2Kk","url":"j37I"}],"EmJS":[function(require,module,exports) {
"use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(){"function"!=typeof Object.assign&&(Object.assign=function(e,t){var r=arguments;if(null==e)throw new TypeError("Cannot convert undefined or null to object");for(var n=Object(e),o=1;o<arguments.length;o++){var i=r[o];if(null!=i)for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(n[s]=i[s])}return n})}function r(){var t,r,n,o;Object.keys||(Object.keys=(t=Object.prototype.hasOwnProperty,r=!{toString:null}.propertyIsEnumerable("toString"),o=(n=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"]).length,function(i){if("function"!=typeof i&&("object"!=e(i)||null===i))throw new TypeError("Object.keys called on non-object");var s,a,c=[];for(s in i)t.call(i,s)&&c.push(s);if(r)for(a=0;a<o;a++)t.call(i,n[a])&&c.push(n[a]);return c}))}Object.defineProperty(exports,"__esModule",{value:!0});var n=function(){try{return Boolean(navigator.cookieEnabled)}catch(e){return!1}},o=function(){try{var e=require("http").request,t=require("https").request;return Boolean(e)&&Boolean(t)}catch(e){return!1}},i=function(e){return void 0===e},s=function(e){return"string"==typeof e},a=function(e){return"number"==typeof e},c=function(e){return"function"==typeof e};function u(e){return function(t,r){if(!this._userHasOptedOut){if(!this._hasCredentials)throw new Error("Before calling any methods on the analytics, you first need to call the 'init' function with appId and apiKey parameters");if(""===r.userToken||""===this._userToken)throw new Error("`userToken` cannot be an empty string.");var n=r.userToken||this._userToken;if(i(n))throw new Error("Before calling any methods on the analytics, you first need to call 'setUserToken' function or include 'userToken' in the event payload.");if(!s(r.index))throw new TypeError("expected required parameter `index` to be a string");if(!s(r.eventName))throw new TypeError("expected required parameter `eventName` to be a string");if(!i(r.userToken)&&!s(r.userToken))throw new TypeError("expected optional parameter `userToken` to be a string");var o={eventType:t,eventName:r.eventName,userToken:n,index:r.index};if(!i(r.timestamp)){if(!a(r.timestamp))throw new TypeError("expected optional parameter `timestamp` to be a number");o.timestamp=r.timestamp}if(!i(r.queryID)){if(!s(r.queryID))throw new TypeError("expected optional parameter `queryID` to be a string");o.queryID=r.queryID}if(!i(r.objectIDs)){if(!Array.isArray(r.objectIDs))throw new TypeError("expected optional parameter `objectIDs` to be an array");o.objectIDs=r.objectIDs}if(!i(r.positions)){if(!Array.isArray(r.positions))throw new TypeError("expected optional parameter `positions` to be an array");if(i(r.objectIDs))throw new Error("cannot use `positions` without providing `objectIDs`");if(r.objectIDs.length!==r.positions.length)throw new Error("objectIDs and positions need to be of the same size");o.positions=r.positions}if(!i(r.filters)){if(!i(r.objectIDs))throw new Error("cannot use `objectIDs` and `filters` for the same event");if(!Array.isArray(r.filters))throw new TypeError("expected optional parameter `filters` to be an array");o.filters=r.filters}if(i(r.objectIDs)&&i(r.filters))throw new Error("expected either `objectIDs` or `filters` to be provided");return p(e,this._appId,this._apiKey,this._uaURIEncoded,this._endpointOrigin,[o])}}}function p(e,t,r,n,o,i){return e(o+"/1/events?X-Algolia-Application-Id="+t+"&X-Algolia-API-Key="+r+"&X-Algolia-Agent="+n,{events:i})}var h="1.6.3",f="insights-js ("+h+")";function l(e){-1===this._ua.indexOf("; "+e)&&(this._ua+="; "+e,this._uaURIEncoded=encodeURIComponent(this._ua))}var d=["de","us"],w=2592e6;function b(e){if(!e)throw new Error("Init function should be called with an object argument containing your apiKey and appId");if(i(e.apiKey)||!s(e.apiKey))throw new Error("apiKey is missing, please provide it so we can authenticate the application");if(i(e.appId)||!s(e.appId))throw new Error("appId is missing, please provide it, so we can properly attribute data to your application");if(!i(e.region)&&-1===d.indexOf(e.region))throw new Error("optional region is incorrect, please provide either one of: "+d.join(", ")+".");if(!(i(e.cookieDuration)||a(e.cookieDuration)&&isFinite(e.cookieDuration)&&Math.floor(e.cookieDuration)===e.cookieDuration))throw new Error("optional cookieDuration is incorrect, expected an integer.");this._apiKey=e.apiKey,this._appId=e.appId,this._userHasOptedOut=!!e.userHasOptedOut,this._region=e.region,this._endpointOrigin=e.region?"https://insights."+e.region+".algolia.io":"https://insights.algolia.io",this._cookieDuration=e.cookieDuration?e.cookieDuration:6*w,this._hasCredentials=!0,this._ua=f,this._uaURIEncoded=encodeURIComponent(f),!this._userHasOptedOut&&n()&&this.setUserToken(this.ANONYMOUS_USER_TOKEN)}function y(e,t){t(this[e])}function v(e){if(!this._hasCredentials)throw new Error("Before calling any methods on the analytics, you first need to call the 'init' function with appId and apiKey parameters");if(!e)throw new Error("initSearch function requires an argument with getQueryID and hitsContainer arguments");if(!e.getQueryID||"function"!=typeof e.getQueryID)throw new Error("getQueryID must be a function that returns the queryID of the last search operation");this.getQueryID=e.getQueryID}function m(e){if(!e)throw new Error("No params were sent to clickedObjectIDsAfterSearch function, please provide `queryID`, `objectIDs` and `positions` to be reported");if(!e.queryID)throw new Error("required queryID parameter was not sent, click event can not be properly sent without");if(!e.objectIDs)throw new Error("required objectIDs parameter was not sent, click event can not be properly sent without");if(!e.positions)throw new Error("required positions parameter was not sent, click event can not be properly sent without");this.sendEvent("click",e)}function I(e){if(!e)throw new Error("No params were sent to clickedObjectIDs function, please provide `objectIDs` to be reported");if(!e.objectIDs)throw new Error("required `objectIDs` parameter was not sent, click event can not be properly sent without");this.sendEvent("click",e)}function g(e){if(!e)throw new Error("No params were sent to clickedFilters function, please provide `filters` to be reported");if(!e.filters)throw new Error("required `filters` parameter was not sent, click event can not be properly sent without");this.sendEvent("click",e)}function E(e){if(!e)throw new Error("No params were sent to convertedObjectIDsAfterSearch function, please provide `queryID` and `objectIDs` to be reported");if(!e.queryID)throw new Error("required queryID parameter was not sent, conversion event can not be properly sent without");if(!e.objectIDs)throw new Error("required objectIDs parameter was not sent, conversion event can not be properly sent without");this.sendEvent("conversion",e)}function D(e){if(!e)throw new Error("No params were sent to convertedObjectIDs function, please provide `objectIDs` to be reported");if(!e.objectIDs)throw new Error("required objectIDs parameter was not sent, conversion event can not be properly sent without");this.sendEvent("conversion",e)}function k(e){if(!e)throw new Error("No params were sent to convertedFilters function, please provide `filters` to be reported");if(!e.filters)throw new Error("required filters parameter was not sent, conversion event can not be properly sent without");this.sendEvent("conversion",e)}function x(e){if(!e)throw new Error("No params were sent to viewedObjectIDs function, please provide `objectIDs` to be reported");if(!e.objectIDs)throw new Error("required objectIDs parameter was not sent, view event can not be properly sent without");this.sendEvent("view",e)}function j(e){if(!e)throw new Error("No params were sent to viewedFilters function, please provide `filters` to be reported");if(!e.filters)throw new Error("required filters parameter was not sent, view event can not be properly sent without");this.sendEvent("view",e)}var O=function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,function(e){var t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})},T="_ALGOLIA",_=function(e,t,r){var n=new Date;n.setTime(n.getTime()+r);var o="expires="+n.toUTCString();document.cookie=e+"="+t+";"+o+";path=/"},q=function(e){for(var t=e+"=",r=document.cookie.split(";"),n=0;n<r.length;n++){for(var o=r[n];" "===o.charAt(0);)o=o.substring(1);if(0===o.indexOf(t))return o.substring(t.length,o.length)}return""},S="ANONYMOUS_USER_TOKEN";function A(e){if(e===S){if(!n())throw new Error("Tracking of anonymous users is only possible on environments which support cookies.");var t=q(T);t&&""!==t&&0===t.indexOf("anonymous-")?this._userToken=t:(this._userToken="anonymous-"+O(),_(T,this._userToken,this._cookieDuration))}else this._userToken=e;c(this._onUserTokenChangeCallback)&&this._onUserTokenChangeCallback(this._userToken)}function C(e,t){return c(t)&&t(null,this._userToken),this._userToken}function U(e,t){this._onUserTokenChangeCallback=e,t&&t.immediate&&c(this._onUserTokenChangeCallback)&&this._onUserTokenChangeCallback(this._userToken)}r(),t();var N=function(e){var t=e.requestFn;this._ua="",this._uaURIEncoded="",this.version=h,this._hasCredentials=!1,this.sendEvent=u(t).bind(this),this.init=b.bind(this),this.initSearch=v.bind(this),this.addAlgoliaAgent=l.bind(this),this.ANONYMOUS_USER_TOKEN=S,this.setUserToken=A.bind(this),this.getUserToken=C.bind(this),this.onUserTokenChange=U.bind(this),this.clickedObjectIDsAfterSearch=m.bind(this),this.clickedObjectIDs=I.bind(this),this.clickedFilters=g.bind(this),this.convertedObjectIDsAfterSearch=E.bind(this),this.convertedObjectIDs=D.bind(this),this.convertedFilters=k.bind(this),this.viewedObjectIDs=x.bind(this),this.viewedFilters=j.bind(this),this._get=y.bind(this)};function K(e){return function(t){for(var r=[],n=arguments.length-1;n-- >0;)r[n]=arguments[n+1];t&&c(e[t])&&e[t].apply(e,r)}}var F=function(e,t){var r=JSON.stringify(t),n=require("url").parse(e),o={protocol:n.protocol,host:n.host,path:n.path,method:"POST",headers:{"Content-Type":"application/json","Content-Length":r.length}},i=(0,(0===e.indexOf("https://")?require("https"):require("http")).request)(o);i.on("error",function(e){console.error(e)}),i.write(r),i.end()};function R(){if(o())return F;throw new Error("Could not find a supported HTTP request client in this environment.")}function P(e){return K(new N({requestFn:e}))}var B=P(R());exports.createInsightsClient=P,exports.default=B;
},{"http":"f2Kk","https":"AHs6","url":"j37I"}],"cD9B":[function(require,module,exports) {
var e=require("./dist/search-insights.cjs.min.js");module.exports=e.default,Object.keys(e).forEach(function(s){"default"!==s&&(module.exports[s]=e[s])});
},{"./dist/search-insights.cjs.min.js":"EmJS"}],"pCMn":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.initInsights=r,exports.extendWithConversionTracking=c;var e=i(require("js-cookie")),t=i(require("search-insights"));function i(e){return e&&e.__esModule?e:{default:e}}function r(e){var i=e.applicationId,r=e.apiKey;(0,t.default)("init",{appId:i,apiKey:r})}function c(i,r){var c=r.clickAnalytics,a=r.indexName;if(!c)return i.trackClick=function(){},void(i.trackConversion=function(){});var n=function(t,i){var r=JSON.stringify({queryID:t,objectID:i.objectID,articleID:i.id});e.default.set("algolia-last-click",r,{expires:1})};i.trackClick=function(e,i,r){n(r,e),(0,t.default)("clickedObjectIDsAfterSearch",{eventName:"article_clicked",index:a,queryID:r,objectIDs:[e.objectID],positions:[Number(i)]})},i.trackConversion=function(i){var r=e.default.get("algolia-last-click");if(r){var c=JSON.parse(r);c.queryID&&c.objectID&&c.articleID&&i===c.articleID&&((0,t.default)("convertedObjectIDsAfterSearch",{index:a,eventName:"article_conversion",queryID:c.queryID,objectIDs:[c.objectID]}),n(c.queryID,{}))}}}
},{"js-cookie":"lMlK","search-insights":"cD9B"}],"Zhwq":[function(require,module,exports) {
"use strict";function e(e){return{add:function(t){e.onRemove(t.objectID),e.onAdd(t)},remove:function(t){e.onRemove(t)},getAll:function(t){return e.getAll(t)}}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.createStore=e;
},{}],"fWia":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getTemplates=e;var t=require("@algolia/autocomplete-js");function e(e){var a=e.onRemove,c=e.onTapAhead;return{item:function(e){var o=e.item,i=e.createElement;return i(e.Fragment,null,i("div",{className:"aa-ItemIcon aa-ItemIcon--no-border"},i("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"currentColor"},i("path",{d:"M12.516 6.984v5.25l4.5 2.672-0.75 1.266-5.25-3.188v-6h1.5zM12 20.016q3.281 0 5.648-2.367t2.367-5.648-2.367-5.648-5.648-2.367-5.648 2.367-2.367 5.648 2.367 5.648 5.648 2.367zM12 2.016q4.125 0 7.055 2.93t2.93 7.055-2.93 7.055-7.055 2.93-7.055-2.93-2.93-7.055 2.93-7.055 7.055-2.93z"}))),i("div",{className:"aa-ItemContent"},i("div",{className:"aa-ItemContentTitle"},(0,t.reverseHighlightHit)({hit:o,attribute:"query",createElement:i})),o.category&&i("div",{className:"aa-ItemContentSubtitle"},"– in ",o.category)),i("div",{className:"aa-ItemActions"},i("button",{className:"aa-ItemActionButton",title:"Remove this search",onClick:function(t){t.stopPropagation(),a(o.objectID)}},i("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"currentColor"},i("path",{d:"M18 7v13c0 0.276-0.111 0.525-0.293 0.707s-0.431 0.293-0.707 0.293h-10c-0.276 0-0.525-0.111-0.707-0.293s-0.293-0.431-0.293-0.707v-13zM17 5v-1c0-0.828-0.337-1.58-0.879-2.121s-1.293-0.879-2.121-0.879h-4c-0.828 0-1.58 0.337-2.121 0.879s-0.879 1.293-0.879 2.121v1h-4c-0.552 0-1 0.448-1 1s0.448 1 1 1h1v13c0 0.828 0.337 1.58 0.879 2.121s1.293 0.879 2.121 0.879h10c0.828 0 1.58-0.337 2.121-0.879s0.879-1.293 0.879-2.121v-13h1c0.552 0 1-0.448 1-1s-0.448-1-1-1zM9 5v-1c0-0.276 0.111-0.525 0.293-0.707s0.431-0.293 0.707-0.293h4c0.276 0 0.525 0.111 0.707 0.293s0.293 0.431 0.293 0.707v1zM9 11v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1zM13 11v6c0 0.552 0.448 1 1 1s1-0.448 1-1v-6c0-0.552-0.448-1-1-1s-1 0.448-1 1z"}))),i("button",{className:"aa-ItemActionButton",title:'Fill query with "'.concat(o.query,'"'),onClick:function(t){t.stopPropagation(),c(o)}},i("svg",{viewBox:"0 0 24 24",width:"18",height:"18",fill:"currentColor"},i("path",{d:"M8 17v-7.586l8.293 8.293c0.391 0.391 1.024 0.391 1.414 0s0.391-1.024 0-1.414l-8.293-8.293h7.586c0.552 0 1-0.448 1-1s-0.448-1-1-1h-10c-0.552 0-1 0.448-1 1v10c0 0.552 0.448 1 1 1s1-0.448 1-1z"})))))}}}
},{"@algolia/autocomplete-js":"mF0j"}],"W1YW":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createRecentSearchesPlugin=y;var e=require("@algolia/autocomplete-shared"),r=require("./createStore"),t=require("./getTemplates");function n(e){return a(e)||c(e)||u(e)||o()}function o(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function u(e,r){if(e){if("string"==typeof e)return i(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?i(e,r):void 0}}function c(e){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e))return Array.from(e)}function a(e){if(Array.isArray(e))return i(e)}function i(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function s(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function l(e){for(var r=1;r<arguments.length;r++){var t=null!=arguments[r]?arguments[r]:{};r%2?s(Object(t),!0).forEach(function(r){f(e,r,t[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(t)):s(Object(t)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(t,r))})}return e}function f(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function y(o){var u=o.storage,c=o.transformSource,a=void 0===c?function(e){return e.source}:c,i=(0,r.createStore)(u),s=(0,e.createRef)([]);return{subscribe:function(e){(0,e.onSelect)(function(e){var r=e.item,t=e.state,n=e.source,o=n.getItemInputValue({item:r,state:t});"querySuggestionsPlugin"===n.sourceId&&o&&i.add({objectID:o,query:o,category:r.__autocomplete_qsCategory})})},onSubmit:function(e){var r=e.state.query;r&&i.add({objectID:r,query:r})},getSources:function(e){var r=e.query,n=e.setQuery,o=e.refresh;function u(e){i.remove(e),o()}function c(e){n(e.query),o()}return s.current=i.getAll(r),Promise.resolve(s.current).then(function(e){return 0===e.length?[]:[a({source:{sourceId:"recentSearchesPlugin",getItemInputValue:function(e){return e.item.query},getItems:function(){return e},templates:(0,t.getTemplates)({onRemove:u,onTapAhead:c})},onRemove:u,onTapAhead:c})]})},data:{getAlgoliaSearchParams:function(){var e,r,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(s.current)?l(l({},t),{},{facetFilters:[].concat(n(null!==(e=t.facetFilters)&&void 0!==e?e:[]),n(s.current.map(function(e){return["objectID:-".concat(e.query)]}))),hitsPerPage:Math.max(1,(null!==(r=t.hitsPerPage)&&void 0!==r?r:10)-s.current.length)}):t}}}}
},{"@algolia/autocomplete-shared":"uvJf","./createStore":"Zhwq","./getTemplates":"fWia"}],"Y9te":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.LOCAL_STORAGE_KEY_TEST=exports.LOCAL_STORAGE_KEY=void 0;var E="AUTOCOMPLETE_RECENT_SEARCHES";exports.LOCAL_STORAGE_KEY=E;var _="__AUTOCOMPLETE_RECENT_SEARCHES_PLUGIN_TEST_KEY__";exports.LOCAL_STORAGE_KEY_TEST=_;
},{}],"SKZx":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isLocalStorageSupported=t;var e=require("./constants");function t(){try{return localStorage.setItem(e.LOCAL_STORAGE_KEY_TEST,""),localStorage.removeItem(e.LOCAL_STORAGE_KEY_TEST),!0}catch(t){return!1}}
},{"./constants":"Y9te"}],"VN2H":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getLocalStorage=t;var e=require("./isLocalStorageSupported");function t(t){var r=t.key;return(0,e.isLocalStorageSupported)()?{setItem:function(e){return window.localStorage.setItem(r,JSON.stringify(e))},getItem:function(){var e=window.localStorage.getItem(r);return e?JSON.parse(e):[]}}:{setItem:function(){},getItem:function(){return[]}}}
},{"./isLocalStorageSupported":"SKZx"}],"E2q5":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createLocalStorage=c;var t=require("./getLocalStorage");function e(t){return i(t)||o(t)||n(t)||r()}function r(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(t,e){if(t){if("string"==typeof t)return a(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(t,e):void 0}}function o(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}function i(t){if(Array.isArray(t))return a(t)}function a(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function c(r){var n=r.key,o=r.limit,i=r.search,a=(0,t.getLocalStorage)({key:n});return{getAll:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";return i({query:t,items:a.getItem(),limit:o}).slice(0,o)},onAdd:function(t){a.setItem([t].concat(e(a.getItem())))},onRemove:function(t){a.setItem(a.getItem().filter(function(e){return e.objectID!==t}))}}}
},{"./getLocalStorage":"VN2H"}],"IEDF":[function(require,module,exports) {
"use strict";function e(e,r){var t=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);r&&(n=n.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),t.push.apply(t,n)}return t}function r(r){for(var n=1;n<arguments.length;n++){var i=null!=arguments[n]?arguments[n]:{};n%2?e(Object(i),!0).forEach(function(e){t(r,e,i[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(i)):e(Object(i)).forEach(function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(i,e))})}return r}function t(e,r,t){return r in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}function n(e){var t=e.item,n=e.query;return r(r({},t),{},{_highlightResult:{query:{value:n?t.query.replace(new RegExp(n.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),"g"),"__aa-highlight__".concat(n,"__/aa-highlight__")):t.query}}})}function i(e){var r=e.query,t=e.items,i=e.limit;return r?t.filter(function(e){return e.query.toLowerCase().includes(r.toLowerCase())}).slice(0,i).map(function(e){return n({item:e,query:r})}):t.slice(0,i).map(function(e){return n({item:e,query:r})})}Object.defineProperty(exports,"__esModule",{value:!0}),exports.search=i;
},{}],"gKCV":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./constants");Object.keys(e).forEach(function(r){"default"!==r&&"__esModule"!==r&&(r in exports&&exports[r]===e[r]||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}}))});var r=require("./getLocalStorage");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var t=require("./createLocalStorage");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});var o=require("./search");Object.keys(o).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===o[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return o[e]}}))});
},{"./constants":"Y9te","./getLocalStorage":"VN2H","./createLocalStorage":"E2q5","./search":"IEDF"}],"nHHp":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.createLocalStorageRecentSearchesPlugin=a;var e=require("./createRecentSearchesPlugin"),r=require("./usecases/localStorage");function a(a){var t=a.key,c=a.limit,o=void 0===c?5:c,s=a.transformSource,i=a.search,n=void 0===i?r.search:i,u=(0,r.createLocalStorage)({key:[r.LOCAL_STORAGE_KEY,t].join(":"),limit:o,search:n});return(0,e.createRecentSearchesPlugin)({transformSource:s,storage:u})}
},{"./createRecentSearchesPlugin":"W1YW","./usecases/localStorage":"gKCV"}],"xTJl":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("./createLocalStorageRecentSearchesPlugin");Object.keys(e).forEach(function(r){"default"!==r&&"__esModule"!==r&&(r in exports&&exports[r]===e[r]||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}}))});var r=require("./createRecentSearchesPlugin");Object.keys(r).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===r[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return r[e]}}))});var t=require("./getTemplates");Object.keys(t).forEach(function(e){"default"!==e&&"__esModule"!==e&&(e in exports&&exports[e]===t[e]||Object.defineProperty(exports,e,{enumerable:!0,get:function(){return t[e]}}))});
},{"./createLocalStorageRecentSearchesPlugin":"nHHp","./createRecentSearchesPlugin":"W1YW","./getTemplates":"fWia"}],"QpCc":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=require("../package.json"),t=s(require("algoliasearch/lite")),r=require("@algolia/autocomplete-js");require("@algolia/autocomplete-theme-classic");var n=require("preact"),a=require("lodash"),o=s(require("./translations")),c=require("./answers"),i=require("./clickAnalytics"),l=require("@algolia/autocomplete-plugin-recent-searches"),u=require("@algolia/autocomplete-plugin-recent-searches/dist/esm/usecases/localStorage");function s(e){return e&&e.__esModule?e:{default:e}}function f(e,t,r){return(f=p()?Reflect.construct:function(e,t,r){var n=[null];n.push.apply(n,t);var a=new(Function.bind.apply(e,n));return r&&y(a,r.prototype),a}).apply(null,arguments)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function y(e,t){return(y=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function d(e,t){return b(e)||v(e,t)||h(e,t)||m()}function m(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function h(e,t){if(e){if("string"==typeof e)return g(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?g(e,t):void 0}}function g(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function v(e,t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(e)){var r=[],n=!0,a=!1,o=void 0;try{for(var c,i=e[Symbol.iterator]();!(n=(c=i.next()).done)&&(r.push(c.value),!t||r.length!==t);n=!0);}catch(l){a=!0,o=l}finally{try{n||null==i.return||i.return()}finally{if(a)throw o}}return r}}function b(e){if(Array.isArray(e))return e}function O(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function P(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?O(Object(r),!0).forEach(function(t){q(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):O(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function q(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function j(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function w(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function S(e,t,r){return t&&w(e.prototype,t),r&&w(e,r),e}var x=function(){function s(r){var n=r.applicationId,a=r.apiKey,o=r.autocomplete.enabled,c=r.indexPrefix,l=r.subdomain,u=r.clickAnalytics;j(this,s),o&&(this.client=(0,t.default)(n,a),this.client.addAlgoliaAgent("Zendesk Integration (".concat(e.version,")")),this.indexName="".concat(c).concat(l,"_articles"),u&&((0,i.initInsights)({applicationId:n,apiKey:a}),(0,i.extendWithConversionTracking)(this,{clickAnalytics:u,indexName:this.indexName})))}return S(s,[{key:"init",value:function(e){var t=e.analytics,i=e.autocomplete,s=i.enabled,f=i.hitsPerPage,p=i.inputSelector,y=e.baseUrl,m=e.color,h=e.clickAnalytics,g=e.debug,v=e.locale,b=e.highlightColor,O=e.poweredBy,q=e.templates,j=e.translations;if(s){var w=document.documentElement;w.style.setProperty("--aa-primary-color",m),w.style.setProperty("--aa-highlight-color",b),w.style.setProperty("--aa-detached-modal-max-width","960px"),w.style.setProperty("--aa-detached-modal-max-height","80%");var S={analytics:t,hitsPerPage:f,facetFilters:'["locale.locale:'.concat(v,'"]'),attributesToSnippet:["body_safe:30"],snippetEllipsisText:"…"},x=this,A={current:[]},I=v.split("-")[0];(0,r.autocomplete)({container:p,placeholder:(0,o.default)(j,v,"placeholder"),detachedMediaQuery:"",debug:g,plugins:[(0,l.createLocalStorageRecentSearchesPlugin)({key:"algolia-recent-searches",search:function(e){var t=e.query,r=e.items,n=e.limit,a=(0,u.search)({query:t,items:r,limit:n});return 1===a.length&&a[0].query===t?[]:a},transformSource:function(e){return P(P({},e.source),{},{onSelect:function(e){(0,e.setIsOpen)(!0)}})}})],openOnFocus:!0,onStateChange:function(e){var t=e.prevState,r=e.state,n=e.refresh;t.query!==r.query&&(0,c.debounceGetAnswers)(x.client.initIndex(x.indexName),r.query,I,{facetFilters:'["locale.locale:'.concat(v,'"]')},function(e){var t=e.hits;A.current=t,n()})},getSources:function(e){var t=e.query,n={sourceId:"Answers",getItems:function(){return A.current},getItemUrl:function(e){var t=e.item;return"".concat(y).concat(v,"/articles/").concat(t.id)},templates:{header:function(e){var t=e.items;return 0===t.length?null:q.autocomplete.bestArticleHeader(j,v,t)},item:function(e){var t=e.item;return q.autocomplete.article(t)}}};return(0,r.getAlgoliaHits)({searchClient:x.client,queries:[{indexName:x.indexName,query:t,params:P(P({},S),{},{clickAnalytics:h,queryLanguages:[I],removeStopWords:!0})}]}).then(function(e){var t=(0,a.groupBy)(e[0],function(e){return"".concat(e.category.title," > ").concat(e.section.title)});return Object.entries(t).map(function(e){var t=d(e,2),r=t[0],n=t[1];return{sourceId:r,getItems:function(){return n},getItemUrl:function(e){var t=e.item;return"".concat(y).concat(v,"/articles/").concat(t.id)},templates:{header:function(e){var t=e.items;return q.autocomplete.articlesHeader(r,t)},item:function(e){var t=e.item;return q.autocomplete.article(t)},noResults:function(e){var t=e.state;return q.autocomplete.noResults(j,v,t.query)}},onSelect:function(e){var t=e.item;x.trackClick(t,t.__autocomplete_id,t.__autocomplete_queryID)}}})}).then(function(e){return e.unshift(n),e})},render:function(e,t){var r=e.sections;(0,n.render)((0,n.h)(n.Fragment,null,(0,n.h)("div",{className:"aa-PanelLayout"},r),O&&(0,n.h)("div",{className:"aa-PanelFooter"},q.autocomplete.poweredBy())),t)}})}}}]),s}(),A=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return f(x,t)};exports.default=A;
},{"../package.json":"ucH8","algoliasearch/lite":"BM46","@algolia/autocomplete-js":"mF0j","@algolia/autocomplete-theme-classic":"DMuU","preact":"u8ui","lodash":"HJaA","./translations":"G7NL","./answers":"qEIK","./clickAnalytics":"pCMn","@algolia/autocomplete-plugin-recent-searches":"xTJl","@algolia/autocomplete-plugin-recent-searches/dist/esm/usecases/localStorage":"gKCV"}],"j0QR":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=require("preact"),a=require("@algolia/autocomplete-js"),t=c(require("./translations"));function c(e){return e&&e.__esModule?e:{default:e}}var l={autocomplete:{poweredBy:function(a){return(0,e.h)(e.Fragment,null,(0,e.h)("a",{className:"aa-powered-by-link",href:"https://www.algolia.com/?utm_source=zendesk&utm_medium=link&utm_campaign=autocomplete-".concat(a)},(0,e.h)("svg",{height:"18px",class:"aa-PoweredByAlgolia",xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 485 120"},(0,e.h)("g",{fill:"none",fillRule:"evenodd"},(0,e.h)("path",{fill:"#5468FF",d:"M15.8-.001h88.4c8.7 0 15.8 7.065 15.8 15.8v88.405c0 8.7-7.064 15.795-15.8 15.795H15.8c-8.7 0-15.8-7.06-15.8-15.795V15.759C0 7.064 7.06-.001 15.8-.001"}),(0,e.h)("path",{fill:"#FFF",d:"M72.504 26.788v-4.114a5.209 5.209 0 0 0-5.21-5.206H55.15a5.209 5.209 0 0 0-5.21 5.206v4.224c0 .47.434.8.91.69a37.966 37.966 0 0 1 10.57-1.49c3.465 0 6.894.47 10.21 1.38.44.11.874-.215.874-.69M39.22 32.173l-2.075-2.075a5.206 5.206 0 0 0-7.364 0l-2.48 2.476a5.185 5.185 0 0 0 0 7.355l2.04 2.04c.33.325.805.25 1.095-.075a39.876 39.876 0 0 1 3.975-4.66 37.68 37.68 0 0 1 4.7-4c.364-.22.4-.73.11-1.06m22.165 13.065v17.8c0 .51.55.874 1.02.62l15.825-8.19c.36-.18.47-.62.29-.98-3.28-5.755-9.37-9.685-16.405-9.94-.366 0-.73.29-.73.69m0 42.88c-13.195 0-23.916-10.706-23.916-23.88 0-13.176 10.72-23.876 23.916-23.876 13.2 0 23.914 10.7 23.914 23.876 0 13.174-10.68 23.88-23.915 23.88m0-57.8c-18.74 0-33.94 15.18-33.94 33.92 0 18.745 15.2 33.89 33.94 33.89s33.94-15.18 33.94-33.925c0-18.745-15.165-33.885-33.94-33.885"}),(0,e.h)("path",{fill:"#5468FF",d:"M239.214 95.177c-23.365.11-23.365-18.855-23.365-21.875l-.04-71.045 14.255-2.26v70.61c0 1.715 0 12.56 9.15 12.595v11.975zm-57.78-11.61c4.375 0 7.62-.255 9.88-.69V68.392a29.196 29.196 0 0 0-3.43-.695 33.742 33.742 0 0 0-4.955-.365c-1.57 0-3.175.11-4.775.365-1.606.22-3.065.655-4.34 1.275-1.275.62-2.335 1.495-3.1 2.62-.8 1.13-1.166 1.785-1.166 3.495 0 3.345 1.166 5.28 3.28 6.55 2.115 1.275 4.995 1.93 8.606 1.93zm-1.24-51.685c4.7 0 8.675.585 11.885 1.75 3.204 1.165 5.794 2.8 7.69 4.875 1.934 2.11 3.244 4.915 4.044 7.9.84 2.985 1.24 6.26 1.24 9.86v36.62c-2.184.47-5.505 1.015-9.95 1.67-4.445.655-9.44.985-14.984.985-3.68 0-7.07-.365-10.095-1.055-3.066-.69-5.65-1.82-7.84-3.385-2.15-1.565-3.826-3.57-5.065-6.04-1.206-2.48-1.826-5.97-1.826-9.61 0-3.495.69-5.715 2.046-8.12 1.38-2.4 3.24-4.365 5.575-5.895 2.37-1.53 5.065-2.62 8.165-3.275 3.1-.655 6.344-.985 9.695-.985 1.57 0 3.21.11 4.96.29 1.714.185 3.575.515 5.544.985v-2.33c0-1.635-.184-3.2-.584-4.655a10.012 10.012 0 0 0-2.045-3.895c-.986-1.13-2.256-2.005-3.86-2.62-1.605-.62-3.65-1.095-6.09-1.095-3.28 0-6.27.4-9.006.875-2.735.47-4.995 1.02-6.71 1.635l-1.71-11.68c1.786-.62 4.446-1.24 7.876-1.855 3.424-.66 7.11-.95 11.044-.95zm281.51 51.285c4.375 0 7.614-.255 9.875-.695v-14.48c-.8-.22-1.93-.475-3.425-.695a33.813 33.813 0 0 0-4.96-.365c-1.566 0-3.17.11-4.776.365-1.6.22-3.06.655-4.334 1.275-1.28.62-2.336 1.495-3.1 2.62-.805 1.13-1.166 1.785-1.166 3.495 0 3.345 1.166 5.28 3.28 6.55 2.15 1.31 4.995 1.93 8.606 1.93zm-1.206-51.645c4.7 0 8.675.58 11.886 1.745 3.204 1.165 5.794 2.8 7.69 4.875 1.894 2.075 3.244 4.915 4.044 7.9.84 2.985 1.24 6.26 1.24 9.865v36.615c-2.185.47-5.505 1.015-9.95 1.675-4.445.655-9.44.98-14.985.98-3.68 0-7.07-.365-10.094-1.055-3.065-.69-5.65-1.82-7.84-3.385-2.15-1.565-3.825-3.57-5.065-6.04-1.205-2.475-1.825-5.97-1.825-9.61 0-3.495.695-5.715 2.045-8.12 1.38-2.4 3.24-4.365 5.575-5.895 2.37-1.525 5.065-2.62 8.165-3.275 3.1-.655 6.344-.98 9.7-.98 1.565 0 3.204.11 4.954.29 1.75.18 3.575.51 5.54.985v-2.33c0-1.64-.18-3.205-.58-4.66a9.977 9.977 0 0 0-2.044-3.895c-.986-1.13-2.255-2.005-3.86-2.62-1.606-.62-3.65-1.09-6.09-1.09-3.28 0-6.27.4-9.006.87-2.734.475-4.995 1.02-6.71 1.64l-1.71-11.685c1.786-.62 4.446-1.235 7.876-1.855 3.424-.62 7.104-.945 11.044-.945zm-42.8-6.77c4.776 0 8.68-3.86 8.68-8.63 0-4.765-3.864-8.625-8.68-8.625-4.81 0-8.674 3.86-8.674 8.625 0 4.77 3.9 8.63 8.675 8.63zm7.18 70.425h-14.325v-61.44l14.325-2.255v63.695zm-25.114 0c-23.365.11-23.365-18.855-23.365-21.875l-.04-71.045 14.255-2.26v70.61c0 1.715 0 12.56 9.15 12.595v11.975zm-46.336-31.445c0-6.155-1.35-11.285-3.974-14.85-2.625-3.605-6.305-5.385-11.01-5.385-4.7 0-8.386 1.78-11.006 5.385-2.625 3.6-3.904 8.695-3.904 14.85 0 6.225 1.315 10.405 3.94 14.01 2.625 3.64 6.305 5.425 11.01 5.425 4.7 0 8.385-1.82 11.01-5.425 2.624-3.64 3.934-7.785 3.934-14.01zm14.58-.035c0 4.805-.69 8.44-2.114 12.41-1.42 3.965-3.425 7.35-6.01 10.155-2.59 2.8-5.69 4.985-9.336 6.515-3.644 1.525-9.26 2.4-12.065 2.4-2.81-.035-8.385-.835-11.995-2.4-3.61-1.565-6.71-3.715-9.295-6.515-2.59-2.805-4.594-6.19-6.054-10.155-1.456-3.97-2.185-7.605-2.185-12.41s.654-9.43 2.114-13.36c1.46-3.93 3.5-7.28 6.125-10.08 2.625-2.805 5.76-4.955 9.33-6.48 3.61-1.53 7.585-2.255 11.885-2.255 4.305 0 8.275.76 11.92 2.255 3.65 1.525 6.786 3.675 9.336 6.48 2.584 2.8 4.59 6.15 6.05 10.08 1.53 3.93 2.295 8.555 2.295 13.36zm-107.284 0c0 5.965 1.31 12.59 3.935 15.355 2.625 2.77 6.014 4.15 10.175 4.15 2.26 0 4.41-.325 6.414-.945 2.005-.62 3.606-1.35 4.886-2.22v-35.34c-1.02-.22-5.286-1.095-9.41-1.2-5.175-.15-9.11 1.965-11.88 5.345-2.736 3.39-4.12 9.32-4.12 14.855zm39.625 28.095c0 9.72-2.48 16.815-7.476 21.33-4.99 4.51-12.61 6.77-22.89 6.77-3.755 0-11.555-.73-17.79-2.11l2.295-11.285c5.216 1.09 12.106 1.385 15.716 1.385 5.72 0 9.805-1.165 12.245-3.495 2.445-2.33 3.644-5.785 3.644-10.375v-2.33c-1.42.69-3.28 1.385-5.575 2.115-2.294.69-4.954 1.055-7.95 1.055-3.934 0-7.51-.62-10.75-1.86-3.244-1.235-6.054-3.055-8.35-5.46-2.294-2.4-4.12-5.42-5.394-9.025-1.276-3.605-1.936-10.045-1.936-14.775 0-4.44.695-10.01 2.046-13.725 1.385-3.71 3.35-6.915 6.014-9.57 2.626-2.655 5.835-4.695 9.59-6.19 3.755-1.49 8.16-2.435 12.935-2.435 4.635 0 8.9.58 13.055 1.275 4.155.69 7.69 1.415 10.57 2.215v56.49z"})))))},articlesHeader:function(a,t){return(0,e.h)(e.Fragment,null,(0,e.h)("span",{className:"aa-SourceHeaderTitle"},a),(0,e.h)("div",{className:"aa-SourceHeaderLine"}))},bestArticleHeader:function(a,t,c){var l,i,n;return(0,e.h)(e.Fragment,null,(0,e.h)("span",{className:"aa-SourceHeaderTitle"},(null===(l=window)||void 0===l?void 0:null===(i=l.I18N)||void 0===i?void 0:null===(n=i.translations)||void 0===n?void 0:n["txt.help_center.helpers.application.articles.promoted"])||"Best Article"),(0,e.h)("div",{className:"aa-SourceHeaderLine"}))},article:function(t){return(0,e.h)(e.Fragment,null,(0,e.h)("div",{className:"aa-ItemIcon aa-ItemIcon--align-top"},(0,e.h)("svg",{viewBox:"0 0 24 24"},(0,e.h)("path",{fill:"currentColor",d:"M17.586 7h-2.586v-2.586zM20.707 7.293l-6-6c-0.092-0.092-0.202-0.166-0.324-0.217s-0.253-0.076-0.383-0.076h-8c-0.828 0-1.58 0.337-2.121 0.879s-0.879 1.293-0.879 2.121v16c0 0.828 0.337 1.58 0.879 2.121s1.293 0.879 2.121 0.879h12c0.828 0 1.58-0.337 2.121-0.879s0.879-1.293 0.879-2.121v-12c0-0.276-0.112-0.526-0.293-0.707zM13 3v5c0 0.552 0.448 1 1 1h5v11c0 0.276-0.111 0.525-0.293 0.707s-0.431 0.293-0.707 0.293h-12c-0.276 0-0.525-0.111-0.707-0.293s-0.293-0.431-0.293-0.707v-16c0-0.276 0.111-0.525 0.293-0.707s0.431-0.293 0.707-0.293zM16 12h-8c-0.552 0-1 0.448-1 1s0.448 1 1 1h8c0.552 0 1-0.448 1-1s-0.448-1-1-1zM16 16h-8c-0.552 0-1 0.448-1 1s0.448 1 1 1h8c0.552 0 1-0.448 1-1s-0.448-1-1-1zM10 8h-2c-0.552 0-1 0.448-1 1s0.448 1 1 1h2c0.552 0 1-0.448 1-1s-0.448-1-1-1z"}))),(0,e.h)("div",{className:"aa-ItemContent aa-ItemContent--dual"},(0,e.h)("div",{className:"aa-ItemContentTitle"},(0,a.highlightHit)({hit:t,attribute:"title"})),(0,e.h)("div",{className:"aa-ItemContentDescription"},(0,a.snippetHit)({hit:t,attribute:"body_safe"}))))},noResults:function(a,c,l){return(0,e.h)(e.Fragment,null,(0,t.default)(a,c,"noResultsFor",l))}}},i=l;exports.default=i;
},{"preact":"u8ui","@algolia/autocomplete-js":"mF0j","./translations":"G7NL"}],"rO3c":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=o(require("fargs")),t=o(require("./autocomplete")),r=o(require("./templates")),n=void 0;function o(e){return e&&e.__esModule?e:{default:e}}function a(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function i(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?a(Object(r),!0).forEach(function(t){l(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):a(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function l(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function c(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function s(e,t,r){return t&&u(e.prototype,t),r&&u(e,r),e}function p(e){return e>=1&&e<=20||"should be between 1 and 20"}function d(){var e=window.location.pathname.split("/")[2];return e||(console.error("[Algolia] Could not retrieve current locale from URL"),"en-us")}var y={required:!0,type:"Object",children:{analytics:{type:"boolean",value:!0},applicationId:{type:"string",required:!0},apiKey:{type:"string",required:!0},autocomplete:{type:"Object",value:{},children:{enabled:{type:"boolean",value:!0},inputSelector:{type:"string",value:"#query"},hitsPerPage:{type:"number",value:5,validators:[p]}}},baseUrl:{type:"string",value:"/hc/"},color:{type:"string",value:"#158EC2"},clickAnalytics:{type:"boolean",value:!0},debug:{type:"boolean",value:!1},locale:{type:"string"},highlightColor:{type:"string"},indexPrefix:{type:"string",value:"zendesk_"},poweredBy:{type:"boolean",value:!0},subdomain:{type:"string",required:!0},templates:{type:"Object",value:{},children:{autocomplete:{type:"Object",value:{}}}},translations:{type:"Object",value:{}}}},f=function(){function n(o){c(this,n);var a=(0,e.default)().check("algoliasearchZendeskHC").arg("options",y).values([o])[0];a.highlightColor=a.highlightColor||a.color,a.locale=a.locale||d(),a.templates={autocomplete:i(i({},r.default.autocomplete),a.templates.autocomplete)},this.search=(0,t.default)(a),"complete"===document.readyState||"interactive"===document.readyState?this.init(a):document.addEventListener("DOMContentLoaded",this.init.bind(this,a))}return s(n,[{key:"init",value:function(e){this.search.init(e)}}]),n}();f.trackConversion=function(e){if(void 0===e){if(-1===window.location.pathname.indexOf("/articles/"))throw new Error("AlgoliasearchZendeskHCError: Calling trackConversion without an articleID on a non-article page");try{e=window.location.pathname.split("/")[4].split("-")[0]}catch(t){throw new Error("AlgoliasearchZendeskHCError: Failed to extract the article articleID from the URL")}}n.search.trackConversion(e)};var h=f;exports.default=h;
},{"fargs":"mUuq","./autocomplete":"QpCc","./templates":"j0QR"}],"H99C":[function(require,module,exports) {
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=t(require("to-factory")),r=t(require("./AlgoliasearchZendeskHC"));function t(e){return e&&e.__esModule?e:{default:e}}var u=(0,e.default)(r.default);exports.default=u;
},{"to-factory":"EfvZ","./AlgoliasearchZendeskHC":"rO3c"}],"Focm":[function(require,module,exports) {
"use strict";var e=r(require("./src/index"));function r(e){return e&&e.__esModule?e:{default:e}}module.exports=e.default;
},{"./src/index":"H99C"}]},{},["Focm"], "algoliasearchZendeskHC")
//# sourceMappingURL=/algoliasearch.zendesk-hc.min.js.map
|
client/src/containers/Attachments.js
|
wilimitis/DoctorIQ
|
import React from 'react';
import { connect } from 'react-redux';
import AttachmentList from '../components/AttachmentList';
import AttachmentUpload from '../components/AttachmentUpload';
import { uploadDocumentRequest } from '../actions/attachmentUploadActions';
export default props => {
const {
handleFileUpload,
handleClick,
handleDelete,
attachments,
grant
} = props;
return (
<div>
<AttachmentList attachments={attachments} handleClick={handleClick} handleDelete={handleDelete} grant={grant}/>
<AttachmentUpload handleFileUpload={handleFileUpload}/>
</div>
);
};
|
test/index.js
|
weflex/react-portal-tooltip
|
import React from 'react'
import assert from 'assert'
import TestUtils from 'react-addons-test-utils'
import Tooltip from '../src'
const renderer = (Component) => {
const shallowRenderer = TestUtils.createRenderer()
shallowRenderer.render(Component)
return shallowRenderer.getRenderOutput()
}
describe('React Portal Tooltip', () => {
it('should export a react component', () => {
assert.equal(typeof Tooltip, 'function')
})
it('should render null', () => {
let tooltip = renderer(<Tooltip parent="#hey" position="top" arrow="center" active={false}><span>Hey this is a tooltip</span></Tooltip>)
assert.equal(tooltip, null)
})
})
|
src/plantdetail/PlantDetail.js
|
BushrootPDX/app
|
import React from 'react';
export default function PlantDetail( props ) {
const {
_id,
name,
scientific_name,
image,
spread,
height,
description,
sun_requirements,
sowing_method
} = props.selectedPlant;
return (
<div id={_id}>
<img src={image} alt={name}/>
<h3>{name}</h3>
<h4>{scientific_name}</h4>
<h5>{description}</h5>
<h5>Size:</h5><span>{spread}in. X {height}in. </span>
<h5>Sunlight Preference: </h5><span>{sun_requirements}</span>
<h5>Sowing Method: </h5><span>{sowing_method}</span>
</div>
);
}
|
framework/react/react-tutorials/src/demo/welcome/Welcomes.js
|
yhtml5/YHTML5-Tutorial
|
import React from 'react';
function Welcome(props) {
return <h4>Hello, {props.name}</h4>
}
function Welcomes() {
return (
<div>
<Welcome name="Sara"/>
<Welcome name="Cahal"/>
<Welcome name="Edite"/>
</div>
);
}
export default Welcomes
|
src/components/SimbologicItem/SimbologicItem.js
|
jmoguelruiz/react-common-components
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class SimbologicItem extends Component {
getStyles(){
return {
container : {
display : "inline-block"
},
elementImage : {
width : "20px",
height : "20px"
},
elementRectangle : {
content : "",
width : "11px",
height : "7px",
backgroundColor : "#000",
display : "inline-block"
},
label : {
fontSize : "9px",
margin: "0px 5px",
fontWeight : "100",
fontStyle : "italic",
color : "#b4b4b4"
}
};
}
render(){
const styles = this.getStyles();
const {
containerStyle,
label,
elementImageStyle,
imgUrl,
elementRectangleStyle,
colorRectangle,
labelStyle
} = this.props;
return(
<div className="simbologic-item" style = {containerStyle ? containerStyle : styles.container} >
{
imgUrl
? <img className="image-figure"
style = {elementImageStyle ? elementImageStyle : styles.elementImage}
src = {imgUrl} />
: <div className= "rectangle-figure"
style = {Object.assign(elementRectangleStyle ? elementRectangleStyle : styles.elementRectangle, { backgroundColor : colorRectangle})} />
}
<span style ={labelStyle ? labelStyle : styles.label}>
{ label }
</span>
</div>
);
}
}
SimbologicItem.propTypes = {
/**
* Styles of container.
*/
containerStyle : PropTypes.object,
/**
* Text to put in label.
*/
label : PropTypes.string,
/**
* Styles of elment image.
*/
elementImageStyle : PropTypes.object,
/**
* Path of image figure.
*/
imgUrl : PropTypes.string,
/**
* Style object of rectangle element.
*/
elementRectangleStyle : PropTypes.object,
/**
* Color of rectangle.
*/
colorRectangle : PropTypes.string,
/**
* Label style object.
*/
labelStyle : PropTypes.object
};
export default SimbologicItem;
|
ajax/libs/6to5/2.13.1/browser.js
|
chrisyip/cdnjs
|
!function(n){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=n();else if("function"==typeof define&&define.amd)define([],n);else{var e;"undefined"!=typeof window?e=window:"undefined"!=typeof global?e=global:"undefined"!=typeof self&&(e=self),e.to5=n()}}(function(){var define,module,exports;return function e(e,n,t){function r(l,u){if(!n[l]){if(!e[l]){var s=typeof require=="function"&&require;if(!u&&s)return s(l,!0);if(a)return a(l,!0);var o=new Error("Cannot find module '"+l+"'");throw o.code="MODULE_NOT_FOUND",o}var i=n[l]={exports:{}};e[l][0].call(i.exports,function(n){var t=e[l][1][n];return r(t?t:n)},i,i.exports,e,e,n,t)}return n[l].exports}var a=typeof require=="function"&&require;for(var l=0;l<t.length;l++)r(t[l]);return r}({1:[function(t,n,e){(function(r,t){if(typeof e=="object"&&typeof n=="object")return t(e);if(typeof define=="function"&&define.amd)return define(["exports"],t);t(r.acorn||(r.acorn={}))})(this,function(B){"use strict";B.version="0.11.1";var r,a,V,yt;B.parse=function(e,t){a=String(e);V=a.length;xt(t);ht();var l=r.locations?[n,mn()]:n;nr();return ua(r.program||S(l))};var cr=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,n,t){a=String(e);V=a.length;xt(t);ht(n);nr();return y()};var lr=function(e){return Object.prototype.toString.call(e)==="[object Array]"};function xt(n){r={};for(var e in cr)r[e]=n&&pt(n,e)?n[e]:cr[e];yt=r.sourceFile||null;if(lr(r.onToken)){var t=r.onToken;r.onToken=function(e){t.push(e)}}if(lr(r.onComment)){var l=r.onComment;r.onComment=function(a,i,n,t,s,o){var e={type:a?"Block":"Line",value:i,start:n,end:t};if(r.locations){e.loc=new rt;e.loc.start=s;e.loc.end=o}if(r.ranges)e.range=[n,t];l.push(e)}}if(r.strictMode){M=true}if(r.ecmaVersion>=6){at=El}else{at=Zt}}var Dl=B.getLineInfo=function(l,t){for(var r=1,n=0;;){En.lastIndex=n;var e=En.exec(l);if(e&&e.index<t){++r;n=e.index+e[0].length}else break}return{line:r,column:t-n}};function _t(){this.type=e;this.value=f;this.start=m;this.end=D;if(r.locations){this.loc=new rt;this.loc.end=Nn;this.startLoc=ln;this.endLoc=Nn}if(r.ranges)this.range=[m,D]}B.Token=_t;B.tokenize=function(t,l){a=String(t);V=a.length;xt(l);ht();sn();function e(e){T=D;un(e);return new _t}e.jumpTo=function(t,l){n=t;if(r.locations){U=1;P=En.lastIndex=0;var e;while((e=En.exec(a))&&e.index<t){++U;P=e.index+e[0].length}}$=l;sn()};e.noRegexp=function(){$=false};e.options=r;return e};var n;var m,D;var ln,Nn;var e,f;var $;var U,P;var jn,T,rn;var Gn,Rn,Xn,k,M,A,I,on;var Vn;var en;function nr(){jn=T=n;if(r.locations)rn=new Qn;Gn=Rn=Xn=M=false;k=[];sn();un()}function u(r,l){var t=Dl(a,r);l+=" ("+t.line+":"+t.column+")";var e=new SyntaxError(l);e.pos=r;e.loc=t;e.raisedAt=n;throw e}var mr=[];var yn={type:"num"},kt={type:"regexp"},J={type:"string"};var p={type:"name"},xn={type:"eof"};var bt={type:"xjsName"},Mn={type:"xjsText"};var hr={keyword:"break"},gt={keyword:"case",beforeExpr:true},zr={keyword:"catch"};var Yt={keyword:"continue"},Wr={keyword:"debugger"},Yn={keyword:"default"};var Gr={keyword:"do",isLoop:true},Vr={keyword:"else",beforeExpr:true};var Ur={keyword:"finally"},Fn={keyword:"for",isLoop:true},dn={keyword:"function"};var Tt={keyword:"if"},Nr={keyword:"return",beforeExpr:true},ct={keyword:"switch"};var jr={keyword:"throw",beforeExpr:true},Pr={keyword:"try"},kn={keyword:"var"};var An={keyword:"let"},zn={keyword:"const"};var ft={keyword:"while",isLoop:true},Tr={keyword:"with"},Ar={keyword:"new",beforeExpr:true};var Ir={keyword:"this"};var wn={keyword:"class"},Ct={keyword:"extends",beforeExpr:true};var _r={keyword:"export"},Lt={keyword:"import"};var wr={keyword:"yield",beforeExpr:true};var Er={keyword:"null",atomValue:null},br={keyword:"true",atomValue:true};var xr={keyword:"false",atomValue:false};var On={keyword:"in",binop:7,beforeExpr:true};var Jn={"break":hr,"case":gt,"catch":zr,"continue":Yt,"debugger":Wr,"default":Yn,"do":Gr,"else":Vr,"finally":Ur,"for":Fn,"function":dn,"if":Tt,"return":Nr,"switch":ct,"throw":jr,"try":Pr,"var":kn,let:An,"const":zn,"while":ft,"with":Tr,"null":Er,"true":br,"false":xr,"new":Ar,"in":On,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":Ir,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":wn,"extends":Ct,"export":_r,"import":Lt,"yield":wr};var X={type:"[",beforeExpr:true},N={type:"]"},R={type:"{",beforeExpr:true};var b={type:"}"},v={type:"(",beforeExpr:true},h={type:")"};var x={type:",",beforeExpr:true},L={type:";",beforeExpr:true};var _={type:":",beforeExpr:true},qn={type:"."},Z={type:"?",beforeExpr:true};var Q={type:"=>",beforeExpr:true},dr={type:"`"},pr={type:"${",beforeExpr:true};var ot={type:"</"};var Q={type:"=>",beforeExpr:true},et={type:"template"},Zn={type:"templateContinued"};var K={type:"...",prefix:true,beforeExpr:true};var dt={type:"::",beforeExpr:true};var mt={type:"@"};var $n={type:"#"};var Bn={binop:10,beforeExpr:true},tn={isAssign:true,beforeExpr:true};var z={isAssign:true,beforeExpr:true};var wl={postfix:true,prefix:true,isUpdate:true},fr={prefix:true,beforeExpr:true};var sr={binop:1,beforeExpr:true};var ir={binop:2,beforeExpr:true};var ar={binop:3,beforeExpr:true};var Jl={binop:4,beforeExpr:true};var rr={binop:5,beforeExpr:true};var ia={binop:6,beforeExpr:true};var ul={binop:7,beforeExpr:true};var fl={binop:8,beforeExpr:true};var hl={binop:9,prefix:true,beforeExpr:true};var yl={binop:10,beforeExpr:true};var Y={binop:10,beforeExpr:true};var tr={binop:11,beforeExpr:true,rightAssociative:true};var w={binop:7,beforeExpr:true},H={binop:7,beforeExpr:true};B.tokTypes={bracketL:X,bracketR:N,braceL:R,braceR:b,parenL:v,parenR:h,comma:x,semi:L,colon:_,dot:qn,ellipsis:K,question:Z,slash:Bn,eq:tn,name:p,eof:xn,num:yn,regexp:kt,string:J,arrow:Q,bquote:dr,dollarBraceL:pr,star:Y,assign:z,xjsName:bt,xjsText:Mn,paamayimNekudotayim:dt,exponent:tr,at:mt,hash:$n,template:et,templateContinued:Zn};for(var er in Jn)B.tokTypes["_"+er]=Jn[er];var al=function Da(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 il=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 Mt=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 Ot=function Ba(e){switch(e){case"eval":case"arguments":return true}return false};var ml="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 Zt=function Ua(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 Oa=ml+" let const class extends export import yield";var El=function Va(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 at=Zt;var Ll=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var Qt="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var ql="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var Kt=new RegExp("["+Qt+"]");var Gl=new RegExp("["+Qt+ql+"]");var Wl=/^\d+$/;var zl=/^[\da-fA-F]+$/;var pn=/[\n\r\u2028\u2029]/;function Ma(e){return e===10||e===13||e===8232||e==8233}var En=/\r\n|[\n\r\u2028\u2029]/g;var Hn=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&&Kt.test(String.fromCharCode(e))};var $t=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&&Gl.test(String.fromCharCode(e))};function Qn(e,n){this.line=e;this.column=n}Qn.prototype.offset=function(e){return new Qn(this.line,this.column+e)};function mn(){return new Qn(U,n-P)}function ht(e){if(e){n=e;P=Math.max(0,a.lastIndexOf("\n",e));U=a.slice(0,P).split(pn).length}else{U=1;n=P=0}$=true;Vn=0;on=A=I=false;en=[];if(n===0&&r.allowHashBang&&a.slice(0,2)==="#!"){Wn(2)}}function g(t,l,a){D=n;if(r.locations)Nn=mn();e=t;if(a!==false)sn();f=l;$=t.beforeExpr;if(r.onToken){r.onToken(new _t)}}function vl(){var i=r.onComment&&r.locations&&mn();var t=n,l=a.indexOf("*/",n+=2);if(l===-1)u(n-2,"Unterminated comment");n=l+2;if(r.locations){En.lastIndex=t;var e;while((e=En.exec(a))&&e.index<n){++U;P=e.index+e[0].length}}if(r.onComment)r.onComment(true,a.slice(t+2,l),t,n,i,r.locations&&mn())}function Wn(t){var l=n;var i=r.onComment&&r.locations&&mn();var e=a.charCodeAt(n+=t);while(n<V&&e!==10&&e!==13&&e!==8232&&e!==8233){++n;e=a.charCodeAt(n)}if(r.onComment)r.onComment(false,a.slice(l+t,n),l,n,i,r.locations&&mn())}function sn(){while(n<V){var e=a.charCodeAt(n);if(e===32){++n}else if(e===13){++n;var t=a.charCodeAt(n);if(t===10){++n}if(r.locations){++U;P=n}}else if(e===10||e===8232||e===8233){++n;if(r.locations){++U;P=n}}else if(e>8&&e<14){++n}else if(e===47){var t=a.charCodeAt(n+1);if(t===42){vl()}else if(t===47){Wn(2)}else break}else if(e===160){++n}else if(e>=5760&&Ll.test(String.fromCharCode(e))){++n}else{break}}}function _l(){var e=a.charCodeAt(n+1);if(e>=48&&e<=57)return Gt(true);var t=a.charCodeAt(n+2);if(r.playground&&e===63){n+=2;return g(_dotQuestion)}else if(r.ecmaVersion>=6&&e===46&&t===46){n+=3;return g(K)}else{++n;return g(qn)}}function Sl(){var e=a.charCodeAt(n+1);if($){++n;return Wt()}if(e===61)return E(z,2);return E(Bn,1)}function kl(){var e=a.charCodeAt(n+1);if(e===61)return E(z,2);return E(yl,1)}function Il(){var e=Y;var t=1;var l=a.charCodeAt(n+1);if(r.ecmaVersion>=7&&l===42){t++;l=a.charCodeAt(n+2);e=tr}if(l===61){t++;e=z}return E(e,t)}function Rl(e){var t=a.charCodeAt(n+1);if(t===e){if(r.playground&&a.charCodeAt(n+2)===61)return E(z,3);return E(e===124?sr:ir,2)}if(t===61)return E(z,2);return E(e===124?ar:rr,1)}function Al(){var e=a.charCodeAt(n+1);if(e===61)return E(z,2);return E(Jl,1)}function Tl(t){var e=a.charCodeAt(n+1);if(e===t){if(e==45&&a.charCodeAt(n+2)==62&&pn.test(a.slice(T,n))){Wn(3);sn();return un()}return E(wl,2)}if(e===61)return E(z,2);return E(hl,1)}function La(t){var r=a.charCodeAt(n+1);var e=1;if(!on&&r===t){e=t===62&&a.charCodeAt(n+2)===62?3:2;if(a.charCodeAt(n+e)===61)return E(z,e+1);return E(fl,e)}if(r==33&&t==60&&a.charCodeAt(n+2)==45&&a.charCodeAt(n+3)==45){Wn(4);sn();return un()}if(r===61){e=a.charCodeAt(n+2)===61?3:2;return E(ul,e)}if(t===60&&r===47){e=2;return E(ot,e)}return t===60?E(w,e):E(H,e,!I)}function Pl(e){var t=a.charCodeAt(n+1);if(t===61)return E(ia,a.charCodeAt(n+2)===61?3:2);if(e===61&&t===62&&r.ecmaVersion>=6){n+=2;return g(Q)}return E(e===61?tn:fr,1)}function ja(t){if(e===J){if(t===96){++n;return g(dr)}else if(t===36&&a.charCodeAt(n+1)===123){n+=2;return g(pr)}}return readTmplString()}function Ol(t){switch(t){case 46:return _l();case 40:++n;return g(v);case 41:++n;return g(h);case 59:++n;return g(L);case 44:++n;return g(x);case 91:++n;return g(X);case 93:++n;return g(N);case 123:++n;if(en.length)++en[en.length-1];return g(R);case 125:++n;if(en.length&&--en[en.length-1]===0)return Jt(Zn);else return g(b);case 63:++n;return g(Z);case 64:if(r.playground){++n;return g(mt)}case 35:if(r.playground){++n;return g($n)}case 58:++n;if(r.ecmaVersion>=7){var e=a.charCodeAt(n);if(e===58){++n;return g(dt)}}return g(_);case 96:if(r.ecmaVersion>=6){++n;return Jt(et)}case 48:var e=a.charCodeAt(n+1);if(e===120||e===88)return It(16);if(r.ecmaVersion>=6){if(e===111||e===79)return It(8);if(e===98||e===66)return It(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return Gt(false);case 34:case 39:return I?cl():ha(t);case 47:return Sl();case 37:return kl();case 42:return Il();case 124:case 38:return Rl(t);case 94:return Al();case 43:case 45:return Tl(t);case 60:case 62:return La(t);case 61:case 33:return Pl(t);case 126:return E(fr,1)}return false}function un(i){if(!i)m=n;else n=m+1;if(r.locations)ln=mn();if(i)return Wt();if(n>=V)return g(xn);var t=a.charCodeAt(n);if(A&&e!==R&&t!==60&&t!==123&&t!==125){return Xt(["<","{"])}if(Hn(t)||t===92)return Vt();var s=Ol(t);if(s===false){var l=String.fromCharCode(t);if(l==="\\"||Kt.test(l))return Vt();u(n,"Unexpected character '"+l+"'")}return s}function E(t,e,r){var l=a.slice(n,n+e);n+=e;g(t,l,r)}var zt=false;try{new RegExp("","u");zt=true}catch(Pa){}function Wt(){var s="",o,i,t=n;for(;;){if(n>=V)u(t,"Unterminated regular expression");var l=an();if(pn.test(l))u(t,"Unterminated regular expression");if(!o){if(l==="[")i=true;else if(l==="]"&&i)i=false;else if(l==="/"&&!i)break;o=l==="\\"}else o=false;++n}var s=a.slice(t,n);++n;var e=yr();var c=s;if(e){var p=/^[gmsiy]*$/;if(r.ecmaVersion>=6)p=/^[gmsiyu]*$/;if(!p.test(e))u(t,"Invalid regular expression flag");if(e.indexOf("u")>=0&&!zt){c=c.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(c)}catch(f){if(f instanceof SyntaxError)u(t,"Error parsing regular expression: "+f.message);u(f)}try{var d=new RegExp(s,e)}catch(m){d=null}return g(kt,{pattern:s,flags:e,value:d})}function Cn(i,r){var s=n,l=0;for(var o=0,u=r==null?Infinity:r;o<u;++o){var e=a.charCodeAt(n),t;if(e>=97)t=e-97+10;else if(e>=65)t=e-65+10;else if(e>=48&&e<=57)t=e-48;else t=Infinity;if(t>=i)break;++n;l=l*i+t}if(n===s||r!=null&&n-s!==r)return null;return l}function It(e){n+=2;var t=Cn(e);if(t==null)u(m+2,"Expected number in radix "+e);if(Hn(a.charCodeAt(n)))u(n,"Identifier directly after number");return g(yn,t)}function Gt(s){var r=n,i=false,o=a.charCodeAt(n)===48;if(!s&&Cn(10)===null)u(r,"Invalid number");if(a.charCodeAt(n)===46){++n;Cn(10);i=true}var e=a.charCodeAt(n);if(e===69||e===101){e=a.charCodeAt(++n);if(e===43||e===45)++n;if(Cn(10)===null)u(r,"Invalid number");i=true}if(Hn(a.charCodeAt(n)))u(n,"Identifier directly after number");var t=a.slice(r,n),l;if(i)l=parseFloat(t);else if(!o||t.length===1)l=parseInt(t,10);else if(/[89]/.test(t)||M)u(r,"Invalid number");else l=parseInt(t,8);return g(yn,l)}function da(){var t=a.charCodeAt(n),e;if(t===123){if(r.ecmaVersion<6)c();++n;e=lt(a.indexOf("}",n)-n);++n;if(e>1114111)c()}else{e=lt(4)}if(e<=65535){return String.fromCharCode(e)}var l=(e-65536>>10)+55296;var i=(e-65536&1023)+56320;return String.fromCharCode(l,i)}function ha(r){++n;var t="";for(;;){if(n>=V)u(m,"Unterminated string constant");var e=a.charCodeAt(n);if(e===r){++n;return g(J,t)}if(e===92){t+=qt()}else{++n;if(pn.test(String.fromCharCode(e))){u(m,"Unterminated string constant")}t+=String.fromCharCode(e)}}}function Jt(l){if(l==Zn)en.pop();var t="",i=n;for(;;){if(n>=V)u(m,"Unterminated template");var e=a.charAt(n);if(e==="`"||e==="$"&&a.charCodeAt(n+1)===123){var s=a.slice(i,n);++n;if(e=="$"){++n;en.push(1)}return g(l,{cooked:t,raw:s})}if(e==="\\"){t+=qt()}else{++n;if(pn.test(e)){if(e==="\r"&&a.charCodeAt(n)===10){++n;e="\n"}if(r.locations){++U;P=n}}t+=e}}}function qt(){var t=a.charCodeAt(++n);var e=/^[0-7]+/.exec(a.slice(n,n+3));if(e)e=e[0];while(e&&parseInt(e,8)>255)e=e.slice(0,-1);if(e==="0")e=null;++n;if(e){if(M)u(n-2,"Octal literal in strict mode");n+=e.length-1;return String.fromCharCode(parseInt(e,8))}else{switch(t){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(lt(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(n)===10)++n;case 10:if(r.locations){P=n;++U}return"";default:return String.fromCharCode(t)}}}var sl={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 ol(){var e="",l=0,t;var r=an();if(r!=="&")u(n,"Entity must start with an ampersand");var a=++n;while(n<V&&l++<10){r=an();n++;if(r===";"){if(e[0]==="#"){if(e[1]==="x"){e=e.substr(2);if(zl.test(e)){t=String.fromCharCode(parseInt(e,16))}}else{e=e.substr(1);if(Wl.test(e)){t=String.fromCharCode(parseInt(e,10))}}}else{t=sl[e]}break}e+=r}if(!t){n=a;return"&"}return t}function Xt(l){var t="";while(n<V){var e=an();if(l.indexOf(e)!==-1){break}if(e==="&"){t+=ol()}else{++n;if(e==="\r"&&an()==="\n"){t+=e;++n;e="\n"}if(e==="\n"&&r.locations){P=n;++U}t+=e}}return g(Mn,t)}function cl(){var t=a.charCodeAt(n);if(t!==34&&t!==39){u("String literal must starts with a quote")}++n;Xt([String.fromCharCode(t)]);if(t!==a.charCodeAt(n)){c()}++n;return g(e,f)}function lt(n){var e=Cn(16,n);if(e===null)u(m,"Bad character escape sequence");return e}var bn;function yr(){bn=false;var e,l=true,i=n;for(;;){var t=a.charCodeAt(n);if($t(t)||I&&t===45){if(bn)e+=an();++n}else if(t===92&&!I){if(!bn)e=a.slice(i,n);bn=true;if(a.charCodeAt(++n)!=117)u(n,"Expecting Unicode escape sequence \\uXXXX");++n;var r=lt(4);var s=String.fromCharCode(r);if(!s)u(n-1,"Invalid Unicode escape");if(!(l?Hn(r):$t(r)))u(n-4,"Invalid Unicode escape");e+=s}else{break}l=false}return bn?e:a.slice(i,n)}function Vt(){var e=yr();var n=I?bt:p;if(!bn&&at(e))n=Jn[e];return g(n,e)}function s(){jn=m;T=D;rn=Nn;un()}function Dt(e){M=e;n=m;if(r.locations){while(n<P){P=a.lastIndexOf("\n",P-2)+1;--U}}sn();un()}function Nt(){this.type=null;this.start=m;this.end=null}B.Node=Nt;function rt(){this.start=ln;this.end=null;if(yt!==null)this.source=yt}function o(){var e=new Nt;if(r.locations)e.loc=new rt;if(r.directSourceFile)e.sourceFile=r.directSourceFile;if(r.ranges)e.range=[m,0];return e}function C(){return r.locations?[m,ln]:m}function S(t){var e=new Nt,n=t;if(r.locations){e.loc=new rt;e.loc.start=n[1];n=t[0]}e.start=n;if(r.directSourceFile)e.sourceFile=r.directSourceFile;if(r.ranges)e.range=[n,0];return e}function t(e,n){e.type=n;e.end=T;if(r.locations)e.loc.end=rn;if(r.ranges)e.range[1]=T;return e}function Cl(e,t,n){if(r.locations){e.loc.end=n[1];n=n[0]}e.type=t;e.end=n;if(r.ranges)e.range[1]=n;return e}function At(e){return r.ecmaVersion>=5&&e.type==="ExpressionStatement"&&e.expression.type==="Literal"&&e.expression.value==="use strict"}function i(n){if(e===n){s();return true}else{return false}}function cn(){return!r.strictSemicolons&&(e===xn||e===b||pn.test(a.slice(T,m)))}function j(){if(!i(L)&&!cn())c()}function l(e){i(e)||c()}function an(){return a.charAt(n)}function c(e){u(e!=null?e:m,"Unexpected token")}function pt(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function _n(e,i,t){if(r.ecmaVersion>=6&&e){switch(e.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":e.type="ObjectPattern";for(var n=0;n<e.properties.length;n++){var l=e.properties[n];if(l.type==="Property"&&l.kind!=="init")c(l.key.start);_n(l.value,false,t)}break;case"ArrayExpression":e.type="ArrayPattern";for(var n=0,a=e.elements.length-1;n<=a;n++){_n(e.elements[n],n===a,t)}break;case"SpreadElement":if(i){_n(e.argument,false,t);jt(e.argument)}else{c(e.start)}break;case"AssignmentExpression":if(e.operator==="="){e.type="AssignmentPattern"}else{c(e.left.end)}break;default:if(t)c(e.start)}}return e}function vn(){if(r.ecmaVersion<6)return d();switch(e){case p:return d();case X:var a=o();s();var u=a.elements=[],f=true;while(!i(N)){f?f=false:l(x);if(e===K){var n=o();s();n.argument=vn();jt(n.argument);u.push(t(n,"SpreadElement"));l(N);break}u.push(e===x?null:Ft())}return t(a,"ArrayPattern");case R:return vr(true);default:c()}}function Ft(r,e){e=e||vn();if(!i(tn))return e;var n=r?S(r):o();n.operator="=";n.left=e;n.right=fn();return t(n,"AssignmentPattern")}function jt(e){if(e.type!=="Identifier"&&e.type!=="ArrayPattern")c(e.start)}function Tn(e,t){switch(e.type){case"Identifier":if(Mt(e.name)||Ot(e.name))u(e.start,"Defining '"+e.name+"' in strict mode");if(pt(t,e.name))u(e.start,"Argument name clash in strict mode");t[e.name]=true;break;case"ObjectPattern":for(var n=0;n<e.properties.length;n++)Tn(e.properties[n].value,t);break;case"ArrayPattern":for(var n=0;n<e.elements.length;n++){var r=e.elements[n];if(r)Tn(r,t)}break}}function ra(i,l){if(r.ecmaVersion>=6)return;var t=i.key,e;switch(t.type){case"Identifier":e=t.name;break;case"Literal":e=String(t.value);break;default:return}var a=i.kind||"init",n;if(pt(l,e)){n=l[e];var s=a!=="init";if((M||s)&&n[a]||!(s^n.init))u(t.start,"Redefinition of property")}else{n=l[e]={init:false,get:false,set:false}}n[a]=true}function W(e,t){switch(e.type){case"Identifier":if(M&&(Ot(e.name)||Mt(e.name)))u(e.start,(t?"Binding ":"Assigning to ")+e.name+" in strict mode");break;case"MemberExpression":if(t)u(e.start,"Binding to member expression");break;case"ObjectPattern":for(var n=0;n<e.properties.length;n++){var r=e.properties[n];if(r.type==="Property")r=r.value;W(r,t)}break;case"ArrayPattern":for(var n=0;n<e.elements.length;n++){var l=e.elements[n];if(l)W(l,t)}break;case"SpreadProperty":case"AssignmentPattern":case"SpreadElement":case"VirtualPropertyExpression":break;default:u(e.start,"Assigning to rvalue")}}function ua(n){var r=true;if(!n.body)n.body=[];while(e!==xn){var l=F(true);n.body.push(l);if(r&&At(l))Dt(true);r=false}jn=m;T=D;rn=Nn;return t(n,"Program")}var Rt={kind:"loop"},ma={kind:"switch"};function F(a){if(e===Bn||e===z&&f=="/=")un(true);var l=e,n=o(),c=C();switch(l){case hr:case Yt:return ya(n,l.keyword);case Wr:return ba(n);case Gr:return ka(n);case Fn:return Ia(n);case dn:return Ca(n);case wn:return Cr(n,true);case Tt:return Ta(n);case Nr:return Yr(n);case ct:return $r(n);case jr:return Kr(n);case Pr:return Qr(n);case kn:case An:case zn:return Zr(n,l.keyword);case ft:return el(n);case Tr:return nl(n);case R:return In();case L:return tl(n);case _r:case Lt:if(!a&&!r.allowImportExportEverywhere)u(m,"'import' and 'export' may only appear at the top level");return l===Lt?Bl(n):Nl(n);default:var s=f,t=y(false,false,true);if(t.type==="FunctionDeclaration")return t;if(l===p&&t.type==="Identifier"){if(i(_)){return rl(n,s,t)}if(r.ecmaVersion>=7&&t.name==="private"&&e===p){return Rr(n)}else if(t.name==="declare"){if(e===wn||e===p||e===dn||e===kn){return Fr(n)}}else if(e===p){if(t.name==="interface"){return fa(n)}else if(t.name==="type"){return pa(n)}}}return ll(n,t)}}function ya(n,o){var l=o=="break";s();if(i(L)||cn())n.label=null;else if(e!==p)c();else{n.label=d();j()}for(var r=0;r<k.length;++r){var a=k[r];if(n.label==null||a.name===n.label.name){if(a.kind!=null&&(l||a.kind==="loop"))break;if(n.label&&l)break}}if(r===k.length)u(n.start,"Unsyntactic "+o);return t(n,l?"BreakStatement":"ContinueStatement")}function ba(e){s();j();return t(e,"DebuggerStatement")}function ka(e){s();k.push(Rt);e.body=F();k.pop();l(ft);e.test=gn();if(r.ecmaVersion>=6)i(L);else j();return t(e,"DoWhileStatement")}function Ia(a){s();k.push(Rt);l(v);if(e===L)return wt(a,null);if(e===kn||e===An){var n=o(),i=e.keyword,u=e===An;s();ur(n,true,i);t(n,"VariableDeclaration");if((e===On||r.ecmaVersion>=6&&e===p&&f==="of")&&n.declarations.length===1&&!(u&&n.declarations[0].init))return or(a,n);return wt(a,n)}var n=y(false,true);if(e===On||r.ecmaVersion>=6&&e===p&&f==="of"){W(n);return or(a,n)}return wt(a,n)}function Ca(e){s();return Bt(e,true,false)}function Ta(e){s();e.test=gn();e.consequent=F();e.alternate=i(Vr)?F():null;return t(e,"IfStatement")}function Yr(e){if(!Gn&&!r.allowReturnOutsideFunction)u(m,"'return' outside of function");s();if(i(L)||cn())e.argument=null;else{e.argument=y();j()}return t(e,"ReturnStatement")}function $r(r){s();r.discriminant=gn();r.cases=[];l(R);k.push(ma);for(var n,a;e!=b;){if(e===gt||e===Yn){var i=e===gt;if(n)t(n,"SwitchCase");r.cases.push(n=o());n.consequent=[];s();if(i)n.test=y();else{if(a)u(jn,"Multiple default clauses");a=true;n.test=null}l(_)}else{if(!n)c();n.consequent.push(F())}}if(n)t(n,"SwitchCase");s();k.pop();return t(r,"SwitchStatement")}function Kr(e){s();if(pn.test(a.slice(T,m)))u(T,"Illegal newline after throw");e.argument=y();j();return t(e,"ThrowStatement")}function Qr(n){s();n.block=In();n.handler=null;if(e===zr){var r=o();s();l(v);r.param=d();if(M&&Ot(r.param.name))u(r.param.start,"Binding "+r.param.name+" in strict mode");l(h);r.guard=null;r.body=In();n.handler=t(r,"CatchClause")}n.guardedHandlers=mr;n.finalizer=i(Ur)?In():null;if(!n.handler&&!n.finalizer)u(n.start,"Missing catch or finally clause");return t(n,"TryStatement")}function Zr(e,n){s();ur(e,false,n);j();return t(e,"VariableDeclaration")}function el(e){s();e.test=gn();k.push(Rt);e.body=F();k.pop();return t(e,"WhileStatement")}function nl(e){if(M)u(m,"'with' in strict mode");s();e.object=gn();e.body=F();return t(e,"WithStatement")}function tl(e){s();return t(e,"EmptyStatement")}function rl(n,r,a){for(var l=0;l<k.length;++l)if(k[l].name===r)u(a.start,"Label '"+r+"' is already declared");var i=e.isLoop?"loop":e===ct?"switch":null;k.push({name:r,kind:i});n.body=F();k.pop();n.label=a;return t(n,"LabeledStatement")}function ll(e,n){e.expression=n;j();return t(e,"ExpressionStatement")}function gn(){l(v);var e=y();l(h);return e}function In(s){var e=o(),n=true,r;e.body=[];l(R);while(!i(b)){var a=F();e.body.push(a);if(n&&s&&At(a)){r=M;Dt(M=true)}n=false}if(r===false)Dt(false);return t(e,"BlockStatement")}function wt(n,r){n.init=r;l(L);n.test=e===L?null:y();l(L);n.update=e===h?null:y();l(h);n.body=F();k.pop();return t(n,"ForStatement")}function or(n,r){var a=e===On?"ForInStatement":"ForOfStatement";s();n.left=r;n.right=y();l(h);n.body=F();k.pop();return t(n,a)}function ur(r,a,l){r.declarations=[];r.kind=l;for(;;){var n=o();n.id=vn();W(n.id,true);if(e===_){n.id.typeAnnotation=Pn();t(n.id,n.id.type)}n.init=i(tn)?y(true,a):l===zn.keyword?c():null;r.declarations.push(t(n,"VariableDeclarator"));if(!i(x))break}return r}function y(a,r,s){var o=C();var l=fn(r,false,s);if(!a&&e===x){var n=S(o);n.expressions=[l];while(i(x))n.expressions.push(fn(r));return t(n,"SequenceExpression")}return l}function fn(l,a,i){var o=C();var n=pl(l,a,i);if(e.isAssign){var r=S(o);r.operator=f;r.left=e===tn?_n(n):n;W(n);s();r.right=fn(l);return t(r,"AssignmentExpression")}return n}function pl(n,o,c){var f=C();var a=dl(n,o,c);if(i(Z)){var e=S(f);if(r.playground&&i(tn)){var s=e.left=_n(a);if(s.type!=="MemberExpression")u(s.start,"You can only use member expressions in memoization assignment");
e.right=fn(n);e.operator="?=";return t(e,"AssignmentExpression")}e.test=a;e.consequent=y(true);l(_);e.alternate=y(true,n);return t(e,"ConditionalExpression")}return a}function dl(e,n,t){var r=C();return st(Ln(t),r,-1,e,n)}function st(i,o,u,l,c){var r=e.binop;if(r!=null&&(!l||e!==On)&&(!c||e!==w)){if(r>u){var n=S(o);n.left=i;n.operator=f;var a=e;s();var p=C();n.right=st(Ln(),p,a.rightAssociative?r-1:r,l);t(n,a===sr||a===ir?"LogicalExpression":"BinaryExpression");return st(n,o,u,l)}}return i}function Ln(i){if(e.prefix){var n=o(),a=e.isUpdate,l;if(e===K){l="SpreadElement"}else{l=a?"UpdateExpression":"UnaryExpression";n.operator=f;n.prefix=true}$=true;s();n.argument=Ln();if(a)W(n.argument);else if(M&&n.operator==="delete"&&n.argument.type==="Identifier")u(n.start,"Deleting local variable in strict mode");return t(n,l)}var c=C();var r=gl(i);while(e.postfix&&!cn()){var n=S(c);n.operator=f;n.prefix=false;n.argument=r;W(r);s();r=t(n,"UpdateExpression")}return r}function gl(e){var n=C();return G(q(e),n)}function G(s,a,o){if(r.playground&&i($n)){var n=S(a);n.object=s;n.property=d(true);if(i(v)){n.arguments=Un(h,false)}else{n.arguments=[]}return G(t(n,"BindMemberExpression"),a,o)}else if(i(dt)){var n=S(a);n.object=s;n.property=d(true);return G(t(n,"VirtualPropertyExpression"),a,o)}else if(i(qn)){var n=S(a);n.object=s;n.property=d(true);n.computed=false;return G(t(n,"MemberExpression"),a,o)}else if(i(X)){var n=S(a);n.object=s;n.property=y();n.computed=true;l(N);return G(t(n,"MemberExpression"),a,o)}else if(!o&&i(v)){var n=S(a);n.callee=s;n.arguments=Un(h,false);return G(t(n,"CallExpression"),a,o)}else if(e===et){var n=S(a);n.tag=s;n.quasi=Ut();return G(t(n,"TaggedTemplateExpression"),a,o)}return s}function q(I){switch(e){case Ir:var n=o();s();return t(n,"ThisExpression");case mt:var b=C();var n=o();var A=o();s();n.object=t(A,"ThisExpression");n.property=G(d(),b);n.computed=false;return t(n,"MemberExpression");case wr:if(Rn)return Vl();case p:var b=C();var n=o();var g=d(e!==p);if(r.ecmaVersion>=7){if(g.name==="async"){if(e===v){s();var _=++Vn;if(e!==h){u=y();x=u.type==="SequenceExpression"?u.expressions:[u]}else{x=[]}l(h);if(Vn===_&&i(Q)){return tt(n,x,true)}else{n.callee=g;n.arguments=x;return G(t(n,"CallExpression"),b)}}else if(e===p){g=d();if(i(Q)){return tt(n,[g],true)}return g}if(e===dn){if(cn())return g;s();return Bt(n,I,true)}}else if(g.name==="await"){if(Xn)return Xl(n)}}if(i(Q)){return tt(n,[g])}return g;case kt:var n=o();n.regex={pattern:f.pattern,flags:f.flags};n.value=f.value;n.raw=a.slice(m,D);s();return t(n,"Literal");case yn:case J:case Mn:var n=o();n.value=f;n.raw=a.slice(m,D);s();return t(n,"Literal");case Er:case br:case xr:var n=o();n.value=e.atomValue;n.raw=e.keyword;s();return t(n,"Literal");case v:var b=C();var u,x;s();if(r.ecmaVersion>=7&&e===Fn){u=Lr(S(b),true)}else{var _=++Vn;if(e!==h){u=y();x=u.type==="SequenceExpression"?u.expressions:[u]}else{x=[]}l(h);if(Vn===_&&i(Q)){u=tt(S(b),x)}else{if(!u)c(jn);if(r.ecmaVersion>=6){for(var E=0;E<x.length;E++){if(x[E].type==="SpreadElement")c()}}if(r.preserveParens){var k=S(b);k.expression=u;u=t(k,"ParenthesizedExpression")}}}return u;case X:var n=o();s();if(r.ecmaVersion>=7&&e===Fn){return Lr(n,false)}n.elements=Un(N,true,true);return t(n,"ArrayExpression");case R:return vr();case dn:var n=o();s();return Bt(n,false,false);case wn:return Cr(o(),false);case Ar:return bl();case et:return Ut();case w:return ut();case $n:return xl();default:c()}}function xl(){var e=o();s();var n=C();e.callee=G(q(),n,true);if(i(v)){e.arguments=Un(h,false)}else{e.arguments=[]}return t(e,"BindFunctionExpression")}function bl(){var e=o();s();var n=C();e.callee=G(q(),n,true);if(i(v))e.arguments=Un(h,false);else e.arguments=mr;return t(e,"NewExpression")}function gr(){var e=S(r.locations?[m+1,ln.offset(1)]:m+1);e.value=f;e.tail=a.charCodeAt(D-1)!==123;s();var n=e.tail?1:2;return Cl(e,"TemplateElement",r.locations?[T-n,rn.offset(-n)]:T-n)}function Ut(){var n=o();n.expressions=[];var r=gr();n.quasis=[r];while(!r.tail){n.expressions.push(y());if(e!==Zn)c();n.quasis.push(r=gr())}return t(n,"TemplateLiteral")}function vr(a){var u=o(),y=true,S={};u.properties=[];s();while(!i(b)){if(!y){l(x);if(r.allowTrailingCommas&&i(b))break}else y=false;var n=o(),m,h=false,g=false;if(r.ecmaVersion>=7&&e===K){n=Ln();n.type="SpreadProperty";u.properties.push(n);continue}if(r.ecmaVersion>=6){n.method=false;n.shorthand=false;if(a){m=C()}else{h=i(Y)}}if(r.ecmaVersion>=7&&e===p&&f==="async"){var k=d();if(e===_||e===v){n.key=k}else{g=true;hn(n)}}else{hn(n)}var E;if(e===w){E=nn();if(e!==v)c()}if(i(_)){n.value=a?Ft(m):fn();n.kind="init"}else if(r.ecmaVersion>=6&&e===v){if(a)c();n.kind="init";n.method=true;n.value=Pt(h,g)}else if(r.ecmaVersion>=5&&!n.computed&&n.key.type==="Identifier"&&(n.key.name==="get"||n.key.name==="set"||r.playground&&n.key.name==="memo")&&(e!=x&&e!=b)){if(h||g||a)c();n.kind=n.key.name;hn(n);n.value=Pt(false,false)}else if(r.ecmaVersion>=6&&!n.computed&&n.key.type==="Identifier"){n.kind="init";n.value=a?Ft(m,n.key):n.key;n.shorthand=true}else c();n.value.typeParameters=E;ra(n,S);u.properties.push(t(n,"Property"))}return t(u,a?"ObjectPattern":"ObjectExpression")}function hn(n){if(r.ecmaVersion>=6){if(i(X)){n.computed=true;n.key=y();l(N);return}else{n.computed=false}}n.key=e===yn||e===J?q():d(true)}function it(e,n){e.id=null;e.params=[];if(r.ecmaVersion>=6){e.defaults=[];e.rest=null;e.generator=false}if(r.ecmaVersion>=7){e.async=n}}function Bt(n,l,a,s){it(n,a);if(r.ecmaVersion>=6){n.generator=i(Y)}if(l||e===p){n.id=d()}if(e===w){n.typeParameters=nn()}Sr(n);Et(n,s);return t(n,l?"FunctionDeclaration":"FunctionExpression")}function Pt(l,a){var e=o();it(e,a);Sr(e);var n;if(r.ecmaVersion>=6){e.generator=l;n=true}else{n=false}Et(e,n);return t(e,"FunctionExpression")}function tt(e,r,o){it(e,o);var a=e.defaults,i=false;for(var l=0,s=r.length-1;l<=s;l++){var n=r[l];if(n.type==="AssignmentExpression"&&n.operator==="="){i=true;r[l]=n.left;a.push(n.right)}else{_n(n,l===s,true);a.push(null);if(n.type==="SpreadElement"){r.length--;e.rest=n.argument;break}}}e.params=r;if(!i)e.defaults=[];Et(e,true);return t(e,"ArrowFunctionExpression")}function Sr(n){var t=[],a=false;l(v);for(;;){if(i(h)){break}else if(r.ecmaVersion>=6&&i(K)){n.rest=vn();jt(n.rest);kr(n.rest);l(h);t.push(null);break}else{var s=vn();kr(s);n.params.push(s);if(r.ecmaVersion>=6){if(i(tn)){a=true;t.push(y(true))}else{t.push(null)}}if(!i(x)){l(h);break}}}if(a)n.defaults=t;if(e===_){n.returnType=Pn()}}function kr(n){if(i(Z)){n.optional=true}if(e===_){n.typeAnnotation=Pn()}t(n,n.type)}function Et(n,a){var r=a&&e!==R;var i=Xn;Xn=n.async;if(r){n.body=y(true);n.expression=true}else{var s=Gn,o=Rn,u=k;Gn=true;Rn=n.generator;k=[];n.body=In(true);n.expression=false;Gn=s;Rn=o;k=u}Xn=i;if(M||!r&&n.body.body.length&&At(n.body.body[0])){var l={};if(n.id)Tn(n.id,{});for(var t=0;t<n.params.length;t++)Tn(n.params[t],l);if(n.rest)Tn(n.rest,l)}}function Rr(e){e.declarations=[];do{e.declarations.push(d())}while(i(x));j();return t(e,"PrivateDeclaration")}function Cr(a,g){s();a.id=e===p?d():g?c():null;if(e===w){a.typeParameters=nn()}a.superClass=i(Ct)?fn(false,true):null;if(a.superClass&&e===w){a.superTypeParameters=Kn()}if(e===p&&f==="implements"){s();a.implements=Ml()}var u=o();u.body=[];l(R);while(!i(b)){while(i(L));if(e===b)continue;var n=o();if(r.ecmaVersion>=7&&e===p&&f==="private"){s();u.body.push(Rr(n));continue}if(e===p&&f==="static"){s();n["static"]=true}else{n["static"]=false}var m=false;var h=i(Y);if(r.ecmaVersion>=7&&!h&&e===p&&f==="async"){var x=d();if(e===_||e===v){n.key=x}else{m=true;hn(n)}}else{hn(n)}if(e!==v&&!n.computed&&n.key.type==="Identifier"&&(n.key.name==="get"||n.key.name==="set"||r.playground&&n.key.name==="memo")){if(h||m)c();n.kind=n.key.name;hn(n)}else{n.kind=""}if(e===_){if(h||m)c();n.typeAnnotation=Pn();j();u.body.push(t(n,"ClassProperty"))}else{var y;if(e===w){y=nn()}n.value=Pt(h,m);n.value.typeParameters=y;u.body.push(t(n,"MethodDefinition"))}}a.body=t(u,"ClassBody");return t(a,g?"ClassDeclaration":"ClassExpression")}function Ml(){var r=[];do{var n=o();n.id=d();if(e===w){n.typeParameters=Kn()}else{n.typeParameters=null}r.push(t(n,"ClassImplements"))}while(i(x));return r}function Un(t,s,o){var n=[],a=true;while(!i(t)){if(!a){l(x);if(s&&r.allowTrailingCommas&&i(t))break}else a=false;if(o&&e===x)n.push(null);else n.push(y(true))}return n}function d(n){var l=o();if(n&&r.forbidReserved=="everywhere")n=false;if(e===p){if(!n&&(r.forbidReserved&&(r.ecmaVersion===3?al:il)(f)||M&&Mt(f))&&a.slice(m,D).indexOf("\\")==-1)u(m,"The keyword '"+f+"' is reserved");l.name=f}else if(n&&e.keyword){l.name=e.keyword}else{c()}$=false;s();return t(l,"Identifier")}function Nl(n){s();if(e===kn||e===zn||e===An||e===dn||e===wn||e===p&&f==="async"){n.declaration=F();n["default"]=false;n.specifiers=null;n.source=null}else if(i(Yn)){var r=n.declaration=y(true);if(r.id){if(r.type==="FunctionExpression"){r.type="FunctionDeclaration"}else if(r.type==="ClassExpression"){r.type="ClassDeclaration"}}n["default"]=true;n.specifiers=null;n.source=null;j()}else{var l=e===Y;n.declaration=null;n["default"]=false;n.specifiers=Fl();if(e===p&&f==="from"){s();n.source=e===J?q():c()}else{if(l)c();n.source=null}j()}return t(n,"ExportDeclaration")}function Fl(){var a=[],u=true;if(e===Y){var n=o();s();a.push(t(n,"ExportBatchSpecifier"))}else{l(R);while(!i(b)){if(!u){l(x);if(r.allowTrailingCommas&&i(b))break}else u=false;var n=o();n.id=d(e===Yn);if(e===p&&f==="as"){s();n.name=d(true)}else{n.name=null}a.push(t(n,"ExportSpecifier"))}}return a}function Bl(n){s();if(e===J){n.specifiers=[];n.source=q()}else{n.specifiers=Ul();if(e!==p||f!=="from")c();s();n.source=e===J?q():c()}j();return t(n,"ImportDeclaration")}function Ul(){var a=[],u=true;if(e===p){var n=o();n.id=o();n.name=d();W(n.name,true);n.id.name="default";t(n.id,"Identifier");a.push(t(n,"ImportSpecifier"));if(!i(x))return a}if(e===Y){var n=o();s();if(e!==p||f!=="as")c();s();n.name=d();W(n.name,true);a.push(t(n,"ImportBatchSpecifier"));return a}l(R);while(!i(b)){if(!u){l(x);if(r.allowTrailingCommas&&i(b))break}else u=false;var n=o();n.id=d(true);if(e===p&&f==="as"){s();n.name=d()}else{n.name=null}W(n.name||n.id,true);n["default"]=false;a.push(t(n,"ImportSpecifier"))}return a}function Vl(){var e=o();s();if(i(L)||cn()){e.delegate=false;e.argument=null}else{e.delegate=i(Y);e.argument=y(true)}return t(e,"YieldExpression")}function Xl(e){if(i(L)||cn()){c()}e.delegate=i(Y);e.argument=y(true);return t(e,"AwaitExpression")}function Lr(n,a){n.blocks=[];while(e===Fn){var r=o();s();l(v);r.left=vn();W(r.left,true);if(e!==p||f!=="of")c();s();r.of=true;r.right=y();l(h);n.blocks.push(t(r,"ComprehensionBlock"))}n.filter=i(Tt)?gn():null;n.body=y();l(a?h:N);n.generator=a;return t(n,"ComprehensionExpression")}function Dn(e){if(e.type==="XJSIdentifier"){return e.name}if(e.type==="XJSNamespacedName"){return e.namespace.name+":"+e.name.name}if(e.type==="XJSMemberExpression"){return Dn(e.object)+"."+Dn(e.property)}}function Sn(){var n=o();if(e===bt){n.name=f}else if(e.keyword){n.name=e.keyword}else{c()}$=false;s();return t(n,"XJSIdentifier")}function Mr(){var e=o();e.namespace=Sn();l(_);e.name=Sn();return t(e,"XJSNamespacedName")}function Hl(){var r=C();var e=Sn();while(i(qn)){var n=S(r);n.object=e;n.property=Sn();e=t(n,"XJSMemberExpression")}return e}function Or(){switch(an()){case":":return Mr();case".":return Hl();default:return Sn()}}function Yl(){if(an()===":"){return Mr()}return Sn()}function $l(){switch(e){case R:var n=Dr();if(n.expression.type==="XJSEmptyExpression"){u(n.start,"XJS attributes must only be assigned a non-empty "+"expression")}return n;case w:return ut();case Mn:return q();default:u(m,"XJS value should be either an expression or a quoted XJS text")}}function Kl(){if(e!==b){c()}var n;n=m;m=T;T=n;n=ln;ln=rn;rn=n;return t(o(),"XJSEmptyExpression")}function Dr(){var r=o();var a=I,i=A;I=false;A=false;s();r.expression=e===b?Kl():y();I=a;A=i;if(A){n=D}l(b);return t(r,"XJSExpressionContainer")}function Zl(){if(e===R){var a=m,i=ln;var u=I;I=false;s();if(e!==K)c();var n=Ln();I=u;l(b);n.type="XJSSpreadAttribute";n.start=a;n.end=T;if(r.locations){n.loc.start=i;n.loc.end=rn}if(r.ranges){n.range=[a,T]}return n}var n=o();n.name=Yl();if(e===tn){s();n.value=$l()}else{n.value=null}return t(n,"XJSAttribute")}function ea(){switch(e){case R:return Dr();case Mn:return q();default:return ut()}}function na(){var n=o(),r=n.attributes=[];var a=A;var u=I;A=false;I=true;s();n.name=Or();while(e!==xn&&e!==Bn&&e!==H){r.push(Zl())}I=false;if(n.selfClosing=!!i(Bn)){I=u;A=a}else{A=true}l(H);return t(n,"XJSOpeningElement")}function ta(){var e=o();var r=A;var a=I;A=false;I=true;$=false;l(ot);e.name=Or();sn();A=r;I=a;$=false;if(A){n=D}l(H);return t(e,"XJSClosingElement")}function ut(){var n=o();var a=[];var i=A;var r=na();var l=null;if(!r.selfClosing){while(e!==xn&&e!==ot){A=true;a.push(ea())}A=i;l=ta();if(Dn(l.name)!==Dn(r.name)){u(l.start,"Expected corresponding XJS closing tag for '"+Dn(r.name)+"'")}}if(!i&&e===w){u(m,"Adjacent XJS elements must be wrapped in an enclosing tag")}n.openingElement=r;n.closingElement=l;n.children=a;return t(n,"XJSElement")}function la(e){s();Br(e,true);return t(e,"DeclareClass")}function aa(a){s();var r=a.id=d();var n=o();var i=o();if(e===w){n.typeParameters=nn()}else{n.typeParameters=null}l(v);var u=St();n.params=u.params;n.rest=u.rest;l(h);l(_);n.returnType=O();i.typeAnnotation=t(n,"FunctionTypeAnnotation");r.typeAnnotation=t(i,"TypeAnnotation");t(r,r.type);j();return t(a,"DeclareFunction")}function Fr(n){if(e===wn){return la(n)}else if(e===dn){return aa(n)}else if(e===kn){return sa(n)}else if(e===p&&f==="module"){return oa(n)}else{c()}}function sa(e){s();e.id=Ql();j();return t(e,"DeclareVariable")}function oa(n){s();if(e===J){n.id=q()}else{n.id=d()}var r=n.body=o();var a=r.body=[];l(R);while(e!==b){var i=o();s();a.push(Fr(i))}l(b);t(r,"BlockStatement");return t(n,"DeclareModule")}function Br(n,t){n.id=d();if(e===w){n.typeParameters=nn()}else{n.typeParameters=null}n.extends=[];if(i(Ct)){do{n.extends.push(ca())}while(i(x))}n.body=Jr(t)}function ca(){var n=o();n.id=d();if(e===w){n.typeParameters=Kn()}else{n.typeParameters=null}return t(n,"InterfaceExtends")}function fa(e){Br(e,false);return t(e,"InterfaceDeclaration")}function pa(n){n.id=d();if(e===w){n.typeParameters=nn()}else{n.typeParameters=null}l(tn);n.right=O();j();return t(n,"TypeAlias")}function nn(){var n=o();n.params=[];l(w);while(e!==H){n.params.push(d());if(e!==H){l(x)}}l(H);return t(n,"TypeParameterDeclaration")}function Kn(){var n=o(),r=on;n.params=[];on=true;l(w);while(e!==H){n.params.push(O());if(e!==H){l(x)}}l(H);on=r;return t(n,"TypeParameterInstantiation")}function Xr(){return e===yn||e===J?q():d(true)}function ga(e,n){e.static=n;l(X);e.id=Xr();l(_);e.key=O();l(N);l(_);e.value=O();return t(e,"ObjectTypeIndexer")}function qr(n){n.params=[];n.rest=null;n.typeParameters=null;if(e===w){n.typeParameters=nn()}l(v);while(e===p){n.params.push(nt());if(e!==h){l(x)}}if(i(K)){n.rest=nt()}l(h);l(_);n.returnType=O();return t(n,"FunctionTypeAnnotation")}function va(n,r,l){var e=S(n);e.value=qr(S(n));e.static=r;e.key=l;e.optional=false;return t(e,"ObjectTypeProperty")}function xa(e,n){var r=o();e.static=n;e.value=qr(r);return t(e,"ObjectTypeCallProperty")}function Jr(m){var n=o();var r;var h=false;var y;var u;var x;var E;var a;n.callProperties=[];n.properties=[];n.indexers=[];l(R);while(e!==b){var g=C();r=o();if(m&&e===p&&f==="static"){s();a=true}if(e===X){n.indexers.push(ga(r,a))}else if(e===v||e===w){n.callProperties.push(xa(r,m))}else{if(a&&e===_){u=d()}else{u=Xr()}if(e===w||e===v){n.properties.push(va(g,a,u))}else{if(i(Z)){h=true}l(_);r.key=u;r.value=O();r.optional=h;r.static=a;n.properties.push(t(r,"ObjectTypeProperty"))}}if(!i(L)&&e!==b){c()}}l(b);return t(n,"ObjectTypeAnnotation")}function Ea(l,a){var n=S(l);n.typeParameters=null;n.id=a;while(i(qn)){var r=S(l);r.qualification=n.id;r.id=d();n.id=t(r,"QualifiedTypeIdentifier")}if(e===w){n.typeParameters=Kn()}return t(n,"GenericTypeAnnotation")}function wa(){var e=o();l(Jn["void"]);return t(e,"VoidTypeAnnotation")}function _a(){var e=o();l(Jn["typeof"]);e.argument=Hr();return t(e,"TypeofTypeAnnotation")}function Sa(){var r=o();r.types=[];l(X);while(n<V&&e!==N){r.types.push(O());if(e===N)break;l(x)}l(N);return t(r,"TupleTypeAnnotation")}function nt(){var n=false;var e=o();e.name=d();if(i(Z)){n=true}l(_);e.optional=n;e.typeAnnotation=O();return t(e,"FunctionTypeParam")}function St(){var n={params:[],rest:null};while(e===p){n.params.push(nt());if(e!==h){l(x)}}if(i(K)){n.rest=nt()}return n}function Ra(r,e,n){switch(n.name){case"any":return t(e,"AnyTypeAnnotation");case"bool":case"boolean":return t(e,"BooleanTypeAnnotation");case"number":return t(e,"NumberTypeAnnotation");case"string":return t(e,"StringTypeAnnotation");default:return Ea(r,n)}}function Hr(){var A=null;var _=null;var I=null;var b=C();var n=o();var E=null;var r;var S;var k;var g;var x=false;switch(e){case p:return Ra(b,n,d());case R:return Jr();case X:return Sa();case w:n.typeParameters=nn();l(v);r=St();n.params=r.params;n.rest=r.rest;l(h);l(Q);n.returnType=O();return t(n,"FunctionTypeAnnotation");case v:s();var y;if(e!==h&&e!==K){if(e===p){}else{x=true}}if(x){if(y&&h){g=y}else{g=O();l(h)}if(i(Q)){u(n,"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 g}r=St();n.params=r.params;n.rest=r.rest;l(h);l(Q);n.returnType=O();n.typeParameters=null;return t(n,"FunctionTypeAnnotation");case J:n.value=f;n.raw=a.slice(m,D);s();return t(n,"StringLiteralTypeAnnotation");default:if(e.keyword){switch(e.keyword){case"void":return wa();case"typeof":return _a()}}}c()}function Aa(){var n=o();var r=n.elementType=Hr();if(e===X){l(X);l(N);return t(n,"ArrayTypeAnnotation")}return r}function vt(){var e=o();if(i(Z)){e.typeAnnotation=vt();return t(e,"NullableTypeAnnotation")}return Aa()}function Ht(){var e=o();var n=vt();e.types=[n];while(i(rr)){e.types.push(vt())}return e.types.length===1?n:t(e,"IntersectionTypeAnnotation")}function jl(){var e=o();var n=Ht();e.types=[n];while(i(ar)){e.types.push(Ht())}return e.types.length===1?n:t(e,"UnionTypeAnnotation")}function O(){var e=on;on=true;var n=jl();on=e;return n}function Pn(){var e=o();l(_);e.typeAnnotation=O();return t(e,"TypeAnnotation")}function Ql(a,s){var u=o();var n=d();var r=false;if(s&&i(Z)){l(Z);r=true}if(a||e===_){n.typeAnnotation=Pn();t(n,n.type)}if(r){n.optional=true;t(n,n.type)}return n}})},{}],2:[function(e,n,t){(function(r){"use strict";var t=n.exports=e("./transformation/transform");t.version=e("../../package").version;t.transform=t;t.run=function(n,e){e=e||{};e.sourceMap="inline";return new Function(t(n,e).code)()};t.load=function(l,a,n,i){n=n||{};n.filename=n.filename||l;var e=r.ActiveXObject?new r.ActiveXObject("Microsoft.XMLHTTP"):new r.XMLHttpRequest;e.open("GET",l,true);if("overrideMimeType"in e)e.overrideMimeType("text/plain");e.onreadystatechange=function(){if(e.readyState!==4)return;var r=e.status;if(r===0||r===200){var s=[e.responseText,n];if(!i)t.run.apply(t,s);if(a)a(s)}else{throw new Error("Could not load "+l)}};e.send(null)};var l=function(){var e=[];var o=["text/ecmascript-6","text/6to5","module"];var a=0;var l=function(){var n=e[a];if(n instanceof Array){t.run.apply(t,n);a++;l()}};var u=function(n,a){var r={};if(n.src){t.load(n.src,function(n){e[a]=n;l()},r,true)}else{r.filename="embedded";e[a]=[n.innerHTML,r]}};var i=r.document.getElementsByTagName("script");for(var n=0;n<i.length;++n){var s=i[n];if(o.indexOf(s.type)>=0)e.push(s)}for(n in e){u(e[n],n)}l()};if(r.addEventListener){r.addEventListener("DOMContentLoaded",l,false)}else if(r.attachEvent){r.attachEvent("onload",l)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"../../package":197,"./transformation/transform":44}],3:[function(a,o,c){"use strict";o.exports=e;var i=/^\#\!.*/;var l=a("./transformation/transform");var u=a("./generation/generator");var s=a("./traverse/scope");var r=a("./util");var t=a("./types");var n=a("lodash");function e(n){this.dynamicImports=[];this.dynamicImportIds={};this.opts=e.normaliseOptions(n);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=n.cloneDeep(e||{});n.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=r.arrayify(e.blacklist);e.whitelist=r.arrayify(e.whitelist);e.optional=r.arrayify(e.optional);e.loose=r.arrayify(e.loose);if(n.contains(e.loose,"all")){e.loose=Object.keys(l.transformers)}n.each({fastForOf:"forOf",classesFastSuper:"classes"},function(r,t){if(n.contains(e.optional,t)){n.pull(e.optional,t);e.loose.push(r)}});n.defaults(e,{moduleRoot:e.sourceRoot});n.defaults(e,{sourceRoot:e.moduleRoot});n.defaults(e,{filenameRelative:e.filename});n.defaults(e,{sourceFileName:e.filenameRelative,sourceMapName:e.filenameRelative});if(e.runtime===true){e.runtime="to5Runtime"}if(e.playground){e.experimental=true}l._ensureTransformerNames("blacklist",e.blacklist);l._ensureTransformerNames("whitelist",e.whitelist);l._ensureTransformerNames("optional",e.optional);l._ensureTransformerNames("loose",e.loose);return e};e.prototype.isLoose=function(e){return n.contains(this.opts.loose,e)};e.prototype.getTransformers=function(){var e=this;var t=[];var r=[];n.each(l.transformers,function(n){if(n.canRun(e)){t.push(n);if(n.secondPass){r.push(n)}if(n.manipulateOptions){n.manipulateOptions(e.opts,e)}}});return t.concat(r)};e.prototype.toArray=function(e,n){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 r="to-array";var l=[e];if(n){l.push(t.literal(n));r="sliced-to-array"}return t.callExpression(this.addHelper(r),l)}};e.prototype.getModuleFormatter=function(e){var t=n.isFunction(e)?e:l.moduleFormatters[e];if(!t){var i=r.resolve(e);if(i)t=a(i)}if(!t){throw new ReferenceError("Unknown module formatter type "+JSON.stringify(e))}return new t(this)};e.prototype.parseShebang=function(e){var n=e.match(i);if(n){this.shebang=n[0];e=e.replace(i,"")}return e};e.prototype.addImport=function(r,e){e=e||r;var n=this.dynamicImportIds[e];if(!n){n=this.dynamicImportIds[e]=this.generateUidIdentifier(e);var a=[t.importSpecifier(t.identifier("default"),n)];var l=t.importDeclaration(a,t.literal(r));l._blockHoist=3;this.dynamicImports.push(l)}return n};e.prototype.addHelper=function(l){if(!n.contains(e.helpers,l)){throw new ReferenceError("unknown declaration "+l)}var a=this.ast.program;var i=a._declarations&&a._declarations[l];if(i)return i.id;var s;var o=this.opts.runtime;if(o&&!n.contains(e.excludeHelpersFromRuntime,l)){l=t.identifier(t.toIdentifier(l));return t.memberExpression(t.identifier(o),l)}else{s=r.template(l)}var u=this.generateUidIdentifier(l);this.scope.push({key:l,id:u,init:s});return u};e.prototype.errorWithNode=function(r,l,e){e=e||SyntaxError;var n=r.loc.start;var t=new e("Line "+n.line+": "+l);t.loc=n;return t};e.prototype.addCode=function(e){e=(e||"")+"";this.code=e;return this.parseShebang(e)};e.prototype.parse=function(e){var n=this;e=this.addCode(e);return r.parse(this.opts,e,function(e){n.transform(e);return n.generate()})};e.prototype.transform=function(t){var e=this;this.ast=t;this.scope=new s(t.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var r=function(t){n.each(e.transformers,function(n){n.astRun(e,t)})};r("enter");n.each(this.transformers,function(n){n.transform(e)});r("exit")};e.prototype.generate=function(){var n=this.opts;var t=this.ast;var e={code:"",map:null,ast:null};if(n.ast)e.ast=t;if(!n.code)return e;var l=u(t,n,this.code);e.code=l.code;e.map=l.map;if(this.shebang){e.code=this.shebang+"\n"+e.code}if(n.sourceMap==="inline"){e.code+="\n"+r.sourceMapToComment(e.map)}return e};e.prototype.generateUid=function(e,n){e=t.toIdentifier(e).replace(/^_+/,"");n=n||this.scope;var r;do{r=this._generateUid(e)}while(n.has(r));return r};e.prototype.generateUidIdentifier=function(r,e){e=e||this.scope;var n=t.identifier(this.generateUid(r,e));e.add(n);return n};e.prototype._generateUid=function(e){var t=this.uids;var n=t[e]||1;var r=e;if(n>1)r+=n;t[e]=n+1;return"_"+r}},{"./generation/generator":5,"./transformation/transform":44,"./traverse/scope":89,"./types":92,"./util":94,lodash:142}],4:[function(r,l,a){"use strict";l.exports=e;var n=r("../util");var t=r("lodash");function e(n,e){this.position=n;this._indent=e.indent.base;this.format=e;this.buf=""}e.prototype.get=function(){return n.trimRight(this.buf)};e.prototype.getIndent=function(){if(this.format.compact){return""}else{return n.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,r){if(this.format.compact)return;r=r||false;if(t.isNumber(e)){if(this.endsWith("{\n"))e--;if(this.endsWith(n.repeat(e,"\n")))return;while(e--){this._newline(r)}return}if(t.isBoolean(e)){r=e}this._newline(r)};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 n=this.buf.lastIndexOf("\n");if(n===-1)return;var e=this.buf.length-1;while(e>n){if(this.buf[e]!==" "){break}e--}if(e===n){this.buf=this.buf.substring(0,e+1)}};e.prototype.push=function(e,t){if(this._indent&&!t&&e!=="\n"){var n=this.getIndent();e=e.replace(/\n/g,"\n"+n);if(this.isLast("\n"))e=n+e}this._push(e)};e.prototype._push=function(e){this.position.push(e);this.buf+=e};e.prototype.endsWith=function(e){var n=this.buf.length-e.length;return n>=0&&this.buf.lastIndexOf(e)===n};e.prototype.isLast=function(r,a){var e=this.buf;if(a)e=n.trimRight(e);var l=e[e.length-1];if(Array.isArray(r)){return t.contains(r,l)}else{return r===l}}},{"../util":94,lodash:142}],5:[function(e,a,f){"use strict";a.exports=function(e,t,r){var l=new n(e,t,r);return l.generate()};a.exports.CodeGenerator=n;var s=e("./whitespace");var o=e("./source-map");var u=e("./position");var i=e("./buffer");var c=e("../util");var r=e("./node");var l=e("../types");var t=e("lodash");function n(t,e,r){e=e||{};this.comments=t.comments||[];this.tokens=t.tokens||[];this.format=n.normaliseOptions(e);this.ast=t;this.whitespace=new s(this.tokens,this.comments);this.position=new u;this.map=new o(this.position,e,r);this.buffer=new i(this.position,this.format)}t.each(i.prototype,function(e,t){n.prototype[t]=function(){return e.apply(this.buffer,arguments)}});n.normaliseOptions=function(e){return t.merge({parentheses:true,comments:e.comments==null||e.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},e.format||{})};n.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")};t.each(n.generators,function(e){t.extend(n.prototype,e)});n.prototype.generate=function(){var e=this.ast;this.print(e);var n=[];t.each(e.comments,function(e){if(!e._displayed)n.push(e)});this._printComments(n);return{map:this.map.get(),code:this.buffer.get()}};n.prototype.buildPrint=function(t){var n=this;var e=function(e,r){return n.print(e,t,r)};e.sequence=function(r,t){t=t||{};t.statement=true;return n.printJoin(e,r,t)};e.join=function(t,r){return n.printJoin(e,t,r)};e.block=function(t){return n.printBlock(e,t)};e.indentOnComments=function(t){return n.printAndIndentOnComments(e,t)};return e};n.prototype.print=function(e,n,t){if(!e)return"";var l=this;t=t||{};var i=function(i){if(!t.statement&&!r.isUserWhitespacable(e,n)){return}var a=0;if(e.start!=null&&!e._ignoreUserWhitespace){if(i){a=l.whitespace.getNewlinesBefore(e)}else{a=l.whitespace.getNewlinesAfter(e)}}else{if(!i)a++;var s=r.needsWhitespaceAfter;if(i)s=r.needsWhitespaceBefore;a+=s(e,n);if(!l.buffer.get())a=0}l.newline(a)};if(this[e.type]){var a=r.needsParensNoLineTerminator(e,n);var s=a||r.needsParens(e,n);if(s)this.push("(");if(a)this.indent();this.printLeadingComments(e,n);i(true);if(t.before)t.before();this.map.mark(e,"start");this[e.type](e,this.buildPrint(e),n);if(a){this.newline();this.dedent()}if(s)this.push(")");this.map.mark(e,"end");if(t.after)t.after();i(false);this.printTrailingComments(e,n)}else{throw new ReferenceError("unknown node of type "+JSON.stringify(e.type)+" with constructor "+JSON.stringify(e&&e.constructor.name))}};n.prototype.printJoin=function(l,n,e){if(!n||!n.length)return;e=e||{};var r=this;var a=n.length;if(e.indent)r.indent();t.each(n,function(n,t){l(n,{statement:e.statement,after:function(){if(e.iterator){e.iterator(n,t)}if(e.separator&&t<a-1){r.push(e.separator)}}})});if(e.indent)r.dedent()};n.prototype.printAndIndentOnComments=function(t,e){var n=!!e.leadingComments;if(n)this.indent();t(e);if(n)this.dedent()};n.prototype.printBlock=function(n,e){if(l.isEmptyStatement(e)){this.semicolon()}else{this.push(" ");n(e)}};n.prototype.generateComment=function(n){var e=n.value;if(n.type==="Line"){e="//"+e}else{e="/*"+e+"*/"}return e};n.prototype.printTrailingComments=function(e,n){this._printComments(this.getComments("trailingComments",e,n))};n.prototype.printLeadingComments=function(e,n){this._printComments(this.getComments("leadingComments",e,n))};n.prototype.getComments=function(a,e,i){if(l.isExpressionStatement(i)){return[]}var n=[];var r=[e];var s=this;if(l.isExpressionStatement(e)){r.push(e.argument)}t.each(r,function(e){n=n.concat(s._getComments(a,e))});return n};n.prototype._getComments=function(n,e){return e&&e[n]||[]};n.prototype._printComments=function(n){if(this.format.compact)return;if(!this.format.comments)return;if(!n||!n.length)return;var e=this;t.each(n,function(r){var a=false;t.each(e.ast.comments,function(e){if(e.start===r.start){if(e._displayed)a=true;e._displayed=true;return false}});if(a)return;e.newline(e.whitespace.getNewlinesBefore(r));var l=e.position.column;var n=e.generateComment(r);if(l&&!e.isLast(["\n"," ","[","{"])){e._push(" ");l++}if(r.type==="Block"&&e.format.indent.adjustMultilineComment){var i=r.loc.start.column;if(i){var s=new RegExp("\\n\\s{1,"+i+"}","g");n=n.replace(s,"\n")}var o=Math.max(e.indentSize(),l);
n=n.replace(/\n/g,"\n"+c.repeat(o))}if(l===0){n=e.getIndent()+n}e._push(n);e.newline(e.whitespace.getNewlinesAfter(r))})}},{"../types":92,"../util":94,"./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:142}],6:[function(n,t,e){"use strict";e.File=function(e,n){n(e.program)};e.Program=function(e,n){n.sequence(e.body)};e.BlockStatement=function(e,n){if(e.body.length===0){this.push("{}")}else{this.push("{");this.newline();n.sequence(e.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],7:[function(n,t,e){"use strict";e.ClassExpression=e.ClassDeclaration=function(e,n){this.push("class");if(e.id){this.space();n(e.id)}if(e.superClass){this.push(" extends ");n(e.superClass)}this.space();n(e.body)};e.ClassBody=function(e,n){if(e.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();n.sequence(e.body);this.dedent();this.rightBrace()}};e.MethodDefinition=function(e,n){if(e.static){this.push("static ")}this._method(e,n)}},{}],8:[function(n,t,e){"use strict";e.ComprehensionBlock=function(e,n){this.keyword("for");this.push("(");n(e.left);this.push(" of ");n(e.right);this.push(")")};e.ComprehensionExpression=function(e,n){this.push(e.generator?"(":"[");n.join(e.blocks,{separator:" "});this.space();if(e.filter){this.keyword("if");this.push("(");n(e.filter);this.push(")");this.space()}n(e.body);this.push(e.generator?")":"]")}},{}],9:[function(t,s,e){"use strict";var l=t("../../util");var n=t("../../types");var a=t("lodash");e.UnaryExpression=function(e,l){var r=/[a-z]$/.test(e.operator);var t=e.argument;if(n.isUpdateExpression(t)||n.isUnaryExpression(t)){r=true}if(n.isUnaryExpression(t)&&t.operator==="!"){r=false}this.push(e.operator);if(r)this.space();l(e.argument)};e.UpdateExpression=function(e,n){if(e.prefix){this.push(e.operator);n(e.argument)}else{n(e.argument);this.push(e.operator)}};e.ConditionalExpression=function(e,n){n(e.test);this.push(" ? ");n(e.consequent);this.push(" : ");n(e.alternate)};e.NewExpression=function(e,n){this.push("new ");n(e.callee);if(e.arguments.length||this.format.parentheses){this.push("(");n.join(e.arguments,{separator:", "});this.push(")")}};e.SequenceExpression=function(e,n){n.join(e.expressions,{separator:", "})};e.ThisExpression=function(){this.push("this")};e.CallExpression=function(e,t){t(e.callee);this.push("(");var n=",";if(e._prettyCall){n+="\n";this.newline();this.indent()}else{n+=" "}t.join(e.arguments,{separator:n});if(e._prettyCall){this.newline();this.dedent()}this.push(")")};var r=function(e){return function(n,t){this.push(e);if(n.delegate)this.push("*");if(n.argument){this.space();t(n.argument)}}};e.YieldExpression=r("yield");e.AwaitExpression=r("await");e.EmptyStatement=function(){this.semicolon()};e.ExpressionStatement=function(e,n){n(e.expression);this.semicolon()};e.BinaryExpression=e.LogicalExpression=e.AssignmentPattern=e.AssignmentExpression=function(e,n){n(e.left);this.push(" "+e.operator+" ");n(e.right)};var i=/e/i;e.MemberExpression=function(e,r){var t=e.object;r(t);if(!e.computed&&n.isMemberExpression(e.property)){throw new TypeError("Got a MemberExpression for MemberExpression property")}var s=e.computed;if(n.isLiteral(e.property)&&a.isNumber(e.property.value)){s=true}if(s){this.push("[");r(e.property);this.push("]")}else{if(n.isLiteral(t)&&l.isInteger(t.value)&&!i.test(t.value.toString())){this.push(".")}this.push(".");r(e.property)}}},{"../../types":92,"../../util":94,lodash:142}],10:[function(n,t,e){"use strict";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(n,l,e){"use strict";var t=n("../../types");var r=n("lodash");e.XJSAttribute=function(e,n){n(e.name);if(e.value){this.push("=");n(e.value)}};e.XJSIdentifier=function(e){this.push(e.name)};e.XJSNamespacedName=function(e,n){n(e.namespace);this.push(":");n(e.name)};e.XJSMemberExpression=function(e,n){n(e.object);this.push(".");n(e.property)};e.XJSSpreadAttribute=function(e,n){this.push("{...");n(e.argument);this.push("}")};e.XJSExpressionContainer=function(e,n){this.push("{");n(e.expression);this.push("}")};e.XJSElement=function(e,n){var a=this;var l=e.openingElement;n(l);if(l.selfClosing)return;this.indent();r.each(e.children,function(e){if(t.isLiteral(e)){a.push(e.value)}else{n(e)}});this.dedent();n(e.closingElement)};e.XJSOpeningElement=function(e,n){this.push("<");n(e.name);if(e.attributes.length>0){this.space();n.join(e.attributes,{separator:" "})}this.push(e.selfClosing?" />":">")};e.XJSClosingElement=function(e,n){this.push("</");n(e.name);this.push(">")};e.XJSEmptyExpression=function(){}},{"../../types":92,lodash:142}],12:[function(n,r,e){"use strict";var t=n("../../types");e._params=function(e,n){var t=this;this.push("(");n.join(e.params,{separator:", ",iterator:function(a,l){var r=e.defaults&&e.defaults[l];if(r){t.push(" = ");n(r)}}});if(e.rest){if(e.params.length){this.push(", ")}this.push("...");n(e.rest)}this.push(")")};e._method=function(e,n){var t=e.value;var r=e.kind;var l=e.key;if(!r||r==="init"){if(t.generator){this.push("*")}}else{this.push(r+" ")}if(t.async)this.push("async ");if(e.computed){this.push("[");n(l);this.push("]")}else{n(l)}this._params(t,n);this.space();n(t.body)};e.FunctionDeclaration=e.FunctionExpression=function(e,n){if(e.async)this.push("async ");this.push("function");if(e.generator)this.push("*");this.space();if(e.id)n(e.id);this._params(e,n);this.space();n(e.body)};e.ArrowFunctionExpression=function(e,n){if(e.async)this.push("async ");if(e.params.length===1&&!e.defaults.length&&!e.rest&&t.isIdentifier(e.params[0])){n(e.params[0])}else{this._params(e,n)}this.push(" => ");n(e.body)}},{"../../types":92}],13:[function(n,l,e){"use strict";var t=n("../../types");var r=n("lodash");e.ImportSpecifier=function(n,t){if(n.id&&n.id.name==="default"){t(n.name)}else{return e.ExportSpecifier.apply(this,arguments)}};e.ExportSpecifier=function(e,n){n(e.id);if(e.name){this.push(" as ");n(e.name)}};e.ExportBatchSpecifier=function(){this.push("*")};e.ExportDeclaration=function(e,r){this.push("export ");var n=e.specifiers;if(e.default){this.push("default ")}if(e.declaration){r(e.declaration);if(t.isStatement(e.declaration))return}else{if(n.length===1&&t.isExportBatchSpecifier(n[0])){r(n[0])}else{this.push("{");if(n.length){this.space();r.join(n,{separator:", "});this.space()}this.push("}")}if(e.source){this.push(" from ");r(e.source)}}this.ensureSemicolon()};e.ImportDeclaration=function(e,t){var l=this;this.push("import ");var a=e.specifiers;if(a&&a.length){var n=false;r.each(e.specifiers,function(e,r){if(+r>0){l.push(", ")}var a=e.id&&e.id.name==="default";if(!a&&e.type!=="ImportBatchSpecifier"&&!n){n=true;l.push("{ ")}t(e)});if(n){this.push(" }")}this.push(" from ")}t(e.source);this.semicolon()};e.ImportBatchSpecifier=function(e,n){this.push("* as ");n(e.name)}},{"../../types":92,lodash:142}],14:[function(e,r,n){"use strict";var t=e("lodash");t.each(["BindMemberExpression","BindFunctionExpression"],function(e){n[e]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(e))}})},{lodash:142}],15:[function(t,i,e){"use strict";var a=t("../../util");var r=t("../../types");e.WithStatement=function(e,n){this.keyword("with");this.push("(");n(e.object);this.push(")");n.block(e.body)};e.IfStatement=function(e,n){this.keyword("if");this.push("(");n(e.test);this.push(") ");n.indentOnComments(e.consequent);if(e.alternate){if(this.isLast("}"))this.space();this.keyword("else");n.indentOnComments(e.alternate)}};e.ForStatement=function(e,n){this.keyword("for");this.push("(");n(e.init);this.push(";");if(e.test){this.space();n(e.test)}this.push(";");if(e.update){this.space();n(e.update)}this.push(")");n.block(e.body)};e.WhileStatement=function(e,n){this.keyword("while");this.push("(");n(e.test);this.push(")");n.block(e.body)};var l=function(e){return function(n,t){this.keyword("for");this.push("(");t(n.left);this.push(" "+e+" ");t(n.right);this.push(")");t.block(n.body)}};e.ForInStatement=l("in");e.ForOfStatement=l("of");e.DoWhileStatement=function(e,n){this.keyword("do");n(e.body);this.space();this.keyword("while");this.push("(");n(e.test);this.push(");")};var n=function(e,n){return function(r,l){this.push(e);var t=r[n||"label"];if(t){this.space();l(t)}this.semicolon()}};e.ContinueStatement=n("continue");e.ReturnStatement=n("return","argument");e.BreakStatement=n("break");e.LabeledStatement=function(e,n){n(e.label);this.push(": ");n(e.body)};e.TryStatement=function(e,n){this.keyword("try");n(e.block);this.space();if(e.handlers){n(e.handlers[0])}else{n(e.handler)}if(e.finalizer){this.space();this.push("finally ");n(e.finalizer)}};e.CatchClause=function(e,n){this.keyword("catch");this.push("(");n(e.param);this.push(") ");n(e.body)};e.ThrowStatement=function(e,n){this.push("throw ");n(e.argument);this.semicolon()};e.SwitchStatement=function(e,n){this.keyword("switch");this.push("(");n(e.discriminant);this.push(") {");n.sequence(e.cases,{indent:true});this.push("}")};e.SwitchCase=function(e,n){if(e.test){this.push("case ");n(e.test);this.push(":")}else{this.push("default:")}this.newline();n.sequence(e.consequent,{indent:true})};e.DebuggerStatement=function(){this.push("debugger;")};e.VariableDeclaration=function(e,o,l){this.push(e.kind+" ");var i=0;var s=0;if(!r.isFor(l)){for(var n=0;n<e.declarations.length;n++){if(e.declarations[n].init){i++}else{s++}}}var t=",";if(i>s){t+="\n"+a.repeat(e.kind.length+1)}else{t+=" "}o.join(e.declarations,{separator:t});if(!r.isFor(l)){this.semicolon()}};e.PrivateDeclaration=function(e,n){this.push("private ");n.join(e.declarations,{separator:", "});this.semicolon()};e.VariableDeclarator=function(e,n){if(e.init){n(e.id);this.push(" = ");n(e.init)}else{n(e.id)}}},{"../../types":92,"../../util":94}],16:[function(n,r,e){"use strict";var t=n("lodash");e.TaggedTemplateExpression=function(e,n){n(e.tag);n(e.quasi)};e.TemplateElement=function(e){this._push(e.value.raw)};e.TemplateLiteral=function(e,n){this.push("`");var r=e.quasis;var l=this;var a=r.length;t.each(r,function(r,t){n(r);if(t+1<a){l.push("${ ");n(e.expressions[t]);l.push(" }")}});this._push("`")}},{lodash:142}],17:[function(n,r,e){"use strict";var t=n("lodash");e.Identifier=function(e){this.push(e.name)};e.SpreadElement=e.SpreadProperty=function(e,n){this.push("...");n(e.argument)};e.VirtualPropertyExpression=function(e,n){n(e.object);this.push("::");n(e.property)};e.ObjectExpression=e.ObjectPattern=function(n,t){var e=n.properties;if(e.length){this.push("{");this.space();t.join(e,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};e.Property=function(e,n){if(e.method||e.kind==="get"||e.kind==="set"){this._method(e,n)}else{if(e.computed){this.push("[");n(e.key);this.push("]")}else{n(e.key);if(e.shorthand)return}this.push(": ");n(e.value)}};e.ArrayExpression=e.ArrayPattern=function(r,l){var n=r.elements;var e=this;var a=n.length;this.push("[");t.each(n,function(n,t){if(!n){e.push(",")}else{if(t>0)e.push(" ");l(n);if(t<a-1)e.push(",")}});this.push("]")};e.Literal=function(n){var e=n.value;var t=typeof e;if(t==="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(t==="boolean"||t==="number"){this.push(JSON.stringify(e))}else if(n.regex){this.push("/"+n.regex.pattern+"/"+n.regex.flags)}else if(e===null){this.push("null")}}},{lodash:142}],18:[function(t,i,o){"use strict";i.exports=e;var a=t("./whitespace");var s=t("./parentheses");var n=t("../../types");var r=t("lodash");var l=function(e,l,s){if(!e)return;var t;var a=Object.keys(e);for(var r=0;r<a.length;r++){var i=a[r];if(n.is(i,l)){var o=e[i];t=o(l,s);if(t!=null)break}}return t};function e(e,n){this.parent=n;this.node=e}e.isUserWhitespacable=function(e){return n.isUserWhitespacable(e)};e.needsWhitespace=function(t,o,s){if(!t)return 0;if(n.isExpressionStatement(t)){t=t.expression}var i=l(a[s].nodes,t,o);if(i)return i;r.each(l(a[s].list,t,o),function(n){i=e.needsWhitespace(n,t,s);if(i)return false});return i||0};e.needsWhitespaceBefore=function(n,t){return e.needsWhitespace(n,t,"before")};e.needsWhitespaceAfter=function(n,t){return e.needsWhitespace(n,t,"after")};e.needsParens=function(e,t){if(!t)return false;if(n.isNewExpression(t)&&t.callee===e){if(n.isCallExpression(e))return true;var a=r.some(e,function(e){return n.isCallExpression(e)});if(a)return true}return l(s,e,t)};e.needsParensNoLineTerminator=function(t,e){if(!e)return false;if(!t.leadingComments||!t.leadingComments.length){return false}if(n.isYieldExpression(e)||n.isAwaitExpression(e)){return true}if(n.isContinueStatement(e)||n.isBreakStatement(e)||n.isReturnStatement(e)||n.isThrowStatement(e)){return true}return false};r.each(e,function(t,n){e.prototype[n]=function(){var t=new Array(arguments.length+2);t[0]=this.node;t[1]=this.parent;for(var r=0;r<t.length;r++){t[r+2]=arguments[r]}return e[n].apply(null,t)}})},{"../../types":92,"./parentheses":19,"./whitespace":20,lodash:142}],19:[function(r,a,n){"use strict";var e=r("../../types");var l=r("lodash");var t={};l.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"],["**"]],function(e,n){l.each(e,function(e){t[e]=n})});n.UpdateExpression=function(t,n){if(e.isMemberExpression(n)&&n.object===t){return true}};n.ObjectExpression=function(t,n){if(e.isExpressionStatement(n)){return true}if(e.isMemberExpression(n)&&n.object===t){return true}return false};n.Binary=function(r,n){if((e.isCallExpression(n)||e.isNewExpression(n))&&n.callee===r){return true}if(e.isUnaryLike(n)){return true}if(e.isMemberExpression(n)&&n.object===r){return true}if(e.isBinary(n)){var i=n.operator;var l=t[i];var s=r.operator;var a=t[s];if(l>a){return true}if(l===a&&n.right===r){return true}}};n.BinaryExpression=function(t,n){if(t.operator==="in"){if(e.isVariableDeclarator(n)){return true}if(e.isFor(n)){return true}}};n.SequenceExpression=function(t,n){if(e.isForStatement(n)){return false}if(e.isExpressionStatement(n)&&n.expression===t){return false}return true};n.YieldExpression=function(t,n){return e.isBinary(n)||e.isUnaryLike(n)||e.isCallExpression(n)||e.isMemberExpression(n)||e.isNewExpression(n)||e.isConditionalExpression(n)||e.isYieldExpression(n)};n.ClassExpression=function(t,n){return e.isExpressionStatement(n)};n.UnaryLike=function(t,n){return e.isMemberExpression(n)&&n.object===t};n.FunctionExpression=function(t,n){if(e.isExpressionStatement(n)){return true}if(e.isMemberExpression(n)&&n.object===t){return true}if(e.isCallExpression(n)&&n.callee===t){return true}};n.AssignmentExpression=n.ConditionalExpression=function(t,n){if(e.isUnaryLike(n)){return true}if(e.isBinary(n)){return true}if(e.isCallExpression(n)&&n.callee===t){return true}if(e.isConditionalExpression(n)&&n.test===t){return true}if(e.isMemberExpression(n)&&n.object===t){return true}return false}},{"../../types":92,lodash:142}],20:[function(r,l,n){"use strict";var e=r("lodash");var t=r("../../types");n.before={nodes:{Property:function(e,n){if(n.properties[0]===e){return 1}},SpreadProperty:function(e,t){return n.before.nodes.Property(e,t)},SwitchCase:function(e,n){if(n.cases[0]===e){return 1}},CallExpression:function(e){if(t.isFunction(e.callee)){return 1}}}};n.after={nodes:{AssignmentExpression:function(e){if(t.isFunction(e.right)){return 1}}},list:{VariableDeclaration:function(n){return e.map(n.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(r,l){if(e.isNumber(r)){r={after:r,before:r}}e.each([l].concat(t.FLIPPED_ALIAS_KEYS[l]||[]),function(t){e.each(r,function(e,r){n[r].nodes[t]=function(){return e}})})})},{"../../types":92,lodash:142}],21:[function(t,n,r){"use strict";n.exports=e;function e(){this.line=1;this.column=0}e.prototype.push=function(n){for(var e=0;e<n.length;e++){if(n[e]==="\n"){this.line++;this.column=0}else{this.column++}}};e.prototype.unshift=function(n){for(var e=0;e<n.length;e++){if(n[e]==="\n"){this.line--}else{this.column--}}}},{}],22:[function(n,r,a){"use strict";r.exports=e;var l=n("source-map");var t=n("../types");function e(n,e,t){this.position=n;this.opts=e;if(e.sourceMap){this.map=new l.SourceMapGenerator({file:e.sourceMapName,sourceRoot:e.sourceRoot});this.map.setSourceContent(e.sourceFileName,t)}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,s){var l=e.loc;if(!l)return;var a=this.map;if(!a)return;if(t.isProgram(e)||t.isFile(e))return;var i=this.position;var n={line:i.line,column:i.column};var r=l[s];if(n.line===r.line&&n.column===r.column)return;a.addMapping({source:this.opts.sourceFileName,generated:n,original:r})}},{"../types":92,"source-map":186}],23:[function(t,r,a){"use strict";r.exports=e;var l=t("lodash");function n(e,t,n){e+=t;if(e>=n)e-=n;return e}function e(e,n){this.tokens=l.sortBy(e.concat(n),"start");this.used={};this._lastFoundIndex=0}e.prototype.getNewlinesBefore=function(s){var a;var i;var e=this.tokens;var t;for(var r=0;r<e.length;r++){var l=n(r,this._lastFoundIndex,this.tokens.length);t=e[l];if(s.start===t.start){a=e[l-1];i=t;this._lastFoundIndex=l;break}}return this.getNewlinesBetween(a,i)};e.prototype.getNewlinesAfter=function(i){var s;var e;var t=this.tokens;var r;for(var l=0;l<t.length;l++){var a=n(l,this._lastFoundIndex,this.tokens.length);r=t[a];if(i.end===r.end){s=r;e=t[a+1];this._lastFoundIndex=a;break}}if(e.type.type==="eof"){return 1}else{var o=this.getNewlinesBetween(s,e);if(i.type==="Line"&&!o){return 1}else{return o}}};e.prototype.getNewlinesBetween=function(n,r){var l=n?n.loc.end.line:1;var a=r.loc.start.line;var t=0;for(var e=l;e<a;e++){if(typeof this.used[e]==="undefined"){this.used[e]=true;t++}}return t}},{lodash:142}],24:[function(n,s,o){"use strict";var l=n("./types");var a=n("lodash");var i=n("estraverse");a.extend(i.VisitorKeys,l.VISITOR_KEYS);var t=n("ast-types");var e=t.Type.def;var r=t.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",r(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",r(e("Identifier"),e("Expression"))).field("arguments",[e("Expression")]);e("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",e("Expression")).field("arguments",[e("Expression")]);t.finalize()},{"./types":92,"ast-types":108,estraverse:136,lodash:142}],25:[function(require,module,exports){"use strict";module.exports=function toFastProperties(obj){function f(){}f.prototype=obj;return f;eval(obj)}},{}],26:[function(n,r,l){"use strict";var t=n("./explode-assignable-expression");var e=n("../../types");r.exports=function(r,n){var l=function(e){return e.operator===n.operator+"="};var a=function(n,t){return e.assignmentExpression("=",n,t)};r.ExpressionStatement=function(o,f,u,p,c){var r=o.expression;if(!l(r))return;var i=[];var s=t(r.left,i,c,u,true);i.push(e.expressionStatement(a(s.ref,n.build(s.uid,r.right))));return i};r.AssignmentExpression=function(a,o,i,c,u){if(e.isExpressionStatement(o))return;if(!l(a))return;var r=[];var s=t(a.left,r,u,i);r.push(n.build(s.uid,a.right));r.push(s.ref);return e.toSequenceExpression(r,i)};r.BinaryExpression=function(e){if(e.operator!==n.operator)return;return n.build(e.left,e.right)}}},{"../../types":92,"./explode-assignable-expression":29}],27:[function(n,t,r){"use strict";var e=n("../../types");t.exports=function l(t,l){var r=t.blocks.shift();if(!r)return;var n=l(t,l);if(!n){n=l();if(t.filter){n=e.ifStatement(t.filter,e.blockStatement([n]))}}return e.forOfStatement(e.variableDeclaration("let",[e.variableDeclarator(r.left)]),r.right,e.blockStatement([n]))}},{"../../types":92}],28:[function(n,r,l){"use strict";var t=n("./explode-assignable-expression");var e=n("../../types");r.exports=function(r,n){var l=function(n,t){return e.assignmentExpression("=",n,t)};r.ExpressionStatement=function(o,c,u,f,r){var a=o.expression;if(!n.is(a,r))return;var i=[];var s=t(a.left,i,r,u);i.push(e.ifStatement(n.build(s.uid,r),e.expressionStatement(l(s.ref,a.right))));return i};r.AssignmentExpression=function(a,u,o,c,i){if(e.isExpressionStatement(u))return;if(!n.is(a,i))return;var r=[];var s=t(a.left,r,i,o);r.push(e.logicalExpression("&&",n.build(s.uid,i),l(s.ref,a.right)));r.push(s.ref);return e.toSequenceExpression(r,o)}}},{"../../types":92,"./explode-assignable-expression":29}],29:[function(n,t,a){"use strict";var e=n("../../types");var r=function(n,l,a,i){var t;if(e.isIdentifier(n)){t=n}else if(e.isMemberExpression(n)){t=n.object}else{throw new Error("We can't explode this node type "+n.type)}var r=i.generateUidBasedOnNode(t,a);l.push(e.variableDeclaration("var",[e.variableDeclarator(r,t)]));return r};var l=function(t,a,i,s){var n=t.property;var r=e.toComputedKey(t,n);if(e.isLiteral(r))return r;var l=s.generateUidBasedOnNode(n,i);a.push(e.variableDeclaration("var",[e.variableDeclarator(l,n)]));return l};t.exports=function(n,s,o,u,f){var t;if(e.isIdentifier(n)&&f){t=n}else{t=r(n,s,o,u)}var a,i;if(e.isIdentifier(n)){a=n;i=t}else{var c=l(n,s,o,u);var p=n.computed||e.isLiteral(c);i=a=e.memberExpression(t,c,p)}return{uid:i,ref:a}}},{"../../types":92}],30:[function(n,i,t){"use strict";var r=n("../../traverse");var l=n("../../util");var e=n("../../types");var a={enter:function(t,r,l,a,n){if(!e.isIdentifier(t,{name:n.id}))return;if(!e.isReferenced(t,r))return;var i=l.get(n.id,true);if(i!==n.outerDeclar)return;n.selfReference=true;a.stop()}};t.property=function(n,o,s){var t=e.toComputedKey(n,n.key);if(!e.isLiteral(t))return n;var i=e.toIdentifier(t.value);t=e.identifier(i);var u={id:i,selfReference:false,outerDeclar:s.get(i,true)};r(n,a,s,u);if(u.selfReference){n.value=l.template("property-method-assignment-wrapper",{FUNCTION:n.value,FUNCTION_ID:t,FUNCTION_KEY:o.generateUidIdentifier(i,s),WRAPPER_KEY:o.generateUidIdentifier(i+"Wrapper",s)})}else{n.value.id=t}}},{"../../traverse":88,"../../types":92,"../../util":94}],31:[function(n,t,l){"use strict";var r=n("../../traverse");var e=n("../../types");t.exports=function(n,a){n.async=false;n.generator=true;r(n,{enter:function(n,r,l,t){if(e.isFunction(n))t.skip();if(e.isAwaitExpression(n)){n.type="YieldExpression"}}});var t=e.callExpression(a,[n]);if(e.isFunctionDeclaration(n)){var l=e.variableDeclaration("var",[e.variableDeclarator(n.id,t)]);l._blockHoist=true;return l}else{return t}}},{"../../traverse":88,"../../types":92}],32:[function(t,r,a){"use strict";r.exports=n;var l=t("../../traverse");var e=t("../../types");function n(e,n,t,r,l){this.topLevelThisReference=null;this.methodNode=e;this.className=n;this.superName=t;this.isLoose=r;this.file=l}n.prototype.superProperty=function(n,t,r,l){return e.callExpression(this.file.addHelper("get"),[e.callExpression(e.memberExpression(e.identifier("Object"),e.identifier("getPrototypeOf")),[t?this.className:e.memberExpression(this.className,e.identifier("prototype"))]),r?n:e.literal(n.name),l])};n.prototype.looseSuperProperty=function(t,n,r){var a=t.key;var l=this.superName||e.identifier("Function");if(r.property===n){return}else if(e.isCallExpression(r,{callee:n})){r.arguments.unshift(e.thisExpression());if(a.name==="constructor"){return e.memberExpression(l,e.identifier("call"))}else{n=l;if(!t.static){n=e.memberExpression(n,e.identifier("prototype"))}n=e.memberExpression(n,a,t.computed);return e.memberExpression(n,e.identifier("call"))}}else if(e.isMemberExpression(r)&&!t.static){return e.memberExpression(l,e.identifier("prototype"))}else{return l}};n.prototype.replace=function(){this.traverseLevel(this.methodNode.value,true)};n.prototype.traverseLevel=function(t,r){var n=this;l(t,{enter:function(t,i,o,l){if(e.isFunction(t)&&!e.isArrowFunctionExpression(t)){n.traverseLevel(t,false);return l.skip()}if(e.isProperty(t,{method:true})||e.isMethodDefinition(t)){return l.skip()}var s=function(){if(r){return e.thisExpression()}else{return n.getThisReference()}};var a=n.specHandle;if(n.isLoose)a=n.looseHandle;return a.call(n,s,t,i)}})};n.prototype.getThisReference=function(){if(this.topLevelThisReference){return this.topLevelThisReference}else{var n=this.topLevelThisReference=this.file.generateUidIdentifier("this");this.methodNode.body.body.unshift(e.variableDeclaration("var",[e.variableDeclarator(this.topLevelThisReference,e.thisExpression())]));return n}};n.prototype.looseHandle=function(r,n,l){if(e.isIdentifier(n,{name:"super"})){return this.looseSuperProperty(this.methodNode,n,l)}else if(e.isCallExpression(n)){var t=n.callee;if(!e.isMemberExpression(t))return;if(t.object.name!=="super")return;e.appendToMemberExpression(t,e.identifier("call"));n.arguments.unshift(r())}};n.prototype.specHandle=function(c,n,i){var s=this.methodNode;var r;var a;var t;if(e.isIdentifier(n,{name:"super"})){if(!(e.isMemberExpression(i)&&!i.computed&&i.property===n)){throw this.file.errorWithNode(n,"illegal use of bare super")}}else if(e.isCallExpression(n)){var l=n.callee;if(e.isIdentifier(l,{name:"super"})){r=s.key;a=s.computed;t=n.arguments}else{if(!e.isMemberExpression(l))return;if(l.object.name!=="super")return;r=l.property;a=l.computed;t=n.arguments}}else if(e.isMemberExpression(n)){if(!e.isIdentifier(n.object,{name:"super"}))return;r=n.property;a=n.computed}if(!r)return;var o=c();var u=this.superProperty(r,s.static,a,o);if(t){if(t.length===1&&e.isSpreadElement(t[0])){return e.callExpression(e.memberExpression(u,e.identifier("apply")),[o,t[0].argument])}else{return e.callExpression(e.memberExpression(u,e.identifier("call")),[o].concat(t))}}else{return u}}},{"../../traverse":88,"../../types":92}],33:[function(t,r,e){"use strict";var n=t("../../types");e.has=function(t){var e=t.body[0];return n.isExpressionStatement(e)&&n.isLiteral(e.expression,{value:"use strict"})};e.wrap=function(n,r){var t;if(e.has(n)){t=n.body.shift()}r();if(t){n.body.unshift(t)}}},{"../../types":92}],34:[function(t,a,c){"use strict";a.exports=n;var r=t("../../traverse");var i=t("../../util");var e=t("../../types");var l=t("lodash");function n(e){this.file=e;this.localExports=this.getLocalExports();this.localImports=this.getLocalImports();this.remapAssignments()}var s={enter:function(n,a,i,s,r){var t=n&&n.declaration;if(e.isExportDeclaration(n)&&t&&e.isStatement(t)){l.extend(r,e.getIds(t,true))}}};n.prototype.getLocalExports=function(){var e={};r(this.file.ast,s,null,e);return e};var o={enter:function(n,r,a,i,t){if(e.isImportDeclaration(n)){l.extend(t,e.getIds(n,true))}}};n.prototype.getLocalImports=function(){var e={};r(this.file.ast,o,null,e);return e};var u={enter:function(t,a,i,s,r){if(e.isAssignmentExpression(t)){var n=t.left;if(e.isMemberExpression(n)){while(n.object)n=n.object}r(n)}else if(e.isDeclaration(t)){l.each(e.getIds(t,true),r)}}};n.prototype.checkCollisions=function(){var n=this.localImports;var t=this.file;var a=function(t){return e.isIdentifier(t)&&l.has(n,t.name)&&n[t.name]!==t};var i=function(e){if(a(e)){throw t.errorWithNode(e,"Illegal assignment of module import")}};r(t.ast,u,null,i)};n.prototype.remapExportAssignment=function(n){return e.assignmentExpression("=",n.left,e.assignmentExpression(n.operator,e.memberExpression(e.identifier("exports"),n.left),n.right))};n.prototype.remapAssignments=function(){var n=this.localExports;var t=this;var l=function(r,l){var t=r.name;return e.isIdentifier(r)&&n[t]&&n[t]===l.get(t,true)};r(this.file.ast,{enter:function(n,u,a,i,s){if(e.isUpdateExpression(n)&&s(n.argument,a)){i.skip();var c=e.assignmentExpression(n.operator[0]+"=",n.argument,e.literal(1));var o=t.remapExportAssignment(c);if(e.isExpressionStatement(u)||n.prefix){return o}var r=[];r.push(o);var l;if(n.operator==="--"){l="+"}else{l="-"}r.push(e.binaryExpression(l,n.argument,e.literal(1)));return e.sequenceExpression(r)}if(e.isAssignmentExpression(n)&&s(n.left,a)){i.skip();return t.remapExportAssignment(n)}}},null,l)};n.prototype.getModuleName=function(){var e=this.file.opts;var t=e.filenameRelative;var n="";if(e.moduleRoot){n=e.moduleRoot+"/"}if(!e.filenameRelative){return n+e.filename.replace(/^\//,"")}if(e.sourceRoot){var r=new RegExp("^"+e.sourceRoot+"/?");t=t.replace(r,"")}if(!e.keepModuleIdExtensions){t=t.replace(/\.(.*?)$/,"")}n+=t;n=n.replace(/\\/g,"/");return n};n.prototype._pushStatement=function(n,t){if(e.isClass(n)||e.isFunction(n)){if(n.id){t.push(e.toStatement(n));n=n.id}}return n};n.prototype._hoistExport=function(t,n,r){if(e.isFunctionDeclaration(t)){n._blockHoist=r||2}return n};n.prototype._exportSpecifier=function(r,n,t,l){var i=false;if(t.specifiers.length===1)i=t;if(t.source){if(e.isExportBatchSpecifier(n)){l.push(this._exportsWildcard(r(),t))}else{var a;if(e.isSpecifierDefault(n)&&!this.noInteropRequire){a=e.callExpression(this.file.addHelper("interop-require"),[r()])}else{a=e.memberExpression(r(),n.id)}l.push(this._exportsAssign(e.getSpecifierName(n),a,t))}}else{l.push(this._exportsAssign(e.getSpecifierName(n),n.id,t))}};n.prototype._exportsWildcard=function(n){return e.expressionStatement(e.callExpression(this.file.addHelper("defaults"),[e.identifier("exports"),e.callExpression(this.file.addHelper("interop-require-wildcard"),[n])]))};n.prototype._exportsAssign=function(e,n){return i.template("exports-assign",{VALUE:n,KEY:e},true)};n.prototype.exportDeclaration=function(t,a){var n=t.declaration;var s=n.id;if(t.default){s=e.identifier("default")}var i;if(e.isVariableDeclaration(n)){for(var r=0;r<n.declarations.length;r++){var l=n.declarations[r];l.init=this._exportsAssign(l.id,l.init,t).expression;var o=e.variableDeclaration(n.kind,[l]);if(r===0)e.inherits(o,n);a.push(o)}}else{var u=n;if(e.isFunctionDeclaration(n)||e.isClassDeclaration(n)){u=n.id;a.push(n)}i=this._exportsAssign(s,u,t);a.push(i);this._hoistExport(n,i)}}},{"../../traverse":88,"../../types":92,"../../util":94,lodash:142}],35:[function(e,n,r){"use strict";var t=e("../../util");n.exports=function(e){var n=function(){this.noInteropExport=true;e.apply(this,arguments)};t.inherits(n,e);return n}},{"../../util":94}],36:[function(e,n,t){"use strict";n.exports=e("./_strict")(e("./amd"))},{"./_strict":35,"./amd":37}],37:[function(t,a,o){"use strict";a.exports=n;var r=t("./_default");var l=t("./common");var i=t("../../util");var e=t("../../types");var s=t("lodash");function n(){l.apply(this,arguments);this.ids={}}i.inherits(n,r);n.prototype.buildDependencyLiterals=function(){var n=[];for(var t in this.ids){n.push(e.literal(t))}return n};n.prototype.transform=function(i){var r=i.program;
var o=r.body;var n=[e.literal("exports")];if(this.passModuleArg)n.push(e.literal("module"));n=n.concat(this.buildDependencyLiterals());n=e.arrayExpression(n);var t=s.values(this.ids);if(this.passModuleArg)t.unshift(e.identifier("module"));t.unshift(e.identifier("exports"));var u=e.functionExpression(null,t,e.blockStatement(o));var l=[n,u];var a=this.getModuleName();if(a)l.unshift(e.literal(a));var c=e.callExpression(e.identifier("define"),l);r.body=[e.expressionStatement(c)]};n.prototype.getModuleName=function(){if(this.file.opts.moduleIds){return r.prototype.getModuleName.apply(this,arguments)}else{return null}};n.prototype._push=function(t){var e=t.source.value;var n=this.ids;if(n[e]){return n[e]}else{return this.ids[e]=this.file.generateUidIdentifier(e)}};n.prototype.importDeclaration=function(e){this._push(e)};n.prototype.importSpecifier=function(t,r,l){var a=e.getSpecifierName(t);var n=this._push(r);if(e.isImportBatchSpecifier(t)){}else if(e.isSpecifierDefault(t)&&!this.noInteropRequire){n=e.callExpression(this.file.addHelper("interop-require"),[n])}else{n=e.memberExpression(n,t.id,false)}l.push(e.variableDeclaration("var",[e.variableDeclarator(a,n)]))};n.prototype.exportDeclaration=function(e){if(e.default&&!this.noInteropExport){this.passModuleArg=true}l.prototype.exportDeclaration.apply(this,arguments)};n.prototype.exportSpecifier=function(n,e,t){var r=this;return this._exportSpecifier(function(){return r._push(e)},n,e,t)}},{"../../types":92,"../../util":94,"./_default":34,"./common":39,lodash:142}],38:[function(e,n,t){"use strict";n.exports=e("./_strict")(e("./common"))},{"./_strict":35,"./common":39}],39:[function(r,a,s){"use strict";a.exports=t;var l=r("./_default");var i=r("../../traverse");var n=r("../../util");var e=r("../../types");function t(t){l.apply(this,arguments);var n=false;i(t.ast,{enter:function(t){if(e.isExportDeclaration(t)&&!t.default)n=true}});this.hasNonDefaultExports=n}n.inherits(t,l);t.prototype.importSpecifier=function(t,r,l){var a=e.getSpecifierName(t);if(e.isSpecifierDefault(t)){l.push(e.variableDeclaration("var",[e.variableDeclarator(a,e.callExpression(this.file.addHelper("interop-require"),[n.template("require",{MODULE_NAME:r.source})]))]))}else{if(t.type==="ImportBatchSpecifier"){l.push(e.variableDeclaration("var",[e.variableDeclarator(a,e.callExpression(this.file.addHelper("interop-require-wildcard"),[e.callExpression(e.identifier("require"),[r.source])]))]))}else{l.push(n.template("require-assign-key",{VARIABLE_NAME:a,MODULE_NAME:r.source,KEY:t.id}))}}};t.prototype.importDeclaration=function(e,t){t.push(n.template("require",{MODULE_NAME:e.source},true))};t.prototype.exportDeclaration=function(i,r){if(i.default&&!this.noInteropRequire&&!this.noInteropExport){var a=i.declaration;var t;var s="exports-default-module";if(this.hasNonDefaultExports)s="exports-default-module-override";if(e.isFunctionDeclaration(a)||!this.hasNonDefaultExports){t=n.template(s,{VALUE:this._pushStatement(a,r)},true);r.push(this._hoistExport(a,t,3));return}else{t=n.template("common-export-default-assign",{EXTENDS_HELPER:this.file.addHelper("extends")},true);t._blockHoist=0;r.push(t)}}l.prototype.exportDeclaration.apply(this,arguments)};t.prototype.exportSpecifier=function(t,n,r){this._exportSpecifier(function(){return e.callExpression(e.identifier("require"),[n.source])},t,n,r)}},{"../../traverse":88,"../../types":92,"../../util":94,"./_default":34}],40:[function(t,r,l){"use strict";r.exports=e;var n=t("../../types");function e(){}e.prototype.exportDeclaration=function(e,r){var t=n.toStatement(e.declaration,true);if(t)r.push(n.inherits(t,e))};e.prototype.importDeclaration=e.prototype.importSpecifier=e.prototype.exportSpecifier=function(){}},{"../../types":92}],41:[function(t,s,u){"use strict";s.exports=n;var l=t("./amd");var o=t("../helpers/use-strict");var a=t("../../traverse");var i=t("../../util");var e=t("../../types");var r=t("lodash");function n(e){this.exportIdentifier=e.generateUidIdentifier("export");this.noInteropRequire=true;l.apply(this,arguments)}i.inherits(n,l);n.prototype._addImportSource=function(e,n){e._importSource=n.source&&n.source.value;return e};n.prototype._exportsWildcard=function(t,r){var n=this.file.generateUidIdentifier("key");var l=e.memberExpression(t,n,true);var a=e.variableDeclaration("var",[e.variableDeclarator(n)]);var i=t;var s=e.blockStatement([e.expressionStatement(this.buildExportCall(n,l))]);return this._addImportSource(e.forInStatement(a,i,s),r)};n.prototype._exportsAssign=function(n,t,r){var l=this.buildExportCall(e.literal(n.name),t,true);return this._addImportSource(l,r)};n.prototype.remapExportAssignment=function(n){return this.buildExportCall(e.literal(n.left.name),n)};n.prototype.buildExportCall=function(t,r,l){var n=e.callExpression(this.exportIdentifier,[t,r]);if(l){return e.expressionStatement(n)}else{return n}};n.prototype.importSpecifier=function(t,e,n){l.prototype.importSpecifier.apply(this,arguments);this._addImportSource(r.last(n),e)};n.prototype.buildRunnerSetters=function(n,t){return e.arrayExpression(r.map(this.ids,function(i,s){var l={nodes:[],hoistDeclarators:t};a(n,{enter:function(n,a,i,l,t){if(n._importSource===s){if(e.isVariableDeclaration(n)){r.each(n.declarations,function(n){t.hoistDeclarators.push(e.variableDeclarator(n.id));t.nodes.push(e.expressionStatement(e.assignmentExpression("=",n.id,n.init)))})}else{t.nodes.push(n)}l.remove()}}},null,l);return e.functionExpression(null,[i],e.blockStatement(l.nodes))}))};n.prototype.transform=function(p){var u=p.program;var l=[];var c=this.getModuleName();var d=e.literal(c);var n=e.blockStatement(u.body);var s=i.template("system",{MODULE_NAME:d,MODULE_DEPENDENCIES:e.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(n,l),EXECUTE:e.functionExpression(null,[],n)},true);var t=s.expression.arguments[2].body.body;if(!c)s.expression.arguments.shift();var m=t.pop();a(n,{enter:function(n,t,a,i,s){if(e.isFunction(n)){return i.skip()}if(e.isVariableDeclaration(n)){if(n.kind!=="var"&&!e.isProgram(t)){return}var l=[];r.each(n.declarations,function(n){s.push(e.variableDeclarator(n.id));if(n.init){var t=e.expressionStatement(e.assignmentExpression("=",n.id,n.init));l.push(t)}});if(e.isFor(t)){if(t.left===n){return n.declarations[0].id}if(t.init===n){return e.toSequenceExpression(l,a)}}return l}}},null,l);if(l.length){var f=e.variableDeclaration("var",l);f._blockHoist=true;t.unshift(f)}a(n,{enter:function(n,l,a,t,r){if(e.isFunction(n))t.skip();if(e.isFunctionDeclaration(n)||n._blockHoist){r.push(n);t.remove()}}},null,t);t.push(m);if(o.has(n)){t.unshift(n.body.shift())}u.body=[s]}},{"../../traverse":88,"../../types":92,"../../util":94,"../helpers/use-strict":33,"./amd":37,lodash:142}],42:[function(e,n,t){"use strict";n.exports=e("./_strict")(e("./umd"))},{"./_strict":35,"./umd":43}],43:[function(n,a,s){"use strict";a.exports=r;var l=n("./amd");var t=n("../../util");var e=n("../../types");var i=n("lodash");function r(){l.apply(this,arguments)}t.inherits(r,l);r.prototype.transform=function(f){var s=f.program;var g=s.body;var a=[];for(var p in this.ids){a.push(e.literal(p))}var h=i.values(this.ids);var r=[e.identifier("exports")];if(this.passModuleArg)r.push(e.identifier("module"));r=r.concat(h);var c=e.functionExpression(null,r,e.blockStatement(g));var n=[e.literal("exports")];if(this.passModuleArg)n.push(e.literal("module"));n=n.concat(a);n=[e.arrayExpression(n)];var o=t.template("test-exports");var d=t.template("test-module");var m=this.passModuleArg?e.logicalExpression("&&",o,d):o;var l=[e.identifier("exports")];if(this.passModuleArg)l.push(e.identifier("module"));l=l.concat(a.map(function(n){return e.callExpression(e.identifier("require"),[n])}));var u=this.getModuleName();if(u)n.unshift(e.literal(u));var y=t.template("umd-runner-body",{AMD_ARGUMENTS:n,COMMON_TEST:m,COMMON_ARGUMENTS:l});var v=e.callExpression(y,[c]);s.body=[e.expressionStatement(v)]}},{"../../types":92,"../../util":94,"./amd":37,lodash:142}],44:[function(e,l,s){"use strict";l.exports=n;var a=e("./transformer");var t=e("../file");var i=e("../util");var r=e("lodash");function n(e,n){var r=new t(n);return r.parse(e)}n.fromAst=function(e,r,l){e=i.normaliseAst(e);var n=new t(l);n.addCode(r);n.transform(e);return n.generate()};n._ensureTransformerNames=function(a,t){for(var e=0;e<t.length;e++){var l=t[e];if(!r.has(n.transformers,l)){throw new ReferenceError("unknown transformer "+l+" specified in "+a)}}};n.transformers={};n.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")};r.each({specNoForInOfAssignment:e("./transformers/spec-no-for-in-of-assignment"),specSetters:e("./transformers/spec-setters"),specBlockScopedFunctions:e("./transformers/spec-block-scoped-functions"),malletOperator:e("./transformers/playground-mallet-operator"),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(t,e){n.transformers[e]=new a(e,t)})},{"../file":3,"../util":94,"./modules/amd":37,"./modules/amd-strict":36,"./modules/common":39,"./modules/common-strict":38,"./modules/ignore":40,"./modules/system":41,"./modules/umd":43,"./modules/umd-strict":42,"./transformer":45,"./transformers/_alias-functions":46,"./transformers/_block-hoist":47,"./transformers/_declarations":48,"./transformers/_module-formatter":49,"./transformers/es6-arrow-functions":50,"./transformers/es6-classes":51,"./transformers/es6-computed-property-names":52,"./transformers/es6-constants":53,"./transformers/es6-default-parameters":54,"./transformers/es6-destructuring":55,"./transformers/es6-for-of":56,"./transformers/es6-generators":57,"./transformers/es6-let-scoping":58,"./transformers/es6-modules":59,"./transformers/es6-property-method-assignment":60,"./transformers/es6-property-name-shorthand":61,"./transformers/es6-rest-parameters":62,"./transformers/es6-spread":63,"./transformers/es6-template-literals":64,"./transformers/es6-unicode-regex":65,"./transformers/es7-abstract-references":66,"./transformers/es7-array-comprehension":67,"./transformers/es7-exponentiation-operator":68,"./transformers/es7-generator-comprehension":69,"./transformers/es7-object-spread":70,"./transformers/optional-async-to-generator":71,"./transformers/optional-bluebird-coroutines":72,"./transformers/optional-core-aliasing":73,"./transformers/optional-proto-to-assign":74,"./transformers/optional-typeof-symbol":75,"./transformers/optional-undefined-to-void":76,"./transformers/playground-mallet-operator":77,"./transformers/playground-memoization-operator":78,"./transformers/playground-method-binding":79,"./transformers/playground-object-getter-memoization":80,"./transformers/react":81,"./transformers/spec-block-scoped-functions":82,"./transformers/spec-member-expression-literals":83,"./transformers/spec-no-for-in-of-assignment":84,"./transformers/spec-property-literals":85,"./transformers/spec-setters":86,"./transformers/use-strict":87,lodash:142}],45:[function(t,i,c){"use strict";i.exports=n;var l=t("../traverse");var a=t("../types");var e=t("lodash");function r(){}function s(e,r,l,a,n){var t=n[1][e.type];if(!t)return;return t.enter(e,r,l,a,n[0])}function o(e,r,l,a,n){var t=n[1][e.type];if(!t)return;return t.exit(e,r,l,a,n[0])}var u={enter:s,exit:o};function n(n,e,t){this.manipulateOptions=e.manipulateOptions;this.experimental=!!e.experimental;this.secondPass=!!e.secondPass;this.transformer=this.normalise(e);this.optional=!!e.optional;this.opts=t||{};this.key=n}n.prototype.normalise=function(n){var t=this;if(e.isFunction(n)){n={ast:n}}e.each(n,function(l,i){if(i[0]==="_"){t[i]=l;return}if(e.isFunction(l))l={enter:l};if(!e.isObject(l))return;if(!l.enter)l.enter=r;if(!l.exit)l.exit=r;n[i]=l;var s=a.FLIPPED_ALIAS_KEYS[i];if(s){e.each(s,function(e){n[e]=l})}});return n};n.prototype.astRun=function(n,t){var e=this.transformer;if(e.ast&&e.ast[t]){e.ast[t](n.ast,n)}};n.prototype.transform=function(e){this.astRun(e,"before");l(e.ast,u,null,[e,this.transformer]);this.astRun(e,"after")};n.prototype.canRun=function(a){var n=a.opts;var t=this.key;if(t[0]==="_")return true;var r=n.blacklist;if(r.length&&e.contains(r,t))return false;var l=n.whitelist;if(l.length&&!e.contains(l,t))return false;if(this.optional&&!e.contains(n.optional,t))return false;if(this.experimental&&!n.experimental)return false;return true}},{"../traverse":88,"../types":92,lodash:142}],46:[function(t,s,n){"use strict";var r=t("../../traverse");var e=t("../../types");var a={enter:function(n,a,i,r,l){if(e.isFunction(n)&&!n._aliasFunction){return r.skip()}if(n._ignoreAliasFunctions)return r.skip();var t;if(e.isIdentifier(n)&&n.name==="arguments"){t=l.getArgumentsId}else if(e.isThisExpression(n)){t=l.getThisId}else{return}if(e.isReferenced(n,a))return t()}};var i={enter:function(n,i,s,t,l){if(!n._aliasFunction){if(e.isFunction(n)){return t.skip()}else{return}}r(n,a,null,l);return t.skip()}};var l=function(u,c,a,s){var n;var t;var f={getArgumentsId:function(){return n=n||a.generateUidIdentifier("arguments",s)},getThisId:function(){return t=t||a.generateUidIdentifier("this",s)}};r(c,i,null,f);var l;var o=function(n,t){l=l||u();l.unshift(e.variableDeclaration("var",[e.variableDeclarator(n,t)]))};if(n){o(n,e.identifier("arguments"))}if(t){o(t,e.thisExpression())}};n.Program=function(e,r,n,a,t){l(function(){return e.body},e,t,n)};n.FunctionDeclaration=n.FunctionExpression=function(n,a,t,i,r){l(function(){e.ensureBlock(n);return n.body.body},n,r,t)}},{"../../traverse":88,"../../types":92}],47:[function(n,l,t){"use strict";var r=n("../helpers/use-strict");var e=n("lodash");t.BlockStatement=t.Program={exit:function(n){var l=false;for(var t=0;t<n.body.length;t++){var a=n.body[t];if(a&&a._blockHoist!=null)l=true}if(!l)return;r.wrap(n,function(){var t=e.groupBy(n.body,function(n){var e=n._blockHoist;if(e==null)e=1;if(e===true)e=2;return e});n.body=e.flatten(e.values(t).reverse())})}}},{"../helpers/use-strict":33,lodash:142}],48:[function(t,l,e){"use strict";var r=t("../helpers/use-strict");var n=t("../../types");e.secondPass=true;e.BlockStatement=e.Program=function(t){if(!t._declarations)return;var l={};var e;r.wrap(t,function(){for(var i in t._declarations){var r=t._declarations[i];e=r.kind||"var";var a=n.variableDeclarator(r.id,r.init);if(!r.init){l[e]=l[e]||[];l[e].push(a)}else{t.body.unshift(n.variableDeclaration(e,[a]))}}for(e in l){t.body.unshift(n.variableDeclaration(e,l[e]))}});t._declarations=null}},{"../../types":92,"../helpers/use-strict":33}],49:[function(e,r,n){"use strict";var t=e("../transform");n.ast={exit:function(n,e){if(!t.transformers.modules.canRun(e))return;if(e.moduleFormatter.transform){e.moduleFormatter.transform(n)}}}},{"../transform":44}],50:[function(e,r,n){"use strict";var t=e("../../types");n.ArrowFunctionExpression=function(e){t.ensureBlock(e);e._aliasFunction="arrow";e.expression=false;e.type="FunctionExpression";return e}},{"../../types":92}],51:[function(t,s,l){"use strict";var a=t("../helpers/replace-supers");var i=t("../helpers/name-method");var r=t("../../util");var e=t("../../types");l.ClassDeclaration=function(e,l,t,a,r){return new n(e,r,t,true).run()};l.ClassExpression=function(r,t,l,i,a){if(!r.id){if(e.isProperty(t)&&t.value===r&&!t.computed&&e.isIdentifier(t.key)){r.id=t.key}if(e.isVariableDeclarator(t)&&e.isIdentifier(t.id)){r.id=t.id}}return new n(r,a,l,false).run()};function n(e,n,t,r){this.isStatement=r;this.scope=t;this.node=e;this.file=n;this.hasInstanceMutators=false;this.hasStaticMutators=false;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=e.id||n.generateUidIdentifier("class",t);this.superName=e.superClass;this.isLoose=n.isLoose("classes")}n.prototype.run=function(){var n=this.superName;var l=this.className;var o=this.file;var t=this.body=[];var r;if(this.node.id){r=e.functionDeclaration(l,[],e.blockStatement([]));t.push(r)}else{r=e.functionExpression(null,[],e.blockStatement([]));t.push(e.variableDeclaration("var",[e.variableDeclarator(l,r)]))}this.constructor=r;var i=[];var s=[];if(n){s.push(n);if(!e.isIdentifier(n)){var u=this.scope.generateUidBasedOnNode(n,this.file);n=u}i.push(n);this.superName=n;t.push(e.expressionStatement(e.callExpression(o.addHelper("inherits"),[l,n])))}this.buildBody();e.inheritsComments(t[0],this.node);var a;if(t.length===1){a=e.toExpression(r)}else{t.push(e.returnStatement(l));a=e.callExpression(e.functionExpression(null,i,e.blockStatement(t)),s)}if(this.isStatement){return e.variableDeclaration("let",[e.variableDeclarator(l,a)])}else{return a}};n.prototype.buildBody=function(){var m=this.constructor;var u=this.className;var c=this.superName;var p=this.node.body.body;var s=this.body;for(var i=0;i<p.length;i++){var n=p[i];if(e.isMethodDefinition(n)){var d=new a(n,this.className,this.superName,this.isLoose,this.file);d.replace();if(n.key.name==="constructor"){this.pushConstructor(n)}else{this.pushMethod(n)}}else if(e.isPrivateDeclaration(n)){this.closure=true;s.unshift(n)}}if(!this.hasConstructor&&c&&!e.isFalsyExpression(c)){var f="class-super-constructor-call";if(this.isLoose)f+="-loose";m.body.body.push(r.template(f,{CLASS_NAME:u,SUPER_NAME:this.superName},true))}var l;var t;if(this.hasInstanceMutators){l=r.buildDefineProperties(this.instanceMutatorMap)}if(this.hasStaticMutators){t=r.buildDefineProperties(this.staticMutatorMap)}if(l||t){t=t||e.literal(null);var o=[u,t];if(l)o.push(l);s.push(e.expressionStatement(e.callExpression(this.file.addHelper("prototype-properties"),o)))}};n.prototype.pushMethod=function(n){var t=n.key;var l=n.kind;if(l===""){i.property(n,this.file,this.scope);if(this.isLoose){var a=this.className;if(!n.static)a=e.memberExpression(a,e.identifier("prototype"));t=e.memberExpression(a,t,n.computed);var s=e.expressionStatement(e.assignmentExpression("=",t,n.value));e.inheritsComments(s,n);this.body.push(s);return}l="value"}var o=this.instanceMutatorMap;if(n.static){this.hasStaticMutators=true;o=this.staticMutatorMap}else{this.hasInstanceMutators=true}r.pushMutatorMap(o,t,l,n.computed,n)};n.prototype.pushConstructor=function(r){if(r.kind){throw this.file.errorWithNode(r,"illegal kind for constructor method")}var n=this.constructor;var t=r.value;this.hasConstructor=true;e.inherits(n,t);e.inheritsComments(n,r);n._ignoreUserWhitespace=true;n.defaults=t.defaults;n.params=t.params;n.body=t.body;n.rest=t.rest}},{"../../types":92,"../../util":94,"../helpers/name-method":30,"../helpers/replace-supers":32}],52:[function(n,a,t){"use strict";var e=n("../../types");t.ObjectExpression=function(a,d,m,h,s){var o=false;for(var t=0;t<a.properties.length;t++){o=e.isProperty(a.properties[t],{computed:true,kind:"init"});if(o)break}if(!o)return;var u=[];var i=m.generateUidBasedOnNode(d,s);var n=[];var c=e.functionExpression(null,[],e.blockStatement(n));c._aliasFunction=true;var f=l;if(s.isLoose("computedPropertyNames"))f=r;var p=f(a,n,i,u,s);if(p)return p;n.unshift(e.variableDeclaration("var",[e.variableDeclarator(i,e.objectExpression(u))]));n.push(e.returnStatement(i));return e.callExpression(c,[])};var r=function(r,l,a){for(var n=0;n<r.properties.length;n++){var t=r.properties[n];l.push(e.expressionStatement(e.assignmentExpression("=",e.memberExpression(a,t.key,t.computed),t.value)))}};var l=function(p,s,c,o,f){var l=p.properties;var n,r;for(var t=0;t<l.length;t++){n=l[t];if(n.kind!=="init")continue;r=n.key;if(!n.computed&&e.isIdentifier(r)){n.key=e.literal(r.name)}}var u=false;for(t=0;t<l.length;t++){n=l[t];if(n.computed){u=true}if(n.kind!=="init"||!u||e.isLiteral(e.toComputedKey(n,n.key),{value:"__proto__"})){o.push(n);l[t]=null}}for(t=0;t<l.length;t++){n=l[t];if(!n)continue;r=n.key;var a;if(n.computed&&e.isMemberExpression(r)&&e.isIdentifier(r.object,{name:"Symbol"})){a=e.assignmentExpression("=",e.memberExpression(c,r,true),n.value)}else{a=e.callExpression(f.addHelper("define-property"),[c,r,n.value])}s.push(e.expressionStatement(a))}if(s.length===1){var i=s[0].expression;if(e.isCallExpression(i)){i.arguments[0]=e.objectExpression(o);return i}}}},{"../../types":92}],53:[function(t,a,n){"use strict";var l=t("../../traverse");var e=t("../../types");var r=t("lodash");n.Program=n.BlockStatement=n.ForInStatement=n.ForOfStatement=n.ForStatement=function(t,c,f,p,o){var a=false;var n={};var i=function(l,a,i){for(var t in a){var s=a[t];if(!r.has(n,t))continue;if(l&&e.isBlockStatement(l)&&l!==n[t])continue;if(i){var u=i.get(t);if(u&&u===s)continue}throw o.errorWithNode(s,t+" is read-only")}};var s=function(n){return e.getIds(n,true,["MemberExpression"])};r.each(t.body,function(t,o){if(e.isExportDeclaration(t)){t=t.declaration}if(e.isVariableDeclaration(t,{kind:"const"})){for(var r=0;r<t.declarations.length;r++){var u=t.declarations[r];var c=s(u);for(var l in c){var p=c[l];var f={};f[l]=p;i(o,f);n[l]=o;a=true}u._ignoreConstant=true}t._ignoreConstant=true;t.kind="let"}});if(!a)return;var u={check:i,getIds:s};l(t,{enter:function(n,r,l,a,t){if(n._ignoreConstant)return;if(e.isVariableDeclaration(n))return;if(e.isVariableDeclarator(n)||e.isDeclaration(n)||e.isAssignmentExpression(n)){t.check(r,t.getIds(n),l)}}},null,u)}},{"../../traverse":88,"../../types":92,lodash:142}],54:[function(n,a,t){"use strict";var r=n("../../traverse");var l=n("../../util");var e=n("../../types");t.Function=function(n,b,u,x,y){if(!n.defaults||!n.defaults.length)return;e.ensureBlock(n);var g=n.params.map(function(n){return e.getIds(n)});var s=false;var a;var h=function(l){var t=function(n,t){if(!e.isIdentifier(n)||!e.isReferenced(n,t))return;if(l.indexOf(n.name)>=0){throw y.errorWithNode(n,"Temporal dead zone - accessing a variable before it's initialized")}if(u.has(n.name,true)){s=true}};t(a,n);r(a,{enter:t})};for(var t=0;t<n.defaults.length;t++){a=n.defaults[t];if(!a)continue;var v=n.params[t];var m=g.slice(t);for(var o=0;o<m.length;o++){h(m[o])}var p=u.get(v.name,true);if(p&&n.params.indexOf(p)<0){s=true}}var i=[];var f=e.identifier("arguments");f._ignoreAliasFunctions=true;var c=0;for(t=0;t<n.defaults.length;t++){a=n.defaults[t];if(!a){c=+t+1;continue}i.push(l.template("default-parameter",{VARIABLE_NAME:n.params[t],DEFAULT_VALUE:a,ARGUMENT_KEY:e.literal(+t),ARGUMENTS:f},true))}n.params=n.params.slice(0,c);if(s){var d=e.functionExpression(null,[],n.body,n.generator);d._aliasFunction=true;i.push(e.returnStatement(e.callExpression(d,[])));n.body=e.blockStatement(i)}else{n.body.body=i.concat(n.body.body)}n.defaults=[]}},{"../../traverse":88,"../../types":92,"../../util":94}],55:[function(a,u,n){"use strict";var e=a("../../types");var r=function(r,n,l){var t=r.operator;if(e.isMemberExpression(n))t="=";if(t){return e.expressionStatement(e.assignmentExpression(t,n,l))}else{return e.variableDeclaration(r.kind,[e.variableDeclarator(n,l)])}};var t=function(t,l,n,a){if(e.isObjectPattern(n)){s(t,l,n,a)}else if(e.isArrayPattern(n)){o(t,l,n,a)}else if(e.isAssignmentPattern(n)){i(t,l,n,a)}else{l.push(r(t,n,a))}};var i=function(n,l,a,i){var t=n.scope.generateUidBasedOnNode(i,n.file);l.push(e.variableDeclaration("var",[e.variableDeclarator(t,i)]));l.push(r(n,a.left,e.conditionalExpression(e.binaryExpression("===",t,e.identifier("undefined")),a.right,t)))};var s=function(o,u,a,d){for(var s=0;s<a.properties.length;s++){var n=a.properties[s];if(e.isSpreadProperty(n)){var l=[];for(var i=0;i<a.properties.length;i++){var c=a.properties[i];if(i>=s)break;if(e.isSpreadProperty(c))continue;var f=c.key;if(e.isIdentifier(f)){f=e.literal(c.key.name)}l.push(f)}l=e.arrayExpression(l);var h=e.callExpression(o.file.addHelper("object-without-properties"),[d,l]);u.push(r(o,n.argument,h))}else{if(e.isLiteral(n.key))n.computed=true;var p=n.value;var m=e.memberExpression(d,n.key,n.computed);if(e.isPattern(p)){t(o,u,p,m)}else{u.push(r(o,p,m))}}}};var o=function(l,o,r,a){if(!r.elements)return;var n;var u=false;for(n=0;n<r.elements.length;n++){if(e.isSpreadElement(r.elements[n])){u=true;break}}var f=l.file.toArray(a,!u&&r.elements.length);var c=l.scope.generateUidBasedOnNode(a,l.file);o.push(e.variableDeclaration("var",[e.variableDeclarator(c,f)]));a=c;for(n=0;n<r.elements.length;n++){var i=r.elements[n];if(!i)continue;n=+n;var s;if(e.isSpreadElement(i)){s=l.file.toArray(a);if(n>0){s=e.callExpression(e.memberExpression(s,e.identifier("slice")),[e.literal(n)])}i=i.argument}else{s=e.memberExpression(a,e.literal(n),true)}t(l,o,i,s)}};var l=function(r){var l=r.nodes;var i=r.pattern;var n=r.id;var s=r.file;var o=r.scope;if(!e.isArrayExpression(n)&&!e.isMemberExpression(n)&&!e.isIdentifier(n)){var a=o.generateUidBasedOnNode(n,s);l.push(e.variableDeclaration("var",[e.variableDeclarator(a,n)]));n=a}t(r,l,i,n)};n.ForInStatement=n.ForOfStatement=function(n,c,l,f,a){var r=n.left;if(!e.isVariableDeclaration(r))return;var i=r.declarations[0].id;if(!e.isPattern(i))return;var s=a.generateUidIdentifier("ref",l);n.left=e.variableDeclaration(r.kind,[e.variableDeclarator(s,null)]);var o=[];t({kind:r.kind,file:a,scope:l},o,i,s);e.ensureBlock(n);var u=n.body;u.body=o.concat(u.body)};n.Function=function(n,o,t,u,r){var a=[];var i=false;n.params=n.params.map(function(n){if(!e.isPattern(n))return n;i=true;var s=r.generateUidIdentifier("ref",t);l({kind:"var",nodes:a,pattern:n,id:s,file:r,scope:t});return s});if(!i)return;e.ensureBlock(n);var s=n.body;s.body=a.concat(s.body)};n.CatchClause=function(n,o,r,u,l){var a=n.param;if(!e.isPattern(a))return;var i=l.generateUidIdentifier("ref",r);n.param=i;var s=[];t({kind:"var",file:l,scope:r},s,a,i);n.body.body=s.concat(n.body.body)};n.ExpressionStatement=function(s,o,l,u,a){var n=s.expression;if(n.type!=="AssignmentExpression")return;if(!e.isPattern(n.left))return;var r=[];var i=a.generateUidIdentifier("ref",l);r.push(e.variableDeclaration("var",[e.variableDeclarator(i,n.right)]));t({operator:n.operator,file:a,scope:l},r,n.left,i);return r};n.AssignmentExpression=function(r,s,l,o,i){if(s.type==="ExpressionStatement")return;if(!e.isPattern(r.left))return;var n=i.generateUidIdentifier("temp",l);l.push({key:n.name,id:n});var a=[];a.push(e.assignmentExpression("=",n,r.right));t({operator:r.operator,file:i,scope:l},a,r.left,n);a.push(n);return e.toSequenceExpression(a,l)};n.VariableDeclaration=function(a,s,d,m,o){if(e.isForInStatement(s)||e.isForOfStatement(s))return;var i=[];var t;var n;var u=false;for(t=0;t<a.declarations.length;t++){n=a.declarations[t];if(e.isPattern(n.id)){u=true;break}}if(!u)return;for(t=0;t<a.declarations.length;t++){n=a.declarations[t];var c=n.init;var f=n.id;var p={kind:a.kind,nodes:i,pattern:f,id:c,file:o,scope:d};if(e.isPattern(f)&&c){l(p);if(+t!==a.declarations.length-1){e.inherits(i[i.length-1],n)}}else{i.push(e.inherits(r(p,n.id,n.init),n))}}if(!e.isProgram(s)&&!e.isBlockStatement(s)){n=null;for(t=0;t<i.length;t++){a=i[t];n=n||e.variableDeclaration(a.kind,[]);if(!e.isVariableDeclaration(a)&&n.kind!==a.kind){throw o.errorWithNode(a,"Cannot use this node within the current parent")}n.declarations=n.declarations.concat(a.declarations)}return n}return i}},{"../../types":92}],56:[function(n,i,r){"use strict";var t=n("../../util");var e=n("../../types");r.ForOfStatement=function(n,c,f,p,o){var u=a;if(o.isLoose("forOf"))u=l;var r=u(n,c,f,p,o);var i=r.declar;var s=r.loop;var t=s.body;e.inheritsComments(s,n);e.ensureBlock(n);if(i){if(r.shouldUnshift){t.body.unshift(i)}else{t.body.push(i)}}t.body=t.body.concat(n.body.body);return s};var l=function(i,u,a,c,r){var n=i.left;var s,l;if(e.isIdentifier(n)||e.isPattern(n)){l=n}else if(e.isVariableDeclaration(n)){l=n.declarations[0].id;s=e.variableDeclaration(n.kind,[e.variableDeclarator(l)])}else{throw r.errorWithNode(n,"Unknown node type "+n.type+" in ForOfStatement")}var o=t.template("for-of-loose",{LOOP_OBJECT:r.generateUidIdentifier("iterator",a),IS_ARRAY:r.generateUidIdentifier("isArray",a),OBJECT:i.right,INDEX:r.generateUidIdentifier("i",a),ID:l});return{shouldUnshift:true,declar:s,loop:o}};var a=function(a,c,i,f,r){var n=a.left;var l;var s=r.generateUidIdentifier("step",i);var o=e.memberExpression(s,e.identifier("value"));if(e.isIdentifier(n)||e.isPattern(n)){l=e.expressionStatement(e.assignmentExpression("=",n,o))}else if(e.isVariableDeclaration(n)){l=e.variableDeclaration(n.kind,[e.variableDeclarator(n.declarations[0].id,o)])}else{throw r.errorWithNode(n,"Unknown node type "+n.type+" in ForOfStatement")}var u=t.template("for-of",{ITERATOR_KEY:r.generateUidIdentifier("iterator",i),STEP_KEY:s,OBJECT:a.right});return{declar:l,loop:u}}},{"../../types":92,"../../util":94}],57:[function(e,r,n){"use strict";var t=e("regenerator");n.ast={before:function(e,n){t.transform(e,{includeRuntime:n.opts.includeRegenerator&&"if used"})}}},{regenerator:150}],58:[function(i,c,r){"use strict";var t=i("../../traverse");var o=i("../../util");var e=i("../../types");var l=i("lodash");var a=function(n,t){if(!e.isVariableDeclaration(n))return false;if(n._let)return true;if(n.kind!=="let")return false;if(!e.isFor(t)||e.isFor(t)&&t.left!==n){l.each(n.declarations,function(n){n.init=n.init||e.identifier("undefined")})}n._let=true;n.kind="var";return true};var s=function(n,t){return e.isVariableDeclaration(n,{kind:"var"})&&!a(n,t)};var u=function(n){for(var e=0;e<n.length;e++){delete n[e]._let}};r.VariableDeclaration=function(e,n){a(e,n)};r.Loop=function(t,r,i,u,s){var l=t.left||t.init;if(a(l,t)){e.ensureBlock(t);t.body._letDeclars=[l]}if(e.isLabeledStatement(r)){t.label=r.label}var o=new n(t,t.body,r,i,s);o.run();if(t.label&&!e.isLabeledStatement(r)){return e.labeledStatement(t.label,t)}};r.Program=r.BlockStatement=function(r,t,l,s,a){if(!e.isLoop(t)){var i=new n(false,r,t,l,a);i.run()}};function n(e,n,t,r,l){this.loopParent=e;this.parent=t;this.scope=r;this.block=n;this.file=l;this.outsideLetReferences={};this.hasLetReferences=false;this.letReferences={};this.body=[]}n.prototype.run=function(){var n=this.block;
if(n._letDone)return;n._letDone=true;var t=this.getLetReferences();this.checkTDZ();if(e.isFunction(this.parent)||e.isProgram(this.block))return;if(!this.hasLetReferences)return;if(t){this.needsClosure()}else{this.remap()}};n.prototype.checkTDZ=function(){var n={letRefs:this.letReferences,file:this.file};t(this.block,{enter:function(n,s,o,u,a){if(!e.isIdentifier(n))return;if(!e.isReferenced(n,s))return;var l=a.letRefs[n.name];if(!l)return;if(o.get(n.name,true)!==l)return;var t=l.loc;var r=n.loc;if(!t||!r)return;var i=r.start.line<t.start.line;if(r.start.line===t.start.line){i=r.start.col<t.start.col}if(i){throw a.file.errorWithNode(n,"Temporal dead zone - accessing a variable before it's initialized")}}},this.scope,n)};n.prototype.remap=function(){var u=this.letReferences;var r=this.scope;var f=this.file;var l={};for(var a in u){var i=u[a];if(r.parentHas(a)){var c=f.generateUidIdentifier(i.name,r).name;i.name=c;l[a]={node:i,uid:c}}}var s=function(n,l,a,r,i){if(!e.isIdentifier(n))return;if(!e.isReferenced(n,l))return;var t=i[n.name];if(!t)return;var s=a.get(n.name,true);if(s===t.node){n.name=t.uid}else{if(r)r.skip()}};var o=function(e,n){s(e,n,r,null,l);t(e,{enter:s},r,l)};var n=this.loopParent;if(n){o(n.right,n);o(n.test,n);o(n.update,n)}t(this.block,{enter:s},r,l)};n.prototype.needsClosure=function(){var a=this.block;this.has=this.checkLoop();this.hoistVarDeclarations();var i=l.values(this.outsideLetReferences);var n=e.functionExpression(null,i,e.blockStatement(a.body));n._aliasFunction=true;a.body=this.body;var r=e.callExpression(n,i);var s=this.file.generateUidIdentifier("ret",this.scope);var o=t.hasType(n.body,"YieldExpression",e.FUNCTION_TYPES);if(o){n.generator=true;r=e.yieldExpression(r,true)}this.build(s,r)};n.prototype.getLetReferences=function(){var s=this.block;var r=s._letDeclars||[];var i;for(var n=0;n<r.length;n++){i=r[n];l.extend(this.outsideLetReferences,e.getIds(i,true))}if(s.body){for(n=0;n<s.body.length;n++){i=s.body[n];if(a(i,s)){r=r.concat(i.declarations)}}}for(n=0;n<r.length;n++){i=r[n];var c=e.getIds(i,true);l.extend(this.letReferences,c);this.hasLetReferences=true}if(!this.hasLetReferences)return;u(r);var o={letReferences:this.letReferences,closurify:false};t(this.block,{enter:function(r,i,l,a,n){if(e.isFunction(r)){t(r,{enter:function(t,r){if(!e.isIdentifier(t))return;if(!e.isReferenced(t,r))return;if(l.hasOwn(t.name,true))return;if(!n.letReferences[t.name])return;n.closurify=true}},l,n);return a.skip()}}},this.scope,o);return o.closurify};n.prototype.checkLoop=function(){var n={hasContinue:false,hasReturn:false,hasBreak:false};t(this.block,{enter:function(t,l,i,a){var r;if(e.isFunction(t)||e.isLoop(t)){return a.skip()}if(t&&!t.label){if(e.isBreakStatement(t)){if(e.isSwitchCase(l))return;n.hasBreak=true;r=e.returnStatement(e.literal("break"))}else if(e.isContinueStatement(t)){n.hasContinue=true;r=e.returnStatement(e.literal("continue"))}}if(e.isReturnStatement(t)){n.hasReturn=true;r=e.returnStatement(e.objectExpression([e.property("init",e.identifier("v"),t.argument||e.identifier("undefined"))]))}if(r)return e.inherits(r,t)}},this.scope,n);return n};n.prototype.hoistVarDeclarations=function(){t(this.block,{enter:function(n,r,a,l,t){if(e.isForStatement(n)){if(s(n.init,n)){n.init=e.sequenceExpression(t.pushDeclar(n.init))}}else if(e.isFor(n)){if(s(n.left,n)){n.left=n.left.declarations[0].id}}else if(s(n,r)){return t.pushDeclar(n).map(e.expressionStatement)}else if(e.isFunction(n)){return l.skip()}}},this.scope,this)};n.prototype.pushDeclar=function(n){this.body.push(e.variableDeclaration(n.kind,n.declarations.map(function(n){return e.variableDeclarator(n.id)})));var l=[];for(var r=0;r<n.declarations.length;r++){var t=n.declarations[r];if(!t.init)continue;var a=e.assignmentExpression("=",t.id,t.init);l.push(e.inherits(a,t))}return l};n.prototype.build=function(r,t){var n=this.has;if(n.hasReturn||n.hasBreak||n.hasContinue){this.buildHas(r,t)}else{this.body.push(e.expressionStatement(t))}};n.prototype.buildHas=function(r,c){var l=this.body;l.push(e.variableDeclaration("var",[e.variableDeclarator(r,c)]));var i=this.loopParent;var a;var n=this.has;var t=[];if(n.hasReturn){a=o.template("let-scoping-return",{RETURN:r})}if(n.hasBreak||n.hasContinue){var s=i.label=i.label||this.file.generateUidIdentifier("loop",this.scope);if(n.hasBreak){t.push(e.switchCase(e.literal("break"),[e.breakStatement(s)]))}if(n.hasContinue){t.push(e.switchCase(e.literal("continue"),[e.continueStatement(s)]))}if(n.hasReturn){t.push(e.switchCase(null,[a]))}if(t.length===1){var u=t[0];l.push(e.ifStatement(e.binaryExpression("===",r,u.test),u.consequent[0]))}else{l.push(e.switchStatement(r,t))}}else{if(n.hasReturn)l.push(a)}}},{"../../traverse":88,"../../types":92,"../../util":94,lodash:142}],59:[function(t,r,e){"use strict";var n=t("../../types");e.ast={before:function(e,n){e.program.body=n.dynamicImports.concat(e.program.body)}};e.ImportDeclaration=function(e,r,a,i,l){var n=[];if(e.specifiers.length){for(var t=0;t<e.specifiers.length;t++){l.moduleFormatter.importSpecifier(e.specifiers[t],e,n,r)}}else{l.moduleFormatter.importDeclaration(e,n,r)}if(n.length===1){n[0]._blockHoist=e._blockHoist}return n};e.ExportDeclaration=function(e,l,s,o,a){var t=[];if(e.declaration){if(n.isVariableDeclaration(e.declaration)){var i=e.declaration.declarations[0];i.init=i.init||n.identifier("undefined")}a.moduleFormatter.exportDeclaration(e,t,l)}else{for(var r=0;r<e.specifiers.length;r++){a.moduleFormatter.exportSpecifier(e.specifiers[r],e,t,l)}}return t}},{"../../types":92}],60:[function(n,a,t){"use strict";var l=n("../helpers/name-method");var r=n("../../util");var e=n("../../types");t.Property=function(e,r,n,a,t){if(!e.method)return;e.method=false;l.property(e,t,n)};t.ObjectExpression=function(n){var t={};var l=false;n.properties=n.properties.filter(function(e){if(e.kind==="get"||e.kind==="set"){l=true;r.pushMutatorMap(t,e.key,e.kind,e.computed,e.value);return false}else{return true}});if(!l)return;return e.callExpression(e.memberExpression(e.identifier("Object"),e.identifier("defineProperties")),[n,r.buildDefineProperties(t)])}},{"../../types":92,"../../util":94,"../helpers/name-method":30}],61:[function(e,l,n){"use strict";var t=e("../../types");var r=e("lodash");n.Property=function(e){if(!e.shorthand)return;e.shorthand=false;e.key=t.removeComments(r.clone(e.key))}},{"../../types":92,lodash:142}],62:[function(n,l,t){"use strict";var r=n("../../util");var e=n("../../types");t.Function=function(n,f,d,p,i){if(!n.rest)return;var c=n.rest;n.rest=null;e.ensureBlock(n);var u=e.identifier("arguments");u._ignoreAliasFunctions=true;var l=e.literal(n.params.length);var a=i.generateUidIdentifier("key");var t=i.generateUidIdentifier("len");var s=a;var o=t;if(n.params.length){s=e.binaryExpression("-",a,l);o=e.conditionalExpression(e.binaryExpression(">",t,l),e.binaryExpression("-",t,l),e.literal(0))}n.body.body.unshift(r.template("rest",{ARGUMENTS:u,ARRAY_KEY:s,ARRAY_LEN:o,START:l,ARRAY:c,KEY:a,LEN:t}))}},{"../../types":92,"../../util":94}],63:[function(l,s,n){"use strict";var e=l("../../types");var a=l("lodash");var i=function(e,n){return n.toArray(e.argument)};var t=function(t){for(var n=0;n<t.length;n++){if(e.isSpreadElement(t[n])){return true}}return false};var r=function(a,o){var t=[];var n=[];var s=function(){if(!n.length)return;t.push(e.arrayExpression(n));n=[]};for(var r=0;r<a.length;r++){var l=a[r];if(e.isSpreadElement(l)){s();t.push(i(l,o))}else{n.push(l)}}s();return t};n.ArrayExpression=function(i,o,u,c,s){var a=i.elements;if(!t(a))return;var l=r(a,s);var n=l.shift();if(!e.isArrayExpression(n)){l.unshift(n);n=e.arrayExpression([])}return e.callExpression(e.memberExpression(n,e.identifier("concat")),l)};n.CallExpression=function(n,p,f,d,u){var a=n.arguments;if(!t(a))return;var s=e.identifier("undefined");n.arguments=[];var i;if(a.length===1&&a[0].argument.name==="arguments"){i=[a[0].argument]}else{i=r(a,u)}var c=i.shift();if(i.length){n.arguments.push(e.callExpression(e.memberExpression(c,e.identifier("concat")),i))}else{n.arguments.push(c)}var l=n.callee;if(e.isMemberExpression(l)){var o=f.generateTempBasedOnNode(l.object,u);if(o){l.object=e.assignmentExpression("=",o,l.object);s=o}else{s=l.object}e.appendToMemberExpression(l,e.identifier("apply"))}else{n.callee=e.memberExpression(n.callee,e.identifier("apply"))}n.arguments.unshift(s)};n.NewExpression=function(l,c,f,p,s){var n=l.arguments;if(!t(n))return;var o=e.isIdentifier(l.callee)&&a.contains(e.NATIVE_TYPE_NAMES,l.callee.name);var i=r(n,s);if(o){i.unshift(e.arrayExpression([e.literal(null)]))}var u=i.shift();if(i.length){n=e.callExpression(e.memberExpression(u,e.identifier("concat")),i)}else{n=u}if(o){return e.newExpression(e.callExpression(e.memberExpression(s.addHelper("bind"),e.identifier("apply")),[l.callee,n]),[])}else{return e.callExpression(s.addHelper("apply-constructor"),[l.callee,n])}}},{"../../types":92,lodash:142}],64:[function(r,l,n){"use strict";var e=r("../../types");var t=function(n,t){return e.binaryExpression("+",n,t)};n.TaggedTemplateExpression=function(s,c,p,f,o){var n=[];var l=s.quasi;var r=[];var t=[];for(var a=0;a<l.quasis.length;a++){var i=l.quasis[a];r.push(e.literal(i.value.cooked));t.push(e.literal(i.value.raw))}r=e.arrayExpression(r);t=e.arrayExpression(t);var u="tagged-template-literal";if(o.isLoose("templateLiterals"))u+="-loose";n.push(e.callExpression(o.addHelper(u),[r,t]));n=n.concat(l.expressions);return e.callExpression(s.tag,n)};n.TemplateLiteral=function(l){var n=[];var r;for(r=0;r<l.quasis.length;r++){var s=l.quasis[r];n.push(e.literal(s.value.cooked));var i=l.expressions.shift();if(i)n.push(i)}if(n.length>1){var o=n[n.length-1];if(e.isLiteral(o,{value:""}))n.pop();var a=t(n.shift(),n.shift());for(r=0;r<n.length;r++){a=t(a,n[r])}return a}else{return n[0]}}},{"../../types":92}],65:[function(e,l,n){"use strict";var t=e("regexpu/rewrite-pattern");var r=e("lodash");n.Literal=function(l){var e=l.regex;if(!e)return;var n=e.flags.split("");if(e.flags.indexOf("u")<0)return;r.pull(n,"u");e.pattern=t(e.pattern,e.flags);e.flags=n.join("")}},{lodash:142,"regexpu/rewrite-pattern":185}],66:[function(r,a,n){"use strict";var t=r("../../util");var e=r("../../types");n.experimental=true;var l=function(r,n,l){if(e.isExpressionStatement(r)){return n}else{var t=[];if(e.isSequenceExpression(n)){t=n.expressions}else{t.push(n)}t.push(l);return e.sequenceExpression(t)}};n.AssignmentExpression=function(n,o,u,f,c){var i=n.left;if(!e.isVirtualPropertyExpression(i))return;var r=n.right;var a;if(!e.isExpressionStatement(o)){a=u.generateTempBasedOnNode(n.right,c);if(a)r=a}if(n.operator!=="="){r=e.binaryExpression(n.operator[0],t.template("abstract-expression-get",{PROPERTY:n.property,OBJECT:n.object}),r)}var s=t.template("abstract-expression-set",{PROPERTY:i.property,OBJECT:i.object,VALUE:r});if(a){s=e.sequenceExpression([e.assignmentExpression("=",a,n.right),s])}return l(o,s,r)};n.UnaryExpression=function(r,a){var n=r.argument;if(!e.isVirtualPropertyExpression(n))return;if(r.operator!=="delete")return;var i=t.template("abstract-expression-delete",{PROPERTY:n.property,OBJECT:n.object});return l(a,i,e.literal(true))};n.CallExpression=function(a,o,i,u,s){var n=a.callee;if(!e.isVirtualPropertyExpression(n))return;var l=i.generateTempBasedOnNode(n.object,s);var r=t.template("abstract-expression-call",{PROPERTY:n.property,OBJECT:l||n.object});r.arguments=r.arguments.concat(a.arguments);if(l){return e.sequenceExpression([e.assignmentExpression("=",l,n.object),r])}else{return r}};n.VirtualPropertyExpression=function(e){return t.template("abstract-expression-get",{PROPERTY:e.property,OBJECT:e.object})};n.PrivateDeclaration=function(n){return e.variableDeclaration("const",n.declarations.map(function(n){return e.variableDeclarator(n,e.newExpression(e.identifier("WeakMap"),[]))}))}},{"../../types":92,"../../util":94}],67:[function(e,s,n){"use strict";var l=e("../helpers/build-comprehension");var a=e("../../traverse");var t=e("../../util");var r=e("../../types");n.experimental=true;var i=function(n,o,u,d,c){var s=u.generateUidBasedOnNode(o,c);var e=t.template("array-comprehension-container",{KEY:s});e.callee._aliasFunction=true;var f=e.callee.body;var i=f.body;if(a.hasType(n,"YieldExpression",r.FUNCTION_TYPES)){e.callee.generator=true;e=r.yieldExpression(e,true)}var p=i.pop();i.push(l(n,function(){return t.template("array-push",{STATEMENT:n.body,KEY:s},true)}));i.push(p);return e};n.ComprehensionExpression=function(e,n,t,r,l){if(e.generator)return;return i(e,n,t,r,l)}},{"../../traverse":88,"../../types":92,"../../util":94,"../helpers/build-comprehension":27}],68:[function(n,a,t){"use strict";t.experimental=true;var r=n("../helpers/build-binary-assignment-operator-transformer");var e=n("../../types");var l=e.memberExpression(e.identifier("Math"),e.identifier("pow"));r(t,{operator:"**",build:function(n,t){return e.callExpression(l,[n,t])}})},{"../../types":92,"../helpers/build-binary-assignment-operator-transformer":26}],69:[function(n,l,t){"use strict";var r=n("../helpers/build-comprehension");var e=n("../../types");t.experimental=true;t.ComprehensionExpression=function(n){if(!n.generator)return;var t=[];var l=e.functionExpression(null,[],e.blockStatement(t),true);l._aliasFunction=true;t.push(r(n,function(){return e.expressionStatement(e.yieldExpression(n.body))}));return e.callExpression(l,[])}},{"../../types":92,"../helpers/build-comprehension":27}],70:[function(t,r,n){"use strict";var e=t("../../types");n.experimental=true;n.ObjectExpression=function(l,u,f,c,o){var s=false;var n;var t;for(n=0;n<l.properties.length;n++){t=l.properties[n];if(e.isSpreadProperty(t)){s=true;break}}if(!s)return;var r=[];var a=[];var i=function(){if(!a.length)return;r.push(e.objectExpression(a));a=[]};for(n=0;n<l.properties.length;n++){t=l.properties[n];if(e.isSpreadProperty(t)){i();r.push(t.argument)}else{a.push(t)}}i();if(!e.isObjectExpression(r[0])){r.unshift(e.objectExpression([]))}return e.callExpression(o.addHelper("extends"),r)}},{"../../types":92}],71:[function(n,l,e){"use strict";var t=n("../helpers/remap-async-to-generator");var r=n("./optional-bluebird-coroutines");e.optional=true;e.manipulateOptions=r.manipulateOptions;e.Function=function(e,r,l,a,n){if(!e.async||e.generator)return;return t(e,n.addHelper("async-to-generator"))}},{"../helpers/remap-async-to-generator":31,"./optional-bluebird-coroutines":72}],72:[function(n,l,e){"use strict";var r=n("../helpers/remap-async-to-generator");var t=n("../../types");e.manipulateOptions=function(e){e.experimental=true;e.blacklist.push("generators")};e.optional=true;e.Function=function(e,l,a,i,n){if(!e.async||e.generator)return;return r(e,t.memberExpression(n.addImport("bluebird"),t.identifier("coroutine")))}},{"../../types":92,"../helpers/remap-async-to-generator":31}],73:[function(n,u,r){"use strict";var a=n("../../traverse");var i=n("../../util");var l=n("core-js/library");var e=n("../../types");var t=n("lodash");var s=function(e){return e.name!=="_"&&t.has(l,e.name)};var o=["Symbol","Promise","Map","WeakMap","Set","WeakSet"];r.optional=true;r.ast={enter:function(n,e){e._coreId=e.addImport("core-js/library","core")},exit:function(r,n){a(r,{enter:function(r,c,d,p){var a;if(e.isMemberExpression(r)&&e.isReferenced(r,c)){var f=r.object;a=r.property;if(!e.isReferenced(f,r))return;if(!r.computed&&s(f)&&t.has(l[f.name],a.name)){p.skip();return e.prependToMemberExpression(r,n._coreId)}}else if(e.isIdentifier(r)&&!e.isMemberExpression(c)&&e.isReferenced(r,c)&&t.contains(o,r.name)){return e.memberExpression(n._coreId,r)}else if(e.isCallExpression(r)){if(r.arguments.length)return;var u=r.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 i.template("corejs-iterator",{CORE_ID:n._coreId,VALUE:u.object})}}})}}},{"../../traverse":88,"../../types":92,"../../util":94,"core-js/library":135,lodash:142}],74:[function(t,s,n){"use strict";var e=t("../../types");var a=t("lodash");var i=function(n){return e.isLiteral(e.toComputedKey(n,n.key),{value:"__proto__"})};var r=function(t){var n=t.left;return e.isMemberExpression(n)&&e.isLiteral(e.toComputedKey(n,n.property),{value:"__proto__"})};var l=function(n,t,r){return e.expressionStatement(e.callExpression(r.addHelper("defaults"),[t,n.right]))};n.optional=true;n.secondPass=true;n.AssignmentExpression=function(n,s,o,c,i){if(e.isExpressionStatement(s))return;if(!r(n))return;var t=[];var u=n.left.object;var a=o.generateTempBasedOnNode(n.left.object,i);t.push(e.expressionStatement(e.assignmentExpression("=",a,u)));t.push(l(n,a,i));if(a)t.push(a);return e.toSequenceExpression(t)};n.ExpressionStatement=function(t,i,s,o,a){var n=t.expression;if(!e.isAssignmentExpression(n,{operator:"="}))return;if(r(n)){return l(n,n.left.object,a)}};n.ObjectExpression=function(n,u,c,f,o){var t;for(var r=0;r<n.properties.length;r++){var l=n.properties[r];if(i(l)){t=l.value;a.pull(n.properties,l)}}if(t){var s=[e.objectExpression([]),t];if(n.properties.length)s.push(n);return e.callExpression(o.addHelper("extends"),s)}}},{"../../types":92,lodash:142}],75:[function(t,r,n){"use strict";var e=t("../../types");n.optional=true;n.UnaryExpression=function(n,i,s,l,a){l.skip();if(n.operator==="typeof"){var t=e.callExpression(a.addHelper("typeof"),[n.argument]);if(e.isIdentifier(n.argument)){var r=e.literal("undefined");return e.conditionalExpression(e.binaryExpression("===",e.unaryExpression("typeof",n.argument),r),r,t)}else{return t}}}},{"../../types":92}],76:[function(t,r,n){"use strict";var e=t("../../types");n.optional=true;n.Identifier=function(n,t){if(n.name==="undefined"&&e.isReferenced(n,t)){return e.unaryExpression("void",e.literal(0),true)}}},{"../../types":92}],77:[function(n,l,t){"use strict";var r=n("../helpers/build-conditional-assignment-operator-transformer");var e=n("../../types");r(t,{is:function(n,r){var l=e.isAssignmentExpression(n)&&n.operator==="||=";if(l){var t=n.left;if(!e.isMemberExpression(t)&&!e.isIdentifier(t)){throw r.errorWithNode(t,"Expected type MemeberExpression or Identifier")}return true}},build:function(n){return e.unaryExpression("!",n,true)}})},{"../../types":92,"../helpers/build-conditional-assignment-operator-transformer":28}],78:[function(n,l,t){"use strict";var r=n("../helpers/build-conditional-assignment-operator-transformer");var e=n("../../types");r(t,{is:function(n){var t=e.isAssignmentExpression(n)&&n.operator==="?=";if(t)e.assertMemberExpression(n.left);return t},build:function(n,t){return e.unaryExpression("!",e.callExpression(e.memberExpression(t.addHelper("has-own"),e.identifier("call")),[n.object,n.property]),true)}})},{"../../types":92,"../helpers/build-conditional-assignment-operator-transformer":28}],79:[function(t,r,n){"use strict";var e=t("../../types");n.BindMemberExpression=function(n,o,a,u,i){var r=n.object;var s=n.property;var t=a.generateTempBasedOnNode(n.object,i);if(t)r=t;var l=e.callExpression(e.memberExpression(e.memberExpression(r,s),e.identifier("bind")),[r].concat(n.arguments));if(t){return e.sequenceExpression([e.assignmentExpression("=",t,n.object),l])}else{return l}};n.BindFunctionExpression=function(n,i,t,s,r){var a=function(a){var l=r.generateUidIdentifier("val",t);return e.functionExpression(null,[l],e.blockStatement([e.returnStatement(e.callExpression(e.memberExpression(l,n.callee),a))]))};var l=t.generateTemp(r,"args");return e.sequenceExpression([e.assignmentExpression("=",l,e.arrayExpression(n.arguments)),a(n.arguments.map(function(t,n){return e.memberExpression(l,e.literal(n),true)}))])}},{"../../types":92}],80:[function(n,l,t){"use strict";var r=n("../../traverse");var e=n("../../types");t.Property=t.MethodDefinition=function(n,i,s,o,a){if(n.kind!=="memo")return;n.kind="get";var l=n.value;e.ensureBlock(l);var t=n.key;if(e.isIdentifier(t)&&!n.computed){t=e.literal(t.name)}r(l,{enter:function(n){if(e.isFunction(n))return;if(e.isReturnStatement(n)&&n.argument){n.argument=e.memberExpression(e.callExpression(a.addHelper("define-property"),[e.thisExpression(),t,n.argument]),t,true)}}})}},{"../../traverse":88,"../../types":92}],81:[function(t,c,n){"use strict";var i=t("esutils");var e=t("../../types");var u=t("lodash");n.XJSIdentifier=function(n){if(i.keyword.isIdentifierName(n.name)){n.type="Identifier"}else{return e.literal(n.name)}};n.XJSNamespacedName=function(e,t,r,l,n){throw n.errorWithNode(e,"Namespace tags are not supported. ReactJSX is not XML.")};n.XJSMemberExpression={exit:function(n){n.computed=e.isLiteral(n.property);n.type="MemberExpression"}};n.XJSExpressionContainer=function(e){return e.expression};n.XJSAttribute={exit:function(n){var t=n.value||e.literal(true);return e.inherits(e.property("init",n.name,t),n)}};var r=function(e){return/^[a-z]|\-/.test(e)};n.XJSOpeningElement={exit:function(i,c,f,p,u){var o=u.opts.reactCompat;var n=i.name;var l=[];var t;if(e.isIdentifier(n)){t=n.name}else if(e.isLiteral(n)){t=n.value}if(!o){if(t&&r(t)){l.push(e.literal(t))}else{l.push(n)}}var a=i.attributes;if(a.length){a=s(a)}else{a=e.literal(null)}l.push(a);if(o){if(t&&r(t)){return e.callExpression(e.memberExpression(e.memberExpression(e.identifier("React"),e.identifier("DOM")),n,e.isLiteral(n)),l)}}else{n=e.memberExpression(e.identifier("React"),e.identifier("createElement"))}return e.callExpression(n,l)}};var s=function(t){var r=[];var n=[];var a=function(){if(!r.length)return;n.push(e.objectExpression(r));r=[]};while(t.length){var l=t.shift();if(e.isXJSSpreadAttribute(l)){a();n.push(l.argument)}else{r.push(l)}}a();if(n.length===1){t=n[0]}else{if(!e.isObjectExpression(n[0])){n.unshift(e.objectExpression([]))}t=e.callExpression(e.memberExpression(e.identifier("React"),e.identifier("__spread")),n)}return t};n.XJSElement={exit:function(r){var n=r.openingElement;for(var l=0;l<r.children.length;l++){var t=r.children[l];if(e.isLiteral(t)&&u.isString(t.value)){o(t,n.arguments);continue}else if(e.isXJSEmptyExpression(t)){continue}n.arguments.push(t)}if(n.arguments.length>=3){n._prettyCall=true}return e.inherits(n,r)}};var o=function(l,a){var r=l.value.split(/\r\n|\n|\r/);for(var t=0;t<r.length;t++){var i=r[t];var s=t===0;var o=t===r.length-1;var n=i.replace(/\t/g," ");if(!s){n=n.replace(/^[ ]+/,"")}if(!o){n=n.replace(/[ ]+$/,"")}if(n){a.push(e.literal(n))}}};var a=function(n){if(!n||!e.isCallExpression(n))return false;var t=n.callee;if(!e.isMemberExpression(t))return false;var l=t.object;if(!e.isIdentifier(l,{name:"React"}))return false;var a=t.property;if(!e.isIdentifier(a,{name:"createClass"}))return false;var r=n.arguments;if(r.length!==1)return false;var i=r[0];if(!e.isObjectExpression(i))return;return true};var l=function(i,r){if(!a(r))return;var n=r.arguments[0].properties;var l=true;for(var t=0;t<n.length;t++){var s=n[t];if(e.isIdentifier(s.key,{name:"displayName"})){l=false;break}}if(l){n.unshift(e.property("init",e.identifier("displayName"),e.literal(i)))}};n.AssignmentExpression=n.Property=n.VariableDeclarator=function(n){var t,r;if(e.isAssignmentExpression(n)){t=n.left;r=n.right}else if(e.isProperty(n)){t=n.key;r=n.value}else if(e.isVariableDeclarator(n)){t=n.id;r=n.init}if(e.isMemberExpression(t)){t=t.property}if(e.isIdentifier(t)){l(t.name,r)}}},{"../../types":92,esutils:140,lodash:142}],82:[function(n,r,t){"use strict";var e=n("../../types");t.FunctionDeclaration=function(n,t){if(e.isProgram(t)||e.isExportDeclaration(t)){return}n.id.loc=null;var r=e.variableDeclaration("let",[e.variableDeclarator(n.id,e.toExpression(n))]);r._blockHoist=2;n.id=null;return r}},{"../../types":92}],83:[function(n,r,t){"use strict";var e=n("../../types");t.MemberExpression=function(n){var t=n.property;if(n.computed&&e.isLiteral(t)&&e.isValidIdentifier(t.value)){n.property=e.identifier(t.value);n.computed=false}else if(!n.computed&&e.isIdentifier(t)&&!e.isValidIdentifier(t.name)){n.property=e.literal(t.name);n.computed=true}}},{"../../types":92}],84:[function(n,r,e){"use strict";var t=n("../../types");e.ForInStatement=e.ForOfStatement=function(r,a,i,s,l){var e=r.left;if(t.isVariableDeclaration(e)){var n=e.declarations[0];if(n.init)throw l.errorWithNode(n,"No assignments allowed in for-in/of head")}}},{"../../types":92}],85:[function(n,r,t){"use strict";var e=n("../../types");t.Property=function(t){var n=t.key;if(e.isLiteral(n)&&e.isValidIdentifier(n.value)){t.key=e.identifier(n.value);t.computed=false}else if(!t.computed&&e.isIdentifier(n)&&!e.isValidIdentifier(n.name)){t.key=e.literal(n.name)}}},{"../../types":92}],86:[function(n,t,e){"use strict";e.MethodDefinition=e.Property=function(e,t,r,l,n){if(e.kind==="set"&&e.value.params.length!==1){throw n.errorWithNode(e.value,"Setters must have only one parameter")}}},{}],87:[function(e,l,t){"use strict";var r=e("../helpers/use-strict");var n=e("../../types");t.ast={exit:function(e){if(!r.has(e.program)){e.program.body.unshift(n.expressionStatement(n.literal("use strict")))}}}},{"../../types":92,"../helpers/use-strict":33}],88:[function(a,u,c){"use strict";u.exports=r;var o=a("./scope");var n=a("../types");var t=a("lodash");function i(){}function e(){this.shouldFlatten=false;this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false}e.prototype.flatten=function(){this.shouldFlatten=true};e.prototype.remove=function(){this.shouldRemove=true;this.shouldSkip=true};e.prototype.skip=function(){this.shouldSkip=true};e.prototype.stop=function(){this.shouldStop=true;this.shouldSkip=true};e.prototype.reset=function(){this.shouldRemove=false;this.shouldSkip=false;this.shouldStop=false};function s(r,l,s,e){var a=Array.isArray(e);var i=e;if(a)i=e[0];if(i)n.inheritsComments(i,s);r[l]=e;if(a&&t.contains(n.STATEMENT_OR_BLOCK_KEYS,l)&&!n.isBlockStatement(r)){n.ensureBlock(r,l)}if(a){return true}}e.prototype.enterNode=function(t,r,e,a,i,o,u){var n=a(e,i,o,this,u);var l=false;if(n){l=s(t,r,e,n);e=n;if(l){this.shouldFlatten=true}}if(this.shouldRemove){t[r]=null;this.shouldFlatten=true}return e};e.prototype.exitNode=function(r,l,e,a,i,o,u){var n=a(e,i,o,this,u);var t=false;if(n){t=s(r,l,e,n);e=n;if(t){this.shouldFlatten=true}}return e};e.prototype.visitNode=function(a,i,t,u,c,s){this.reset();var e=a[i];if(t.blacklist&&t.blacklist.indexOf(e.type)>-1)return;var r=u;if(n.isScope(e)){r=new o(e,u)}e=this.enterNode(a,i,e,t.enter,c,r,s);if(this.shouldSkip)return this.shouldStop;l(e,t,r,s);this.exitNode(a,i,e,t.exit,c,r,s);return this.shouldStop};e.prototype.visit=function(e,n,a,i,s){var r=e[n];if(!r)return;if(!Array.isArray(r)){return this.visitNode(e,n,a,i,e,s)}if(r.length===0){return}for(var l=0;l<r.length;l++){if(r[l]&&this.visitNode(r,l,a,i,e,s))return true}if(this.shouldFlatten){e[n]=t.flatten(e[n]);if(n==="body"){e[n]=t.compact(e[n])}}};function l(l,a,i,s){var t=n.VISITOR_KEYS[l.type];if(!t)return;var o=new e;for(var r=0;r<t.length;r++){if(o.visit(l,t[r],a,i,s)){return}}}function r(n,e,r,a){if(!n)return;if(!e)e={};if(!e.enter)e.enter=i;if(!e.exit)e.exit=i;if(Array.isArray(n)){for(var t=0;t<n.length;t++){l(n[t],e,r,a)}}else{l(n,e,r,a)}}r.removeProperties=function(e){var n=function(e){e._declarations=null;e.extendedRange=null;e._scopeInfo=null;e.tokens=null;e.range=null;e.start=null;e.end=null;e.loc=null;e.raw=null;l(e.trailingComments);l(e.leadingComments)};var l=function(e){t.each(e,n)};n(e);r(e,{enter:n});return e};r.hasType=function(n,l,e){e=[].concat(e||[]);if(t.contains(e,n.type))return false;if(n.type===l)return true;var a={has:false};r(n,{blacklist:e,enter:function(e,r,a,n,t){if(e.type===l){t.has=true;n.skip()}}},null,a);return a.has}},{"../types":92,"./scope":89,lodash:142}],89:[function(r,i,o){"use strict";i.exports=n;var s=r("./index");var e=r("../types");var t=r("lodash");var a=["left","init"];function n(n,t){this.parent=t;this.block=n;var e=this.getInfo();this.references=e.references;this.declarations=e.declarations}var l=r("jshint/src/vars");n.defaultDeclarations=t.flatten([l.newEcmaIdentifiers,l.node,l.ecmaIdentifiers,l.reservedVars].map(t.keys));n.add=function(n,r){if(!n)return;t.defaults(r,e.getIds(n,true))};n.prototype.generateTemp=function(n,t){var e=n.generateUidIdentifier(t||"temp",this);this.push({key:e.name,id:e});return e};n.prototype.generateUidBasedOnNode=function(t,i){var n=t;if(e.isAssignmentExpression(t)){n=t.left}else if(e.isVariableDeclarator(t)){n=t.id}else if(e.isProperty(n)){n=n.key}var l=[];var r=function(n){if(e.isMemberExpression(n)){r(n.object);r(n.property)}else if(e.isIdentifier(n)){l.push(n.name)}else if(e.isLiteral(n)){l.push(n.value)}else if(e.isCallExpression(n)){r(n.callee)}};r(n);var a=l.join("$");a=a.replace(/^_/,"")||"ref";return i.generateUidIdentifier(a,this)};n.prototype.generateTempBasedOnNode=function(n,r){if(e.isIdentifier(n)&&this.has(n.name,true)){return null}var t=this.generateUidBasedOnNode(n,r);this.push({key:t.name,id:t});return t};n.prototype.getInfo=function(){var r=this.block;if(r._scopeInfo)return r._scopeInfo;var i=r._scopeInfo={};var o=i.references={};var u=i.declarations={};var l=function(e,t){n.add(e,o);if(!t)n.add(e,u)};if(e.isFor(r)){t.each(a,function(t){var n=r[t];if(e.isBlockScoped(n))l(n)})}if(e.isBlockStatement(r)||e.isProgram(r)){t.each(r.body,function(n){if(e.isBlockScoped(n))l(n)})}if(e.isCatchClause(r)){l(r.param)}if(e.isComprehensionExpression(r)){l(r)}if(e.isProgram(r)||e.isFunction(r)){var c={blockId:r.id,add:l};s(r,{enter:function(n,i,s,o,r){if(e.isFor(n)){t.each(a,function(r){var t=n[r];if(e.isVar(t))l(t)})}if(e.isFunction(n))return o.skip();if(r.blockId&&n===r.blockId)return;if(e.isIdentifier(n)&&e.isReferenced(n,i)&&!s.has(n.name)){r.add(n,true)}if(e.isDeclaration(n)&&!e.isBlockScoped(n)){r.add(n)}}},this,c)}if(e.isFunction(r)){l(r.rest);t.each(r.params,function(e){l(e)})}return i};n.prototype.push=function(t){var n=this.block;if(e.isFor(n)||e.isCatchClause(n)||e.isFunction(n)){e.ensureBlock(n);n=n.body}if(e.isBlockStatement(n)||e.isProgram(n)){n._declarations=n._declarations||{};n._declarations[t.key]={kind:t.kind,id:t.id,init:t.init}}else{throw new TypeError("cannot add a declaration here in node type "+n.type)}};n.prototype.add=function(e){n.add(e,this.references)};n.prototype.get=function(e,n){return e&&(this.getOwn(e,n)||this.parentGet(e,n))};n.prototype.getOwn=function(n,r){var e=this.references;if(r)e=this.declarations;return t.has(e,n)&&e[n]};n.prototype.parentGet=function(e,n){return this.parent&&this.parent.get(e,n)};n.prototype.has=function(e,r){return e&&(this.hasOwn(e,r)||this.parentHas(e,r))||t.contains(n.defaultDeclarations,e)};n.prototype.hasOwn=function(e,n){return!!this.getOwn(e,n)};n.prototype.parentHas=function(e,n){return this.parent&&this.parent.has(e,n)}},{"../types":92,"./index":88,"jshint/src/vars":141,lodash:142}],90:[function(n,e,t){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"],PrivateDeclaration:["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","Scope"],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"]}
},{}],91:[function(n,e,t){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"]}},{}],92:[function(t,s,r){"use strict";var l=t("../to-fast-properties");var a=t("esutils");var n=t("lodash");var e=r;e.NATIVE_TYPE_NAMES=["Array","Object","Number","Boolean","Date","Array","String"];function i(n,t){var r=e["is"+n]=function(r,l){return e.is(n,r,l,t)};e["assert"+n]=function(t,e){e=e||{};if(!r(t,e)){throw new Error("Expected type "+JSON.stringify(n)+" with option "+JSON.stringify(e))}}}e.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];e.VISITOR_KEYS=t("./visitor-keys");e.ALIAS_KEYS=t("./alias-keys");e.FLIPPED_ALIAS_KEYS={};n.each(e.VISITOR_KEYS,function(n,e){i(e,true)});n.each(e.ALIAS_KEYS,function(t,r){n.each(t,function(n){var t=e.FLIPPED_ALIAS_KEYS[n]=e.FLIPPED_ALIAS_KEYS[n]||[];t.push(r)})});n.each(e.FLIPPED_ALIAS_KEYS,function(t,n){e[n.toUpperCase()+"_TYPES"]=t;i(n,false)});e.is=function(r,n,l,i){if(!n)return;var t=r===n.type;if(!t&&!i){var a=e.FLIPPED_ALIAS_KEYS[r];if(typeof a!=="undefined")t=a.indexOf(n.type)>-1}if(!t){return false}if(typeof l!=="undefined")return e.shallowEqual(n,l);return true};e.BUILDER_KEYS=n.defaults(t("./builder-keys"),e.VISITOR_KEYS);n.each(e.BUILDER_KEYS,function(r,t){e[t[0].toLowerCase()+t.slice(1)]=function(){var l=arguments;var e={type:t};n.each(r,function(n,t){e[n]=l[t]});return e}});e.toComputedKey=function(t,n){if(!t.computed){if(e.isIdentifier(n))n=e.literal(n.name)}return n};e.isFalsyExpression=function(n){if(e.isLiteral(n)){return!n.value}else if(e.isIdentifier(n)){return n.name==="undefined"}return false};e.toSequenceExpression=function(r,l){var t=[];n.each(r,function(r){if(e.isExpression(r)){t.push(r)}if(e.isExpressionStatement(r)){t.push(r.expression)}else if(e.isVariableDeclaration(r)){n.each(r.declarations,function(n){l.push({kind:r.kind,key:n.id.name,id:n.id});t.push(e.assignmentExpression("=",n.id,n.init))})}});if(t.length===1){return t[0]}else{return e.sequenceExpression(t)}};e.shallowEqual=function(l,t){var r=Object.keys(t);var e;for(var n=0;n<r.length;n++){e=r[n];if(l[e]!==t[e])return false}return true};e.appendToMemberExpression=function(n,t,r){n.object=e.memberExpression(n.object,n.property,n.computed);n.property=t;n.computed=!!r;return n};e.prependToMemberExpression=function(n,t){n.object=e.memberExpression(t,n.object);return n};e.isReferenced=function(r,t){if(e.isProperty(t)&&t.key===r&&!t.computed)return false;if(e.isFunction(t)){if(n.contains(t.params,r))return false;if(t.rest===r)return false}if(e.isMethodDefinition(t)&&t.key===r&&!t.computed){return false}if(e.isCatchClause(t)&&t.param===r)return false;if(e.isVariableDeclarator(t)&&t.id===r)return false;var l=e.isMemberExpression(t);var a=l&&t.property===r&&t.computed;var i=l&&t.object===r;if(!l||a||i)return true;return false};e.isValidIdentifier=function(e){return n.isString(e)&&a.keyword.isIdentifierName(e)&&!a.keyword.isReservedWordES6(e,true)};e.toIdentifier=function(n){if(e.isIdentifier(n))return n.name;n=n+"";n=n.replace(/[^a-zA-Z0-9$_]/g,"-");n=n.replace(/^[-0-9]+/,"");n=n.replace(/[-_\s]+(.)?/g,function(n,e){return e?e.toUpperCase():""});n=n.replace(/^\_/,"");if(!e.isValidIdentifier(n)){n="_"+n}return n||"_"};e.ensureBlock=function(t,n){n=n||"body";t[n]=e.toBlock(t[n],t)};e.toStatement=function(n,l){if(e.isStatement(n)){return n}var r=false;var t;if(e.isClass(n)){r=true;t="ClassDeclaration"}else if(e.isFunction(n)){r=true;t="FunctionDeclaration"}if(r&&!n.id){t=false}if(!t){if(l){return false}else{throw new Error("cannot turn "+n.type+" to a statement")}}n.type=t;return n};r.toExpression=function(n){if(e.isExpressionStatement(n)){n=n.expression}if(e.isClass(n)){n.type="ClassExpression"}else if(e.isFunction(n)){n.type="FunctionExpression"}if(e.isExpression(n)){return n}else{throw new Error("cannot turn "+n.type+" to an expression")}};e.toBlock=function(n,t){if(e.isBlockStatement(n)){return n}if(e.isEmptyStatement(n)){n=[]}if(!Array.isArray(n)){if(!e.isStatement(n)){if(e.isFunction(t)){n=e.returnStatement(n)}else{n=e.expressionStatement(n)}}n=[n]}return e.blockStatement(n)};e.getIds=function(c,f,s){s=s||[];var l=[].concat(c);var i={};while(l.length){var t=l.shift();if(!t)continue;if(n.contains(s,t.type))continue;var o=e.getIds.nodes[t.type];var u=e.getIds.arrays[t.type];var r,a;if(e.isIdentifier(t)){i[t.name]=t}else if(o){for(r=0;r<o.length;r++){a=o[r];if(t[a]){l.push(t[a]);break}}}else if(u){for(r=0;r<u.length;r++){a=u[r];l=l.concat(t[a]||[])}}}if(!f)i=n.keys(i);return i};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"],ComprehensionBlock:["left"]};e.getIds.arrays={PrivateDeclaration:["declarations"],ComprehensionExpression:["blocks"],ExportDeclaration:["specifiers","declaration"],ImportDeclaration:["specifiers"],VariableDeclaration:["declarations"],ArrayPattern:["elements"],ObjectPattern:["properties"]};e.isLet=function(n){return e.isVariableDeclaration(n)&&(n.kind!=="var"||n._let)};e.isBlockScoped=function(n){return e.isFunctionDeclaration(n)||e.isLet(n)};e.isVar=function(n){return e.isVariableDeclaration(n,{kind:"var"})&&!n._let};e.COMMENT_KEYS=["leadingComments","trailingComments"];e.removeComments=function(t){n.each(e.COMMENT_KEYS,function(e){delete t[e]});return t};e.inheritsComments=function(t,r){n.each(e.COMMENT_KEYS,function(e){t[e]=n.uniq(n.compact([].concat(t[e],r[e])))});return t};e.inherits=function(n,t){n.range=t.range;n.start=t.start;n.loc=t.loc;n.end=t.end;e.inheritsComments(n,t);return n};e.getSpecifierName=function(e){return e.name||e.id};e.isSpecifierDefault=function(n){return e.isIdentifier(n.id)&&n.id.name==="default"};l(e);l(e.VISITOR_KEYS)},{"../to-fast-properties":25,"./alias-keys":90,"./builder-keys":91,"./visitor-keys":93,esutils:140,lodash:142}],93:[function(n,e,t){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"]}},{}],94:[function(n,t,e){(function(u,o){"use strict";n("./patch");var f=n("estraverse");var l=n("./traverse");var c=n("acorn-6to5");var a=n("path");var m=n("util");var i=n("fs");var t=n("./types");var r=n("lodash");e.inherits=m.inherits;e.canCompile=function(n,t){var l=t||e.canCompile.EXTENSIONS;var i=a.extname(n);return r.contains(l,i)};e.canCompile.EXTENSIONS=[".js",".jsx",".es6",".es"];e.isInteger=function(e){return r.isNumber(e)&&e%1===0};e.resolve=function(e){try{return n.resolve(e)}catch(t){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(r.isString(e))return new RegExp(e);if(r.isRegExp(e))return e;throw new TypeError("illegal type for regexify")};e.arrayify=function(n){if(!n)return[];if(r.isString(n))return e.list(n);if(Array.isArray(n))return n;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 n=JSON.stringify(e);var t=new u(n).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+t};e.pushMutatorMap=function(i,n,o,s,u){var e;if(t.isIdentifier(n)){e=n.name;if(s)e="computed:"+e}else if(t.isLiteral(n)){e=String(n.value)}else{e=JSON.stringify(l.removeProperties(r.cloneDeep(n)))}var a;if(r.has(i,e)){a=i[e]}else{a={}}i[e]=a;a._key=n;if(s){a._computed=true}a[o]=u};e.buildDefineProperties=function(n){var e=t.objectExpression([]);r.each(n,function(n){var l=t.objectExpression([]);var a=t.property("init",n._key,l,n._computed);if(!n.get&&!n.set){n.writable=t.literal(true)}n.enumerable=t.literal(true);n.configurable=t.literal(true);r.each(n,function(e,n){if(n[0]==="_")return;e=r.clone(e);var a=e;if(t.isMethodDefinition(e))e=e.value;var i=t.property("init",t.identifier(n),e);t.inheritsComments(i,a);t.removeComments(a);l.properties.push(i)});e.properties.push(a)});return e};var p={enter:function(e,l,a,i,n){if(t.isIdentifier(e)&&r.has(n,e.name)){return n[e.name]}}};e.template=function(s,a,o){var n=e.templates[s];if(!n)throw new ReferenceError("unknown template "+s);if(a===true){o=true;a=null}n=r.cloneDeep(n);if(!r.isEmpty(a)){l(n,p,null,a)}var i=n.body[0];if(!o&&t.isExpressionStatement(i)){return i.expression}else{return i}};e.codeFrame=function(n,t,r){r=Math.max(r,0);n=n.split("\n");var l=Math.max(t-3,0);var a=Math.min(n.length,t+3);var i=(a+"").length;if(!t&&!r){l=0;a=n.length}return"\n"+n.slice(l,a).map(function(o,u){var a=u+l+1;var s=a===t?"> ":" ";var c=a+e.repeat(i+1);s+=c+"| ";var n=s+o;if(r&&a===t){n+="\n";n+=e.repeat(s.length-2);n+="|"+e.repeat(r)+"^"}return n}).join("\n")};e.repeat=function(r,e){e=e||" ";var n="";for(var t=0;t<r;t++){n+=e}return n};e.normaliseAst=function(e,n,r){if(e&&e.type==="Program"){return t.file(e,n||[],r||[])}else{throw new Error("Not a valid ast?")}};e.parse=function(r,o,u){try{var l=[];var a=[];var t=c.parse(o,{allowImportExportEverywhere:true,allowReturnOutsideFunction:true,ecmaVersion:r.experimental?7:6,playground:r.playground,strictMode:true,onComment:l,locations:true,onToken:a,ranges:true});f.attachComments(t,l,a);t=e.normaliseAst(t,l,a);if(u){return u(t)}else{return t}}catch(n){if(!n._6to5){n._6to5=true;var i=r.filename+": "+n.message;var s=n.loc;if(s){var p=e.codeFrame(o,s.line,s.column);i+=p}if(n.stack)n.stack=n.stack.replace(n.message,i);n.message=i}throw n}};e.parseTemplate=function(n,t){var r=e.parse({filename:n},t).program;return l.removeProperties(r)};var d=function(){var t={};var n=o+"/transformation/templates";if(!i.existsSync(n)){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")}r.each(i.readdirSync(n),function(r){if(r[0]===".")return;var s=a.basename(r,a.extname(r));var l=n+"/"+r;var o=i.readFileSync(l,"utf8");t[s]=e.parseTemplate(l,o)});return t};try{e.templates=n("../../templates.json")}catch(s){if(s.code!=="MODULE_NOT_FOUND")throw s;e.templates=d()}}).call(this,n("buffer").Buffer,"/lib/6to5")},{"../../templates.json":198,"./patch":24,"./traverse":88,"./types":92,"acorn-6to5":1,buffer:111,estraverse:136,fs:109,lodash:142,path:118,util:134}],95:[function(u,v,x){var s=u("../lib/types");var o=s.Type;var e=o.def;var n=o.or;var a=s.builtInTypes;var l=a.string;var p=a.number;var r=a.boolean;var f=a.RegExp;var c=u("../lib/shared");var t=c.defaults;var i=c.geq;e("Printable").field("loc",n(e("SourceLocation"),null),t["null"],true);e("Node").bases("Printable").field("type",l);e("SourceLocation").build("start","end","source").field("start",e("Position")).field("end",e("Position")).field("source",n(l,null),t["null"]);e("Position").build("line","column").field("line",i(1)).field("column",i(0));e("Program").bases("Node").build("body").field("body",[e("Statement")]).field("comments",n([n(e("Block"),e("Line"))],null),t["null"],true);e("Function").bases("Node").field("id",n(e("Identifier"),null),t["null"]).field("params",[e("Pattern")]).field("body",n(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",n(e("Statement"),null),t["null"]);e("LabeledStatement").bases("Statement").build("label","body").field("label",e("Identifier")).field("body",e("Statement"));e("BreakStatement").bases("Statement").build("label").field("label",n(e("Identifier"),null),t["null"]);e("ContinueStatement").bases("Statement").build("label").field("label",n(e("Identifier"),null),t["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",r,t["false"]);e("ReturnStatement").bases("Statement").build("argument").field("argument",n(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",n(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")],t.emptyArray).field("finalizer",n(e("BlockStatement"),null),t["null"]);e("CatchClause").bases("Node").build("param","guard","body").field("param",e("Pattern")).field("guard",n(e("Expression"),null),t["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",n(e("VariableDeclaration"),e("Expression"),null)).field("test",n(e("Expression"),null)).field("update",n(e("Expression"),null)).field("body",e("Statement"));e("ForInStatement").bases("Statement").build("left","right","body","each").field("left",n(e("VariableDeclaration"),e("Expression"))).field("right",e("Expression")).field("body",e("Statement")).field("each",r);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",n("var","let","const")).field("declarations",[n(e("VariableDeclarator"),e("Identifier"))]);e("VariableDeclarator").bases("Node").build("id","init").field("id",e("Pattern")).field("init",n(e("Expression"),null));e("Expression").bases("Node","Pattern");e("ThisExpression").bases("Expression").build();e("ArrayExpression").bases("Expression").build("elements").field("elements",[n(e("Expression"),null)]);e("ObjectExpression").bases("Expression").build("properties").field("properties",[e("Property")]);e("Property").bases("Node").build("kind","key","value").field("kind",n("init","get","set")).field("key",n(e("Literal"),e("Identifier"))).field("value",e("Expression"));e("SequenceExpression").bases("Expression").build("expressions").field("expressions",[e("Expression")]);var d=n("-","+","!","~","typeof","void","delete");e("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",d).field("argument",e("Expression")).field("prefix",r,t["true"]);var m=n("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");e("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",m).field("left",e("Expression")).field("right",e("Expression"));var h=n("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");e("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",h).field("left",e("Pattern")).field("right",e("Expression"));var g=n("++","--");e("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",g).field("argument",e("Expression")).field("prefix",r);var y=n("||","&&");e("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",y).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",n(e("Identifier"),e("Expression"))).field("computed",r);e("Pattern").bases("Node");e("ObjectPattern").bases("Pattern").build("properties").field("properties",[e("PropertyPattern")]);e("PropertyPattern").bases("Pattern").build("key","pattern").field("key",n(e("Literal"),e("Identifier"))).field("pattern",e("Pattern"));e("ArrayPattern").bases("Pattern").build("elements").field("elements",[n(e("Pattern"),null)]);e("SwitchCase").bases("Node").build("test","consequent").field("test",n(e("Expression"),null)).field("consequent",[e("Statement")]);e("Identifier").bases("Node","Expression","Pattern").build("name").field("name",l);e("Literal").bases("Node","Expression").build("value").field("value",n(l,r,null,p,f));e("Block").bases("Printable").build("loc","value").field("value",l);e("Line").bases("Printable").build("loc","value").field("value",l)},{"../lib/shared":106,"../lib/types":107}],96:[function(l,s,o){l("./core");var r=l("../lib/types");var e=r.Type.def;var t=r.Type.or;var a=r.builtInTypes;var n=a.string;var i=a.boolean;e("XMLDefaultDeclaration").bases("Declaration").field("namespace",e("Expression"));e("XMLAnyName").bases("Expression");e("XMLQualifiedIdentifier").bases("Expression").field("left",t(e("Identifier"),e("XMLAnyName"))).field("right",t(e("Identifier"),e("Expression"))).field("computed",i);e("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",t(e("Identifier"),e("Expression"))).field("computed",i);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",n);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",t(n,[e("XML")]));e("XMLAttribute").bases("XML").field("value",n);e("XMLCdata").bases("XML").field("contents",n);e("XMLComment").bases("XML").field("contents",n);e("XMLProcessingInstruction").bases("XML").field("target",n).field("contents",t(n,null))},{"../lib/types":107,"./core":95}],97:[function(s,c,f){s("./core");var a=s("../lib/types");var e=a.Type.def;var n=a.Type.or;var l=a.builtInTypes;var r=l.boolean;var u=l.object;var i=l.string;var t=s("../lib/shared").defaults;e("Function").field("generator",r,t["false"]).field("expression",r,t["false"]).field("defaults",[n(e("Expression"),null)],t.emptyArray).field("rest",n(e("Identifier"),null),t["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,t["null"]).field("generator",false);e("YieldExpression").bases("Expression").build("argument","delegate").field("argument",n(e("Expression"),null)).field("delegate",r,t["false"]);e("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",e("Expression")).field("blocks",[e("ComprehensionBlock")]).field("filter",n(e("Expression"),null));e("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",e("Expression")).field("blocks",[e("ComprehensionBlock")]).field("filter",n(e("Expression"),null));e("ComprehensionBlock").bases("Node").build("left","right","each").field("left",e("Pattern")).field("right",e("Expression")).field("each",r);e("ModuleSpecifier").bases("Literal").build("value").field("value",i);e("Property").field("key",n(e("Literal"),e("Identifier"),e("Expression"))).field("method",r,t["false"]).field("shorthand",r,t["false"]).field("computed",r,t["false"]);e("PropertyPattern").field("key",n(e("Literal"),e("Identifier"),e("Expression"))).field("computed",r,t["false"]);e("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",n("init","get","set","")).field("key",n(e("Literal"),e("Identifier"),e("Expression"))).field("value",e("Function")).field("computed",r,t["false"]);e("SpreadElement").bases("Node").build("argument").field("argument",e("Expression"));e("ArrayExpression").field("elements",[n(e("Expression"),e("SpreadElement"),null)]);e("NewExpression").field("arguments",[n(e("Expression"),e("SpreadElement"))]);e("CallExpression").field("arguments",[n(e("Expression"),e("SpreadElement"))]);e("SpreadElementPattern").bases("Pattern").build("argument").field("argument",e("Pattern"));var o=n(e("MethodDefinition"),e("VariableDeclarator"),e("ClassPropertyDefinition"),e("ClassProperty"));e("ClassProperty").bases("Declaration").build("key").field("key",n(e("Literal"),e("Identifier"),e("Expression"))).field("computed",r,t["false"]);e("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",o);e("ClassBody").bases("Declaration").build("body").field("body",[o]);e("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",e("Identifier")).field("body",e("ClassBody")).field("superClass",n(e("Expression"),null),t["null"]);e("ClassExpression").bases("Expression").build("id","body","superClass").field("id",n(e("Identifier"),null),t["null"]).field("body",e("ClassBody")).field("superClass",n(e("Expression"),null),t["null"]).field("implements",[e("ClassImplements")],t.emptyArray);e("ClassImplements").bases("Node").build("id").field("id",e("Identifier")).field("superClass",n(e("Expression"),null),t["null"]);e("Specifier").bases("Node");e("NamedSpecifier").bases("Specifier").field("id",e("Identifier")).field("name",n(e("Identifier"),null),t["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",r).field("declaration",n(e("Declaration"),e("Expression"),null)).field("specifiers",[n(e("ExportSpecifier"),e("ExportBatchSpecifier"))],t.emptyArray).field("source",n(e("ModuleSpecifier"),null),t["null"]);e("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[n(e("ImportSpecifier"),e("ImportNamespaceSpecifier"),e("ImportDefaultSpecifier"))],t.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:i,raw:i}).field("tail",r)},{"../lib/shared":106,"../lib/types":107,"./core":95}],98:[function(n,s,o){n("./core");var t=n("../lib/types");var e=t.Type.def;var r=t.Type.or;var i=t.builtInTypes;var l=i.boolean;var a=n("../lib/shared").defaults;e("Function").field("async",l,a["false"]);e("SpreadProperty").bases("Node").build("argument").field("argument",e("Expression"));e("ObjectExpression").field("properties",[r(e("Property"),e("SpreadProperty"))]);e("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",e("Pattern"));e("ObjectPattern").field("properties",[r(e("PropertyPattern"),e("SpreadPropertyPattern"))]);e("AwaitExpression").bases("Expression").build("argument","all").field("argument",r(e("Expression"),null)).field("all",l,a["false"])},{"../lib/shared":106,"../lib/types":107,"./core":95}],99:[function(a,c,f){a("./core");var s=a("../lib/types");var e=s.Type.def;var n=s.Type.or;var u=s.builtInTypes;var l=u.string;var r=u.boolean;var t=a("../lib/shared").defaults;e("XJSAttribute").bases("Node").build("name","value").field("name",n(e("XJSIdentifier"),e("XJSNamespacedName"))).field("value",n(e("Literal"),e("XJSExpressionContainer"),null),t["null"]);e("XJSIdentifier").bases("Node").build("name").field("name",l);e("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",e("XJSIdentifier")).field("name",e("XJSIdentifier"));e("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",n(e("XJSIdentifier"),e("XJSMemberExpression"))).field("property",e("XJSIdentifier")).field("computed",r,t.false);var i=n(e("XJSIdentifier"),e("XJSNamespacedName"),e("XJSMemberExpression"));e("XJSSpreadAttribute").bases("Node").build("argument").field("argument",e("Expression"));var o=[n(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",n(e("XJSClosingElement"),null),t["null"]).field("children",[n(e("XJSElement"),e("XJSExpressionContainer"),e("XJSText"),e("Literal"))],t.emptyArray).field("name",i,function(){return this.openingElement.name}).field("selfClosing",r,function(){return this.openingElement.selfClosing}).field("attributes",o,function(){return this.openingElement.attributes});e("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",i).field("attributes",o,t.emptyArray).field("selfClosing",r,t["false"]);e("XJSClosingElement").bases("Node").build("name").field("name",i);e("XJSText").bases("Literal").build("value").field("value",l);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",l).field("raw",l);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",n(e("FunctionTypeParam"),null)).field("typeParameters",n(e("TypeParameterDeclaration"),null));e("FunctionTypeParam").bases("Node").build("name","typeAnnotation","optional").field("name",e("Identifier")).field("typeAnnotation",e("Type")).field("optional",r);e("ObjectTypeAnnotation").bases("Type").build("properties").field("properties",[e("ObjectTypeProperty")]).field("indexers",[e("ObjectTypeIndexer")],t.emptyArray).field("callProperties",[e("ObjectTypeCallProperty")],t.emptyArray);
e("ObjectTypeProperty").bases("Node").build("key","value","optional").field("key",n(e("Literal"),e("Identifier"))).field("value",e("Type")).field("optional",r);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",r,false);e("QualifiedTypeIdentifier").bases("Node").build("qualification","id").field("qualification",n(e("Identifier"),e("QualifiedTypeIdentifier"))).field("id",e("Identifier"));e("GenericTypeAnnotation").bases("Type").build("id","typeParameters").field("id",n(e("Identifier"),e("QualifiedTypeIdentifier"))).field("typeParameters",n(e("TypeParameterInstantiation"),null));e("MemberTypeAnnotation").bases("Type").build("object","property").field("object",e("Identifier")).field("property",n(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",n(e("TypeAnnotation"),null),t["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",n(e("TypeAnnotation"),null),t["null"]).field("typeParameters",n(e("TypeParameterDeclaration"),null),t["null"]);e("ClassProperty").build("key","typeAnnotation").field("typeAnnotation",e("TypeAnnotation")).field("static",r,false);e("ClassImplements").field("typeParameters",n(e("TypeParameterInstantiation"),null),t["null"]);e("InterfaceDeclaration").bases("Statement").build("id","body","extends").field("id",e("Identifier")).field("typeParameters",n(e("TypeParameterDeclaration"),null),t["null"]).field("body",e("ObjectTypeAnnotation")).field("extends",[e("InterfaceExtends")]);e("InterfaceExtends").bases("Node").build("id").field("id",e("Identifier")).field("typeParameters",n(e("TypeParameterInstantiation"),null));e("TypeAlias").bases("Statement").build("id","typeParameters","right").field("id",e("Identifier")).field("typeParameters",n(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",n(e("Identifier"),e("Literal"))).field("body",e("BlockStatement"))},{"../lib/shared":106,"../lib/types":107,"./core":95}],100:[function(n,a,i){n("./core");var t=n("../lib/types");var e=t.Type.def;var l=t.Type.or;var r=n("../lib/shared").geq;e("ForOfStatement").bases("Statement").build("left","right","body").field("left",l(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",r(0)).field("expression",e("Literal"));e("GraphIndexExpression").bases("Expression").build("index").field("index",r(0))},{"../lib/shared":106,"../lib/types":107,"./core":95}],101:[function(s,p,g){var n=s("assert");var e=s("../main");var o=e.getFieldNames;var i=e.getFieldValue;var t=e.builtInTypes.array;var r=e.builtInTypes.object;var u=e.builtInTypes.Date;var c=e.builtInTypes.RegExp;var f=Object.prototype.hasOwnProperty;function a(n,r,e){if(t.check(e)){e.length=0}else{e=null}return l(n,r,e)}a.assert=function(t,r){var e=[];if(!a(t,r,e)){if(e.length===0){n.strictEqual(t,r)}else{n.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 l(e,n,l){if(e===n){return true}if(t.check(e)){return m(e,n,l)}if(r.check(e)){return h(e,n,l)}if(u.check(e)){return u.check(n)&&+e===+n}if(c.check(e)){return c.check(n)&&(e.source===n.source&&e.global===n.global&&e.multiline===n.multiline&&e.ignoreCase===n.ignoreCase)}return e==n}function m(a,i,r){t.assert(a);var s=a.length;if(!t.check(i)||i.length!==s){if(r){r.push("length")}return false}for(var e=0;e<s;++e){if(r){r.push(e)}if(e in a!==e in i){return false}if(!l(a[e],i[e],r)){return false}if(r){n.strictEqual(r.pop(),e)}}return true}function h(s,c,t){r.assert(s);if(!r.check(c)){return false}if(s.type!==c.type){if(t){t.push("type")}return false}var d=o(s);var p=d.length;var m=o(c);var h=m.length;if(p===h){for(var e=0;e<p;++e){var a=d[e];var g=i(s,a);var y=i(c,a);if(t){t.push(a)}if(!l(g,y,t)){return false}if(t){n.strictEqual(t.pop(),a)}}return true}if(!t){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(!f.call(u,a)){t.push(a);return false}delete u[a]}for(a in u){t.push(a);break}return false}p.exports=a},{"../main":108,assert:110}],102:[function(l,f,x){var n=l("assert");var r=l("./types");var e=r.namedTypes;var c=r.builders;var m=r.builtInTypes.number;var p=r.builtInTypes.array;var o=l("./path");var u=l("./scope");function a(e,t,r){n.ok(this instanceof a);o.call(this,e,t,r)}l("util").inherits(a,o);var t=a.prototype;Object.defineProperties(t,{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}}});t.replace=function(){delete this.node;delete this.parent;delete this.scope;return o.prototype.replace.apply(this,arguments)};t.prune=function(){var e=this.parent;this.replace();return g(e)};t._computeNode=function(){var n=this.value;if(e.Node.check(n)){return n}var t=this.parentPath;return t&&t.node||null};t._computeParent=function(){var t=this.value;var n=this.parentPath;if(!e.Node.check(t)){while(n&&!e.Node.check(n.value)){n=n.parentPath}if(n){n=n.parentPath}}while(n&&!e.Node.check(n.value)){n=n.parentPath}return n||null};t._computeScope=function(){var t=this.value;var r=this.parentPath;var n=r&&r.scope;if(e.Node.check(t)&&u.isEstablishedBy(t)){n=new u(this,n)}return n||null};t.getValueProperty=function(e){return r.getFieldValue(this.value,e)};t.needsParens=function(o){var l=this.parentPath;if(!l){return false}var r=this.value;if(!e.Expression.check(r)){return false}if(r.type==="Identifier"){return false}while(!e.Node.check(l.value)){l=l.parentPath;if(!l){return false}}var t=l.value;switch(r.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return t.type==="MemberExpression"&&this.name==="object"&&t.object===r;case"BinaryExpression":case"LogicalExpression":switch(t.type){case"CallExpression":return this.name==="callee"&&t.callee===r;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&t.object===r;case"BinaryExpression":case"LogicalExpression":var u=t.operator;var l=s[u];var c=r.operator;var a=s[c];if(l>a){return true}if(l===a&&this.name==="right"){n.strictEqual(t.right,r);return true}default:return false}case"SequenceExpression":switch(t.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(t.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 t.type==="MemberExpression"&&m.check(r.value)&&this.name==="object"&&t.object===r;case"AssignmentExpression":case"ConditionalExpression":switch(t.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&t.callee===r;case"ConditionalExpression":return this.name==="test"&&t.test===r;case"MemberExpression":return this.name==="object"&&t.object===r;default:return false}default:if(t.type==="NewExpression"&&this.name==="callee"&&t.callee===r){return i(r)}}if(o!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function d(n){return e.BinaryExpression.check(n)||e.LogicalExpression.check(n)}function v(n){return e.UnaryExpression.check(n)||e.SpreadElement&&e.SpreadElement.check(n)||e.SpreadProperty&&e.SpreadProperty.check(n)}var s={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,n){e.forEach(function(e){s[e]=n})});function i(n){if(e.CallExpression.check(n)){return true}if(p.check(n)){return n.some(i)}if(e.Node.check(n)){return r.someField(n,function(n,e){return i(e)})}return false}t.canBeFirstInStatement=function(){var n=this.node;return!e.FunctionExpression.check(n)&&!e.ObjectExpression.check(n)};t.firstInStatement=function(){return h(this)};function h(r){for(var l,t;r.parent;r=r.parent){l=r.node;t=r.parent.node;if(e.BlockStatement.check(t)&&r.parent.name==="body"&&r.name===0){n.strictEqual(t.body[0],l);return true}if(e.ExpressionStatement.check(t)&&r.name==="expression"){n.strictEqual(t.expression,l);return true}if(e.SequenceExpression.check(t)&&r.parent.name==="expressions"&&r.name===0){n.strictEqual(t.expressions[0],l);continue}if(e.CallExpression.check(t)&&r.name==="callee"){n.strictEqual(t.callee,l);continue}if(e.MemberExpression.check(t)&&r.name==="object"){n.strictEqual(t.object,l);continue}if(e.ConditionalExpression.check(t)&&r.name==="test"){n.strictEqual(t.test,l);continue}if(d(t)&&r.name==="left"){n.strictEqual(t.left,l);continue}if(e.UnaryExpression.check(t)&&!t.prefix&&r.name==="argument"){n.strictEqual(t.argument,l);continue}return false}return true}function g(n){if(e.VariableDeclaration.check(n.node)){var t=n.get("declarations").value;if(!t||t.length===0){return n.prune()}}else if(e.ExpressionStatement.check(n.node)){if(!n.get("expression").value){return n.prune()}}else if(e.IfStatement.check(n.node)){y(n)}return n}function y(n){var t=n.get("test").value;var r=n.get("alternate").value;var l=n.get("consequent").value;if(!l&&!r){var i=c.expressionStatement(t);n.replace(i)}else if(!l&&r){var a=c.unaryExpression("!",t,true);if(e.UnaryExpression.check(t)&&t.operator==="!"){a=t.argument}n.get("test").replace(a);n.get("consequent").replace(r);n.get("alternate").replace()}}f.exports=a},{"./path":104,"./scope":105,"./types":107,assert:110,util:134}],103:[function(s,m,x){var e=s("assert");var l=s("./types");var t=s("./node-path");var v=l.namedTypes.Node;var p=l.builtInTypes.array;var u=l.builtInTypes.object;var o=l.builtInTypes.function;var c=Object.prototype.hasOwnProperty;var g;function n(){e.ok(this instanceof n);this._reusableContextStack=[];this._methodNameTable=d(this);this.Context=y(this);this._visiting=false;this._changeReported=false}function d(r){var n=Object.create(null);for(var e in r){if(/^visit[A-Z]/.test(e)){n[e.slice("visit".length)]=true}}var a=l.computeSupertypeLookupTable(n);var i=Object.create(null);var n=Object.keys(a);var u=n.length;for(var t=0;t<u;++t){var s=n[t];e="visit"+a[s];if(o.check(r[e])){i[s]=e}}return i}n.fromMethodsObject=function b(l){if(l instanceof n){return l}if(!u.check(l)){return new n}function t(){e.ok(this instanceof t);n.call(this)}var a=t.prototype=Object.create(r);a.constructor=t;i(a,l);i(t,n);o.assert(t.fromMethodsObject);o.assert(t.visit);return new t};function i(t,e){for(var n in e){if(c.call(e,n)){t[n]=e[n]}}return t}n.visit=function E(e,t){return n.fromMethodsObject(t).visit(e)};var r=n.prototype;var h=["Recursively calling visitor.visit(path) resets visitor state.","Try this.visit(path) or this.traverse(path) instead."].join(" ");r.visit=function(){e.ok(!this._visiting,h);this._visiting=true;this._changeReported=false;var l=arguments.length;var n=new Array(l);for(var r=0;r<l;++r){n[r]=arguments[r]}if(!(n[0]instanceof t)){n[0]=new t({root:n[0]}).get("root")}this.reset.apply(this,n);try{return this.visitWithoutReset(n[0])}finally{this._visiting=false}};r.reset=function(e){};r.visitWithoutReset=function(n){if(this instanceof this.Context){return this.visitor.visitWithoutReset(n)}e.ok(n instanceof t);var r=n.value;var l=v.check(r)&&this._methodNameTable[r.type];if(l){var a=this.acquireContext(n);try{return a.invokeVisitorMethod(l)}finally{this.releaseContext(a)}}else{return f(n,this)}};function f(i,s){e.ok(i instanceof t);e.ok(s instanceof n);var r=i.value;if(p.check(r)){i.each(s.visitWithoutReset,s)}else if(!u.check(r)){}else{var f=l.getFieldNames(r);var d=f.length;var m=[];for(var a=0;a<d;++a){var o=f[a];if(!c.call(r,o)){r[o]=l.getFieldValue(r,o)}m.push(i.get(o))}for(var a=0;a<d;++a){s.visitWithoutReset(m[a])}}return i.value}r.acquireContext=function(e){if(this._reusableContextStack.length===0){return new this.Context(e)}return this._reusableContextStack.pop().reset(e)};r.releaseContext=function(n){e.ok(n instanceof this.Context);this._reusableContextStack.push(n);n.currentPath=null};r.reportChanged=function(){this._changeReported=true};r.wasChangeReported=function(){return this._changeReported};function y(l){function r(a){e.ok(this instanceof r);e.ok(this instanceof n);e.ok(a instanceof t);Object.defineProperty(this,"visitor",{value:l,writable:false,enumerable:true,configurable:false});this.currentPath=a;this.needToCallTraverse=true;Object.seal(this)}e.ok(l instanceof n);var s=r.prototype=Object.create(l);s.constructor=r;i(s,a);return r}var a=Object.create(null);a.reset=function w(n){e.ok(this instanceof this.Context);e.ok(n instanceof t);this.currentPath=n;this.needToCallTraverse=true;return this};a.invokeVisitorMethod=function _(r){e.ok(this instanceof this.Context);e.ok(this.currentPath instanceof t);var n=this.visitor[r].call(this,this.currentPath);if(n===false){this.needToCallTraverse=false}else if(n!==g){this.currentPath=this.currentPath.replace(n)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}e.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+r);var l=this.currentPath;return l&&l.value};a.traverse=function S(r,l){e.ok(this instanceof this.Context);e.ok(r instanceof t);e.ok(this.currentPath instanceof t);this.needToCallTraverse=false;return f(r,n.fromMethodsObject(l||this.visitor))};a.visit=function k(r,l){e.ok(this instanceof this.Context);e.ok(r instanceof t);e.ok(this.currentPath instanceof t);this.needToCallTraverse=false;return n.fromMethodsObject(l||this.visitor).visitWithoutReset(r)};a.reportChanged=function I(){this.visitor.reportChanged()};m.exports=n},{"./node-path":102,"./types":107,assert:110}],104:[function(c,p,v){var n=c("assert");var m=Object.prototype;var i=m.hasOwnProperty;var u=c("./types");var r=u.builtInTypes.array;var f=u.builtInTypes.number;var o=Array.prototype;var y=o.slice;var g=o.map;function l(r,e,t){n.ok(this instanceof l);if(e){n.ok(e instanceof l)}else{e=null;t=null}this.value=r;this.parentPath=e;this.name=t;this.__childCache=null}var e=l.prototype;function t(e){return e.__childCache||(e.__childCache=Object.create(null))}function d(n,e){var r=t(n);var a=n.getValueProperty(e);var l=r[e];if(!i.call(r,e)||l.value!==a){l=r[e]=new n.constructor(a,n,e)}return l}e.getValueProperty=function x(e){return this.value[e]};e.get=function b(l){var e=this;var t=arguments;var r=t.length;for(var n=0;n<r;++n){e=d(e,t[n])}return e};e.each=function E(l,n){var t=[];var r=this.value.length;var e=0;for(var e=0;e<r;++e){if(i.call(this.value,e)){t[e]=this.get(e)}}n=n||this;for(e=0;e<r;++e){if(i.call(t,e)){l.call(n,t[e])}}};e.map=function w(n,t){var e=[];this.each(function(t){e.push(n.call(this,t))},t);return e};e.filter=function _(n,t){var e=[];this.each(function(t){if(n.call(this,t)){e.push(t)}},t);return e};function s(){}function a(a,h,e,o){r.assert(a.value);if(h===0){return s}var u=a.value.length;if(u<1){return s}var g=arguments.length;if(g===2){e=0;o=u}else if(g===3){e=Math.max(e,0);o=u}else{e=Math.max(e,0);o=Math.min(o,u)}f.assert(e);f.assert(o);var c=Object.create(null);var p=t(a);for(var l=e;l<o;++l){if(i.call(a.value,l)){var d=a.get(l);n.strictEqual(d.name,l);var m=l+h;d.name=m;c[m]=d;delete p[l]}}delete p.length;return function(){for(var e in c){var t=c[e];n.strictEqual(t.name,+e);p[e]=t;a.value[e]=t.value}}}e.shift=function S(){var e=a(this,-1);var n=this.value.shift();e();return n};e.unshift=function k(t){var e=a(this,arguments.length);var n=this.value.unshift.apply(this.value,arguments);e();return n};e.push=function I(e){r.assert(this.value);delete t(this).length;return this.value.push.apply(this.value,arguments)};e.pop=function R(){r.assert(this.value);var e=t(this);delete e[this.value.length-1];delete e.length;return this.value.pop()};e.insertAt=function C(e,l){var t=arguments.length;var r=a(this,t-1,e);if(r===s){return this}e=Math.max(e,0);for(var n=1;n<t;++n){this.value[e+n-1]=arguments[n]}r();return this};e.insertBefore=function A(l){var n=this.parentPath;var r=arguments.length;var t=[this.name];for(var e=0;e<r;++e){t.push(arguments[e])}return n.insertAt.apply(n,t)};e.insertAfter=function T(l){var n=this.parentPath;var r=arguments.length;var t=[this.name+1];for(var e=0;e<r;++e){t.push(arguments[e])}return n.insertAt.apply(n,t)};function h(e){n.ok(e instanceof l);var i=e.parentPath;if(!i){return e}var a=i.value;var s=t(i);if(a[e.name]===e.value){s[e.name]=e}else if(r.check(a)){var o=a.indexOf(e.value);if(o>=0){s[e.name=o]=e}}else{a[e.name]=e.value;s[e.name]=e}n.strictEqual(a[e.name],e.value);n.strictEqual(e.parentPath.get(e.name),e);return e}e.replace=function L(s){var o=[];var e=this.parentPath.value;var p=t(this.parentPath);var l=arguments.length;h(this);if(r.check(e)){var c=e.length;var f=a(this.parentPath,l-1,this.name+1);var u=[this.name,1];for(var i=0;i<l;++i){u.push(arguments[i])}var d=e.splice.apply(e,u);n.strictEqual(d[0],this.value);n.strictEqual(e.length,c-1+l);f();if(l===0){delete this.value;delete p[this.name];this.__childCache=null}else{n.strictEqual(e[this.name],s);if(this.value!==s){this.value=s;this.__childCache=null}for(i=0;i<l;++i){o.push(this.parentPath.get(this.name+i))}n.strictEqual(o[0],this)}}else if(l===1){if(this.value!==s){this.__childCache=null}this.value=e[this.name]=s;o.push(this)}else if(l===0){delete e[this.name];delete this.value;this.__childCache=null}else{n.ok(false,"Could not replace path")}return o};p.exports=l},{"./types":107,assert:110}],105:[function(o,m,x){var l=o("assert");var r=o("./types");var d=r.Type;var e=r.namedTypes;var y=e.Node;var p=e.Expression;var h=r.builtInTypes.array;var c=Object.prototype.hasOwnProperty;var f=r.builders;function a(n,e){l.ok(this instanceof a);l.ok(n instanceof o("./node-path"));s.assert(n.value);var t;if(e){l.ok(e instanceof a);t=e.depth+1}else{e=null;t=0}Object.defineProperties(this,{path:{value:n},node:{value:n.value},isGlobal:{value:!e,enumerable:true},depth:{value:t},parent:{value:e},bindings:{value:{}}})}var g=[e.Program,e.Function,e.CatchClause];var s=d.or.apply(d,g);a.isEstablishedBy=function(e){return s.check(e)};var t=a.prototype;t.didScan=false;t.declares=function(e){this.scan();return c.call(this.bindings,e)};t.declareTemporary=function(e){if(e){l.ok(/^[a-z$_]/i.test(e),e)}else{e="t$"}e+=this.depth.toString(36)+"$";this.scan();var n=0;while(this.declares(e+n)){++n}var t=e+n;return this.bindings[t]=r.builders.identifier(t)};t.injectTemporary=function(n,r){n||(n=this.declareTemporary());var t=this.path.get("body");if(e.BlockStatement.check(t.value)){t=t.get("body")}t.unshift(f.variableDeclaration("var",[f.variableDeclarator(n,r||null)]));return n};t.scan=function(e){if(e||!this.didScan){for(var n in this.bindings){delete this.bindings[n]}v(this.path,this.bindings);this.didScan=true}};t.getBindings=function(){this.scan();return this.bindings};function v(t,r){var l=t.value;s.assert(l);if(e.CatchClause.check(l)){n(t.get("param"),r)}else{u(t,r)}}function u(t,s){var a=t.value;if(t.parent&&e.FunctionExpression.check(t.parent.node)&&t.parent.node.id){n(t.parent.get("id"),s)}if(!a){}else if(h.check(a)){t.each(function(e){i(e,s)})}else if(e.Function.check(a)){t.get("params").each(function(e){n(e,s)});i(t.get("body"),s)}else if(e.VariableDeclarator.check(a)){n(t.get("id"),s);i(t.get("init"),s)}else if(a.type==="ImportSpecifier"||a.type==="ImportNamespaceSpecifier"||a.type==="ImportDefaultSpecifier"){n(a.name?t.get("name"):t.get("id"),s)}else if(y.check(a)&&!p.check(a)){r.eachField(a,function(n,r){var e=t.get(n);l.strictEqual(e.value,r);i(e,s)})}}function i(l,r){var t=l.value;if(!t||p.check(t)){}else if(e.FunctionDeclaration.check(t)){n(l.get("id"),r)}else if(e.ClassDeclaration&&e.ClassDeclaration.check(t)){n(l.get("id"),r)}else if(s.check(t)){if(e.CatchClause.check(t)){var a=t.param.name;var i=c.call(r,a);u(l.get("body"),r);if(!i){delete r[a]}}}else{u(l,r)}}function n(r,l){var t=r.value;e.Pattern.assert(t);if(e.Identifier.check(t)){if(c.call(l,t.name)){l[t.name].push(r)}else{l[t.name]=[r]}}else if(e.SpreadElement&&e.SpreadElement.check(t)){n(r.get("argument"),l)}}t.lookup=function(n){for(var e=this;e;e=e.parent)if(e.declares(n))break;return e};t.getGlobalScope=function(){var e=this;while(!e.isGlobal)e=e.parent;return e};m.exports=a},{"./node-path":102,"./types":107,assert:110}],106:[function(a,s,n){var r=a("../lib/types");var t=r.Type;var e=r.builtInTypes;var l=e.number;n.geq=function(e){return new t(function(n){return l.check(n)&&n>=e},l+" >= "+e)};n.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var i=t.or(e.string,e.number,e.boolean,e.null,e.undefined);n.isPrimitive=new t(function(e){if(e===null)return true;var n=typeof e;return!(n==="object"||n==="function")},i.toString())},{"../lib/types":107}],107:[function(T,N,r){var e=T("assert");var E=Array.prototype;var A=E.slice;var F=E.map;var O=E.forEach;var k=Object.prototype;var o=k.toString;var v=o.call(function(){});var P=o.call("");var l=k.hasOwnProperty;function n(r,l){var t=this;e.ok(t instanceof n,t);e.strictEqual(o.call(r),v,r+" is not a function");var a=o.call(l);e.ok(a===v||a===P,l+" is neither a function nor a string");Object.defineProperties(t,{name:{value:l},check:{value:function(n,e){var l=r.call(t,n,e);if(!l&&e&&o.call(e)===v)e(t,n);return l}}})}var w=n.prototype;r.Type=n;w.assert=function(n,t){if(!this.check(n,t)){var r=h(n);e.ok(false,r+" does not match type "+this);return false}return true};function h(e){if(u.check(e))return"{"+Object.keys(e).map(function(n){return n+": "+e[n]}).join(", ")+"}";if(p.check(e))return"["+e.map(h).join(", ")+"]";return JSON.stringify(e)}w.toString=function(){var e=this.name;if(c.check(e))return e;if(f.check(e))return e.call(this)+"";return e+" type"};var g={};r.builtInTypes=g;function a(t,e){var r=o.call(t);Object.defineProperty(g,e,{enumerable:true,value:new n(function(e){return o.call(e)===r},e)});return g[e]}var c=a("","string");var f=a(function(){},"function");var p=a([],"array");var u=a({},"object");var B=a(/./,"RegExp");var U=a(new Date,"Date");var L=a(3,"number");var V=a(true,"boolean");var D=a(null,"null");var S=a(void 0,"undefined");function _(e,t){if(e instanceof n)return e;if(e instanceof s)return e.type;if(p.check(e))return n.fromArray(e);if(u.check(e))return n.fromObject(e);if(f.check(e))return new n(e,t);return new n(function(n){return n===e},S.check(t)?function(){return e+""}:t)}n.or=function(){var e=[];var r=arguments.length;for(var t=0;t<r;++t)e.push(_(arguments[t]));return new n(function(t,l){for(var n=0;n<r;++n)if(e[n].check(t,l))return true;return false},function(){return e.join(" | ")})};n.fromArray=function(n){e.ok(p.check(n));e.strictEqual(n.length,1,"only one element type is permitted for typed arrays");return _(n[0]).arrayOf()};w.arrayOf=function(){var e=this;return new n(function(n,t){return p.check(n)&&n.every(function(n){return e.check(n,t)})},function(){return"["+e+"]"})};n.fromObject=function(e){var t=Object.keys(e).map(function(n){return new m(n,e[n])});return new n(function(e,n){return u.check(e)&&t.every(function(t){return t.type.check(e[t.name],n)})},function(){return"{ "+t.join(", ")+" }"})};function m(t,n,r,i){var l=this;e.ok(l instanceof m);c.assert(t);n=_(n);var a={name:{value:t},type:{value:n},hidden:{value:!!i}};if(f.check(r)){a.defaultFn={value:r}}Object.defineProperties(l,a)}var I=m.prototype;I.toString=function(){return JSON.stringify(this.name)+": "+this.type};I.getValue=function(n){var e=n[this.name];if(!S.check(e))return e;if(this.defaultFn)e=this.defaultFn.call(n);return e};n.def=function(e){c.assert(e);return l.call(t,e)?t[e]:t[e]=new s(e)};var t=Object.create(null);function s(r){var t=this;e.ok(t instanceof s);Object.defineProperties(t,{typeName:{value:r},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new n(function(e,n){return t.check(e,n)},r)}})}s.fromValue=function(e){if(e&&typeof e==="object"){var n=e.type;if(typeof n==="string"&&l.call(t,n)){var r=t[n];if(r.finalized){return r}}}return null};var i=s.prototype;i.isSupertypeOf=function(n){if(n instanceof s){e.strictEqual(this.finalized,true);e.strictEqual(n.finalized,true);return l.call(n.allSupertypes,this.typeName)}else{e.ok(false,n+" is not a Def")}};r.getSupertypeNames=function(n){e.ok(l.call(t,n));var r=t[n];e.strictEqual(r.finalized,true);return r.supertypeList.slice(1)};r.computeSupertypeLookupTable=function(c){var i={};var s=Object.keys(t);var f=s.length;for(var n=0;n<f;++n){var o=s[n];var r=t[o];e.strictEqual(r.finalized,true);for(var a=0;a<r.supertypeList.length;++a){var u=r.supertypeList[a];if(l.call(c,u)){i[o]=u;break}}}return i};i.checkAllFields=function(n,r){var t=this.allFields;e.strictEqual(this.finalized,true);function l(l){var e=t[l];var a=e.type;var i=e.getValue(n);return a.check(i,r)}return u.check(n)&&Object.keys(t).every(l)};i.check=function(n,t){e.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!u.check(n))return false;var r=s.fromValue(n);if(!r){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(n,t)}return false}if(t&&r===this)return this.checkAllFields(n,t);if(!this.isSupertypeOf(r))return false;if(!t)return true;return r.checkAllFields(n,t)&&this.checkAllFields(n,false)};i.bases=function(){var n=this.baseNames;e.strictEqual(this.finalized,false);O.call(arguments,function(e){c.assert(e);if(n.indexOf(e)<0)n.push(e)});return this};Object.defineProperty(i,"buildable",{value:false});var C={};r.builders=C;var d={};r.defineMethod=function(e,n){var t=d[e];if(S.check(n)){delete d[e]}else{f.assert(n);Object.defineProperty(d,e,{enumerable:true,configurable:true,value:n})}return t};i.build=function(){var n=this;Object.defineProperty(n,"buildParams",{value:A.call(arguments),writable:false,enumerable:false,configurable:true});e.strictEqual(n.finalized,false);c.arrayOf().assert(n.buildParams);if(n.buildable){return n}n.field("type",n.typeName,function(){return n.typeName});Object.defineProperty(n,"buildable",{value:true});Object.defineProperty(C,j(n.typeName),{enumerable:true,value:function(){var r=arguments;var i=r.length;var t=Object.create(d);e.ok(n.finalized,"attempting to instantiate unfinalized type "+n.typeName);function a(a,u){if(l.call(t,a))return;var c=n.allFields;e.ok(l.call(c,a),a);var o=c[a];var f=o.type;var s;if(L.check(u)&&u<i){s=r[u]}else if(o.defaultFn){s=o.defaultFn.call(t)}else{var p="no value or default function given for field "+JSON.stringify(a)+" of "+n.typeName+"("+n.buildParams.map(function(e){return c[e]}).join(", ")+")";e.ok(false,p)}if(!f.check(s)){e.ok(false,h(s)+" does not match field "+o+" of type "+n.typeName)}t[a]=s}n.buildParams.forEach(function(e,n){a(e,n)});Object.keys(n.allFields).forEach(function(e){a(e)});e.strictEqual(t.type,n.typeName);return t}});return n};function j(e){return e.replace(/^[A-Z]+/,function(e){var n=e.length;switch(n){case 0:return"";case 1:return e.toLowerCase();default:return e.slice(0,n-1).toLowerCase()+e.charAt(n-1)}})}i.field=function(n,t,r,l){e.strictEqual(this.finalized,false);this.ownFields[n]=new m(n,t,r,l);return this};var R={};r.namedTypes=R;function x(n){var t=s.fromValue(n);if(t){return t.fieldNames.slice(0)}if("type"in n){e.ok(false,"did not recognize object of type "+JSON.stringify(n.type))}return Object.keys(n)}r.getFieldNames=x;function y(e,n){var t=s.fromValue(e);if(t){var r=t.allFields[n];if(r){return r.getValue(e)}}return e[n]}r.getFieldValue=y;r.eachField=function(e,n,t){x(e).forEach(function(t){n.call(this,t,y(e,t))},t)};r.someField=function(e,n,t){return x(e).some(function(t){return n.call(this,t,y(e,t))},t)};Object.defineProperty(i,"finalized",{value:false});i.finalize=function(){if(!this.finalized){var e=this.allFields;var r=this.allSupertypes;this.baseNames.forEach(function(l){var n=t[l];n.finalize();b(e,n.allFields);b(r,n.allSupertypes)});b(e,this.ownFields);r[this.typeName]=this;this.fieldNames.length=0;for(var n in e){if(l.call(e,n)&&!e[n].hidden){this.fieldNames.push(n)}}Object.defineProperty(R,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});M(this.typeName,this.supertypeList)}};function M(r,n){n.length=0;n.push(r);var s=Object.create(null);for(var a=0;a<n.length;++a){r=n[a];var u=t[r];e.strictEqual(u.finalized,true);if(l.call(s,r)){delete n[s[r]]}s[r]=a;n.push.apply(n,u.baseNames)}for(var o=0,i=o,c=n.length;i<c;++i){if(l.call(n,i)){n[o++]=n[i]}}n.length=o}function b(e,n){Object.keys(n).forEach(function(t){e[t]=n[t]});return e}r.finalize=function(){Object.keys(t).forEach(function(e){t[e].finalize()})}},{assert:110}],108:[function(t,r,e){var n=t("./lib/types");t("./def/core");t("./def/es6");t("./def/es7");t("./def/mozilla");t("./def/e4x");t("./def/fb-harmony");n.finalize();e.Type=n.Type;e.builtInTypes=n.builtInTypes;e.namedTypes=n.namedTypes;e.builders=n.builders;e.defineMethod=n.defineMethod;e.getFieldNames=n.getFieldNames;e.getFieldValue=n.getFieldValue;e.eachField=n.eachField;e.someField=n.someField;e.getSupertypeNames=n.getSupertypeNames;e.astNodesAreEquivalent=t("./lib/equiv");e.finalize=n.finalize;e.NodePath=t("./lib/node-path");e.PathVisitor=t("./lib/path-visitor");e.visit=e.PathVisitor.visit},{"./def/core":95,"./def/e4x":96,"./def/es6":97,"./def/es7":98,"./def/fb-harmony":99,"./def/mozilla":100,"./lib/equiv":101,"./lib/node-path":102,"./lib/path-visitor":103,"./lib/types":107}],109:[function(e,n,t){},{}],110:[function(h,p,y){var n=h("util/");var r=Array.prototype.slice;var d=Object.prototype.hasOwnProperty;var e=p.exports=o;e.AssertionError=function v(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=g(this);this.generatedMessage=true}var r=e.stackStartFunction||t;if(Error.captureStackTrace){Error.captureStackTrace(this,r)}else{var l=new Error;if(l.stack){var n=l.stack;var i=r.name;var a=n.indexOf("\n"+i);if(a>=0){var s=n.indexOf("\n",a+1);n=n.substring(s+1)}this.stack=n}}};n.inherits(e.AssertionError,Error);function u(t,e){if(n.isUndefined(e)){return""+e}if(n.isNumber(e)&&!isFinite(e)){return e.toString()}if(n.isFunction(e)||n.isRegExp(e)){return e.toString()}return e
}function a(e,t){if(n.isString(e)){return e.length<t?e:e.slice(0,t)}else{return e}}function g(e){return a(JSON.stringify(e.actual,u),128)+" "+e.operator+" "+a(JSON.stringify(e.expected,u),128)}function t(n,t,r,l,a){throw new e.AssertionError({message:r,actual:n,expected:t,operator:l,stackStartFunction:a})}e.fail=t;function o(n,r){if(!n)t(n,true,r,"==",e.ok)}e.ok=o;e.equal=function x(n,r,l){if(n!=r)t(n,r,l,"==",e.equal)};e.notEqual=function b(n,r,l){if(n==r){t(n,r,l,"!=",e.notEqual)}};e.deepEqual=function E(n,r,a){if(!l(n,r)){t(n,r,a,"deepEqual",e.deepEqual)}};function l(e,t){if(e===t){return true}else if(n.isBuffer(e)&&n.isBuffer(t)){if(e.length!=t.length)return false;for(var r=0;r<e.length;r++){if(e[r]!==t[r])return false}return true}else if(n.isDate(e)&&n.isDate(t)){return e.getTime()===t.getTime()}else if(n.isRegExp(e)&&n.isRegExp(t)){return e.source===t.source&&e.global===t.global&&e.multiline===t.multiline&&e.lastIndex===t.lastIndex&&e.ignoreCase===t.ignoreCase}else if(!n.isObject(e)&&!n.isObject(t)){return e==t}else{return m(e,t)}}function c(e){return Object.prototype.toString.call(e)=="[object Arguments]"}function m(e,t){if(n.isNullOrUndefined(e)||n.isNullOrUndefined(t))return false;if(e.prototype!==t.prototype)return false;if(n.isPrimitive(e)||n.isPrimitive(t)){return e===t}var o=c(e),p=c(t);if(o&&!p||!o&&p)return false;if(o){e=r.call(e);t=r.call(t);return l(e,t)}var i=s(e),u=s(t),f,a;if(i.length!=u.length)return false;i.sort();u.sort();for(a=i.length-1;a>=0;a--){if(i[a]!=u[a])return false}for(a=i.length-1;a>=0;a--){f=i[a];if(!l(e[f],t[f]))return false}return true}e.notDeepEqual=function w(n,r,a){if(l(n,r)){t(n,r,a,"notDeepEqual",e.notDeepEqual)}};e.strictEqual=function _(n,r,l){if(n!==r){t(n,r,l,"===",e.strictEqual)}};e.notStrictEqual=function S(n,r,l){if(n===r){t(n,r,l,"!==",e.notStrictEqual)}};function f(n,e){if(!n||!e){return false}if(Object.prototype.toString.call(e)=="[object RegExp]"){return e.test(n)}else if(n instanceof e){return true}else if(e.call({},n)===true){return true}return false}function i(a,i,e,l){var r;if(n.isString(e)){l=e;e=null}try{i()}catch(s){r=s}l=(e&&e.name?" ("+e.name+").":".")+(l?" "+l:".");if(a&&!r){t(r,e,"Missing expected exception"+l)}if(!a&&f(r,e)){t(r,e,"Got unwanted exception"+l)}if(a&&r&&e&&!f(r,e)||!a&&r){throw r}}e.throws=function(e,n,t){i.apply(this,[true].concat(r.call(arguments)))};e.doesNotThrow=function(e,n){i.apply(this,[false].concat(r.call(arguments)))};e.ifError=function(e){if(e){throw e}};var s=Object.keys||function(e){var n=[];for(var t in e){if(d.call(e,t))n.push(t)}return n}},{"util/":134}],111:[function(c,U,i){var u=c("base64-js");var l=c("ieee754");var f=c("is-array");i.Buffer=e;i.SlowBuffer=d;i.INSPECT_MAX_BYTES=50;e.poolSize=8192;var v=1073741823;var L={};e.TYPED_ARRAY_SUPPORT=function(){try{var n=new ArrayBuffer(0);var e=new Uint8Array(n);e.foo=function(){return 42};return 42===e.foo()&&typeof e.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(t){return false}}();function e(n,i,s){if(!(this instanceof e))return new e(n,i,s);var a=typeof n;var r;if(a==="number")r=n>0?n>>>0:0;else if(a==="string"){r=e.byteLength(n,i)}else if(a==="object"&&n!==null){if(n.type==="Buffer"&&f(n.data))n=n.data;r=+n.length>0?Math.floor(+n.length):0}else throw new TypeError("must start with number, buffer, array or string");if(r>v)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+v.toString(16)+" bytes");var l;if(e.TYPED_ARRAY_SUPPORT){l=e._augment(new Uint8Array(r))}else{l=this;l.length=r;l._isBuffer=true}var t;if(e.TYPED_ARRAY_SUPPORT&&typeof n.byteLength==="number"){l._set(n)}else if(j(n)){if(e.isBuffer(n)){for(t=0;t<r;t++)l[t]=n.readUInt8(t)}else{for(t=0;t<r;t++)l[t]=(n[t]%256+256)%256}}else if(a==="string"){l.write(n,0,i)}else if(a==="number"&&!e.TYPED_ARRAY_SUPPORT&&!s){for(t=0;t<r;t++){l[t]=0}}if(r>0&&r<=e.poolSize)l.parent=L;return l}function d(n,t,r){if(!(this instanceof d))return new d(n,t,r);var l=new e(n,t,r);delete l.parent;return l}e.isBuffer=function(e){return!!(e!=null&&e._isBuffer)};e.compare=function(t,r){if(!e.isBuffer(t)||!e.isBuffer(r))throw new TypeError("Arguments must be Buffers");var l=t.length;var a=r.length;for(var n=0,i=Math.min(l,a);n<i&&t[n]===r[n];n++){}if(n!==i){l=t[n];a=r[n]}if(l<a)return-1;if(a<l)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(n,r){if(!f(n))throw new TypeError("Usage: Buffer.concat(list[, length])");if(n.length===0){return new e(0)}else if(n.length===1){return n[0]}var t;if(r===undefined){r=0;for(t=0;t<n.length;t++){r+=n[t].length}}var l=new e(r);var a=0;for(t=0;t<n.length;t++){var i=n[t];i.copy(l,a);a+=i.length}return l};e.byteLength=function(e,t){var n;e=e+"";switch(t||"utf8"){case"ascii":case"binary":case"raw":n=e.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":n=e.length*2;break;case"hex":n=e.length>>>1;break;case"utf8":case"utf-8":n=p(e).length;break;case"base64":n=y(e).length;break;default:n=e.length}return n};e.prototype.length=undefined;e.prototype.parent=undefined;e.prototype.toString=function(t,n,e){var r=false;n=n>>>0;e=e===undefined||e===Infinity?this.length:e>>>0;if(!t)t="utf8";if(n<0)n=0;if(e>this.length)e=this.length;if(e<=n)return"";while(true){switch(t){case"hex":return B(this,n,e);case"utf8":case"utf-8":return k(this,n,e);case"ascii":return S(this,n,e);case"binary":return _(this,n,e);case"base64":return I(this,n,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return w(this,n,e);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase();r=true}}};e.prototype.equals=function(n){if(!e.isBuffer(n))throw new TypeError("Argument must be a Buffer");return e.compare(this,n)===0};e.prototype.inspect=function(){var e="";var n=i.INSPECT_MAX_BYTES;if(this.length>0){e=this.toString("hex",0,n).match(/.{2}/g).join(" ");if(this.length>n)e+=" ... "}return"<Buffer "+e+">"};e.prototype.compare=function(n){if(!e.isBuffer(n))throw new TypeError("Argument must be a Buffer");return e.compare(this,n)};e.prototype.get=function(e){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(e)};e.prototype.set=function(e,n){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(e,n)};function F(a,i,t,e){t=Number(t)||0;var r=a.length-t;if(!e){e=r}else{e=Number(e);if(e>r){e=r}}var l=i.length;if(l%2!==0)throw new Error("Invalid hex string");if(e>l/2){e=l/2}for(var n=0;n<e;n++){var s=parseInt(i.substr(n*2,2),16);if(isNaN(s))throw new Error("Invalid hex string");a[t+n]=s}return n}function O(e,t,n,r){var l=a(p(t,e.length-n),e,n,r);return l}function x(e,n,t,r){var l=a(D(n),e,t,r);return l}function A(e,n,t,r){return x(e,n,t,r)}function C(e,n,t,r){var l=a(y(n),e,t,r);return l}function R(e,t,n,r){var l=a(N(t,e.length-n),e,n,r,2);return l}e.prototype.write=function(l,n,e,t){if(isFinite(n)){if(!isFinite(e)){t=e;e=undefined}}else{var i=t;t=n;n=e;e=i}n=Number(n)||0;if(e<0||n<0||n>this.length)throw new RangeError("attempt to write outside buffer bounds");var a=this.length-n;if(!e){e=a}else{e=Number(e);if(e>a){e=a}}t=String(t||"utf8").toLowerCase();var r;switch(t){case"hex":r=F(this,l,n,e);break;case"utf8":case"utf-8":r=O(this,l,n,e);break;case"ascii":r=x(this,l,n,e);break;case"binary":r=A(this,l,n,e);break;case"base64":r=C(this,l,n,e);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":r=R(this,l,n,e);break;default:throw new TypeError("Unknown encoding: "+t)}return r};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function I(e,n,t){if(n===0&&t===e.length){return u.fromByteArray(e)}else{return u.fromByteArray(e.slice(n,t))}}function k(n,a,r){var l="";var t="";r=Math.min(n.length,r);for(var e=a;e<r;e++){if(n[e]<=127){l+=b(t)+String.fromCharCode(n[e]);t=""}else{t+="%"+n[e].toString(16)}}return l+b(t)}function S(t,l,e){var r="";e=Math.min(t.length,e);for(var n=l;n<e;n++){r+=String.fromCharCode(t[n]&127)}return r}function _(t,l,e){var r="";e=Math.min(t.length,e);for(var n=l;n<e;n++){r+=String.fromCharCode(t[n])}return r}function B(r,n,e){var l=r.length;if(!n||n<0)n=0;if(!e||e<0||e>l)e=l;var a="";for(var t=n;t<e;t++){a+=M(r[t])}return a}function w(r,l,a){var n=r.slice(l,a);var t="";for(var e=0;e<n.length;e+=2){t+=String.fromCharCode(n[e]+n[e+1]*256)}return t}e.prototype.slice=function(n,t){var r=this.length;n=~~n;t=t===undefined?r:~~t;if(n<0){n+=r;if(n<0)n=0}else if(n>r){n=r}if(t<0){t+=r;if(t<0)t=0}else if(t>r){t=r}if(t<n)t=n;var l;if(e.TYPED_ARRAY_SUPPORT){l=e._augment(this.subarray(n,t))}else{var i=t-n;l=new e(i,undefined,true);for(var a=0;a<i;a++){l[a]=this[a+n]}}if(l.length)l.parent=this.parent||this;return l};function t(e,n,t){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+n>t)throw new RangeError("Trying to access beyond buffer length")}e.prototype.readUIntLE=function(e,n,i){e=e>>>0;n=n>>>0;if(!i)t(e,n,this.length);var r=this[e];var l=1;var a=0;while(++a<n&&(l*=256))r+=this[e+a]*l;return r};e.prototype.readUIntBE=function(n,e,a){n=n>>>0;e=e>>>0;if(!a)t(n,e,this.length);var r=this[n+--e];var l=1;while(e>0&&(l*=256))r+=this[n+--e]*l;return r};e.prototype.readUInt8=function(e,n){if(!n)t(e,1,this.length);return this[e]};e.prototype.readUInt16LE=function(e,n){if(!n)t(e,2,this.length);return this[e]|this[e+1]<<8};e.prototype.readUInt16BE=function(e,n){if(!n)t(e,2,this.length);return this[e]<<8|this[e+1]};e.prototype.readUInt32LE=function(e,n){if(!n)t(e,4,this.length);return(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};e.prototype.readUInt32BE=function(e,n){if(!n)t(e,4,this.length);return this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};e.prototype.readIntLE=function(e,n,i){e=e>>>0;n=n>>>0;if(!i)t(e,n,this.length);var r=this[e];var l=1;var a=0;while(++a<n&&(l*=256))r+=this[e+a]*l;l*=128;if(r>=l)r-=Math.pow(2,8*n);return r};e.prototype.readIntBE=function(e,n,i){e=e>>>0;n=n>>>0;if(!i)t(e,n,this.length);var a=n;var r=1;var l=this[e+--a];while(a>0&&(r*=256))l+=this[e+--a]*r;r*=128;if(l>=r)l-=Math.pow(2,8*n);return l};e.prototype.readInt8=function(e,n){if(!n)t(e,1,this.length);if(!(this[e]&128))return this[e];return(255-this[e]+1)*-1};e.prototype.readInt16LE=function(e,r){if(!r)t(e,2,this.length);var n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};e.prototype.readInt16BE=function(e,r){if(!r)t(e,2,this.length);var n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};e.prototype.readInt32LE=function(e,n){if(!n)t(e,4,this.length);return this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};e.prototype.readInt32BE=function(e,n){if(!n)t(e,4,this.length);return this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};e.prototype.readFloatLE=function(e,n){if(!n)t(e,4,this.length);return l.read(this,e,true,23,4)};e.prototype.readFloatBE=function(e,n){if(!n)t(e,4,this.length);return l.read(this,e,false,23,4)};e.prototype.readDoubleLE=function(e,n){if(!n)t(e,8,this.length);return l.read(this,e,true,52,8)};e.prototype.readDoubleBE=function(e,n){if(!n)t(e,8,this.length);return l.read(this,e,false,52,8)};function r(n,t,r,l,a,i){if(!e.isBuffer(n))throw new TypeError("buffer must be a Buffer instance");if(t>a||t<i)throw new RangeError("value is out of bounds");if(r+l>n.length)throw new RangeError("index out of range")}e.prototype.writeUIntLE=function(t,e,n,i){t=+t;e=e>>>0;n=n>>>0;if(!i)r(this,t,e,n,Math.pow(2,8*n),0);var l=1;var a=0;this[e]=t&255;while(++a<n&&(l*=256))this[e+a]=t/l>>>0&255;return e+n};e.prototype.writeUIntBE=function(t,e,n,i){t=+t;e=e>>>0;n=n>>>0;if(!i)r(this,t,e,n,Math.pow(2,8*n),0);var l=n-1;var a=1;this[e+l]=t&255;while(--l>=0&&(a*=256))this[e+l]=t/a>>>0&255;return e+n};e.prototype.writeUInt8=function(n,t,l){n=+n;t=t>>>0;if(!l)r(this,n,t,1,255,0);if(!e.TYPED_ARRAY_SUPPORT)n=Math.floor(n);this[t]=n;return t+1};function o(t,n,r,l){if(n<0)n=65535+n+1;for(var e=0,a=Math.min(t.length-r,2);e<a;e++){t[r+e]=(n&255<<8*(l?e:1-e))>>>(l?e:1-e)*8}}e.prototype.writeUInt16LE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,2,65535,0);if(e.TYPED_ARRAY_SUPPORT){this[n]=t;this[n+1]=t>>>8}else o(this,t,n,true);return n+2};e.prototype.writeUInt16BE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,2,65535,0);if(e.TYPED_ARRAY_SUPPORT){this[n]=t>>>8;this[n+1]=t}else o(this,t,n,false);return n+2};function s(t,n,r,l){if(n<0)n=4294967295+n+1;for(var e=0,a=Math.min(t.length-r,4);e<a;e++){t[r+e]=n>>>(l?e:3-e)*8&255}}e.prototype.writeUInt32LE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,4,4294967295,0);if(e.TYPED_ARRAY_SUPPORT){this[n+3]=t>>>24;this[n+2]=t>>>16;this[n+1]=t>>>8;this[n]=t}else s(this,t,n,true);return n+4};e.prototype.writeUInt32BE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,4,4294967295,0);if(e.TYPED_ARRAY_SUPPORT){this[n]=t>>>24;this[n+1]=t>>>16;this[n+2]=t>>>8;this[n+3]=t}else s(this,t,n,false);return n+4};e.prototype.writeIntLE=function(e,n,t,i){e=+e;n=n>>>0;if(!i){r(this,e,n,t,Math.pow(2,8*t-1)-1,-Math.pow(2,8*t-1))}var l=0;var a=1;var s=e<0?1:0;this[n]=e&255;while(++l<t&&(a*=256))this[n+l]=(e/a>>0)-s&255;return n+t};e.prototype.writeIntBE=function(e,n,t,i){e=+e;n=n>>>0;if(!i){r(this,e,n,t,Math.pow(2,8*t-1)-1,-Math.pow(2,8*t-1))}var l=t-1;var a=1;var s=e<0?1:0;this[n+l]=e&255;while(--l>=0&&(a*=256))this[n+l]=(e/a>>0)-s&255;return n+t};e.prototype.writeInt8=function(n,t,l){n=+n;t=t>>>0;if(!l)r(this,n,t,1,127,-128);if(!e.TYPED_ARRAY_SUPPORT)n=Math.floor(n);if(n<0)n=255+n+1;this[t]=n;return t+1};e.prototype.writeInt16LE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,2,32767,-32768);if(e.TYPED_ARRAY_SUPPORT){this[n]=t;this[n+1]=t>>>8}else o(this,t,n,true);return n+2};e.prototype.writeInt16BE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,2,32767,-32768);if(e.TYPED_ARRAY_SUPPORT){this[n]=t>>>8;this[n+1]=t}else o(this,t,n,false);return n+2};e.prototype.writeInt32LE=function(t,n,l){t=+t;n=n>>>0;if(!l)r(this,t,n,4,2147483647,-2147483648);if(e.TYPED_ARRAY_SUPPORT){this[n]=t;this[n+1]=t>>>8;this[n+2]=t>>>16;this[n+3]=t>>>24}else s(this,t,n,true);return n+4};e.prototype.writeInt32BE=function(n,t,l){n=+n;t=t>>>0;if(!l)r(this,n,t,4,2147483647,-2147483648);if(n<0)n=4294967295+n+1;if(e.TYPED_ARRAY_SUPPORT){this[t]=n>>>24;this[t+1]=n>>>16;this[t+2]=n>>>8;this[t+3]=n}else s(this,n,t,false);return t+4};function g(t,e,n,r,l,a){if(e>l||e<a)throw new RangeError("value is out of bounds");if(n+r>t.length)throw new RangeError("index out of range");if(n<0)throw new RangeError("index out of range")}function h(n,t,e,r,a){if(!a)g(n,t,e,4,3.4028234663852886e38,-3.4028234663852886e38);l.write(n,t,e,r,23,4);return e+4}e.prototype.writeFloatLE=function(e,n,t){return h(this,e,n,true,t)};e.prototype.writeFloatBE=function(e,n,t){return h(this,e,n,false,t)};function m(n,t,e,r,a){if(!a)g(n,t,e,8,1.7976931348623157e308,-1.7976931348623157e308);l.write(n,t,e,r,52,8);return e+8}e.prototype.writeDoubleLE=function(e,n,t){return m(this,e,n,true,t)};e.prototype.writeDoubleBE=function(e,n,t){return m(this,e,n,false,t)};e.prototype.copy=function(l,r,n,t){var s=this;if(!n)n=0;if(!t&&t!==0)t=this.length;if(r>=l.length)r=l.length;if(!r)r=0;if(t>0&&t<n)t=n;if(t===n)return 0;if(l.length===0||s.length===0)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=s.length)throw new RangeError("sourceStart out of bounds");if(t<0)throw new RangeError("sourceEnd out of bounds");if(t>this.length)t=this.length;if(l.length-r<t-n)t=l.length-r+n;var a=t-n;if(a<1e3||!e.TYPED_ARRAY_SUPPORT){for(var i=0;i<a;i++){l[i+r]=this[i+n]}}else{l._set(this.subarray(n,n+a),r)}return a};e.prototype.fill=function(r,n,t){if(!r)r=0;if(!n)n=0;if(!t)t=this.length;if(t<n)throw new RangeError("end < start");if(t===n)return;if(this.length===0)return;if(n<0||n>=this.length)throw new RangeError("start out of bounds");if(t<0||t>this.length)throw new RangeError("end out of bounds");var e;if(typeof r==="number"){for(e=n;e<t;e++){this[e]=r}}else{var l=p(r.toString());var a=l.length;for(e=n;e<t;e++){this[e]=l[e%a]}}return this};e.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(e.TYPED_ARRAY_SUPPORT){return new e(this).buffer}else{var t=new Uint8Array(this.length);for(var n=0,r=t.length;n<r;n+=1){t[n]=this[n]}return t.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var n=e.prototype;e._augment=function(t){t.constructor=e;t._isBuffer=true;t._get=t.get;t._set=t.set;t.get=n.get;t.set=n.set;t.write=n.write;t.toString=n.toString;t.toLocaleString=n.toString;t.toJSON=n.toJSON;t.equals=n.equals;t.compare=n.compare;t.copy=n.copy;t.slice=n.slice;t.readUIntLE=n.readUIntLE;t.readUIntBE=n.readUIntBE;t.readUInt8=n.readUInt8;t.readUInt16LE=n.readUInt16LE;t.readUInt16BE=n.readUInt16BE;t.readUInt32LE=n.readUInt32LE;t.readUInt32BE=n.readUInt32BE;t.readIntLE=n.readIntLE;t.readIntBE=n.readIntBE;t.readInt8=n.readInt8;t.readInt16LE=n.readInt16LE;t.readInt16BE=n.readInt16BE;t.readInt32LE=n.readInt32LE;t.readInt32BE=n.readInt32BE;t.readFloatLE=n.readFloatLE;t.readFloatBE=n.readFloatBE;t.readDoubleLE=n.readDoubleLE;t.readDoubleBE=n.readDoubleBE;t.writeUInt8=n.writeUInt8;t.writeUIntLE=n.writeUIntLE;t.writeUIntBE=n.writeUIntBE;t.writeUInt16LE=n.writeUInt16LE;t.writeUInt16BE=n.writeUInt16BE;t.writeUInt32LE=n.writeUInt32LE;t.writeUInt32BE=n.writeUInt32BE;t.writeIntLE=n.writeIntLE;t.writeIntBE=n.writeIntBE;t.writeInt8=n.writeInt8;t.writeInt16LE=n.writeInt16LE;t.writeInt16BE=n.writeInt16BE;t.writeInt32LE=n.writeInt32LE;t.writeInt32BE=n.writeInt32BE;t.writeFloatLE=n.writeFloatLE;t.writeFloatBE=n.writeFloatBE;t.writeDoubleLE=n.writeDoubleLE;t.writeDoubleBE=n.writeDoubleBE;t.fill=n.fill;t.inspect=n.inspect;t.toArrayBuffer=n.toArrayBuffer;return t};var T=/[^+\/0-9A-z\-]/g;function E(e){e=P(e).replace(T,"");if(e.length<2)return"";while(e.length%4!==0){e=e+"="}return e}function P(e){if(e.trim)return e.trim();return e.replace(/^\s+|\s+$/g,"")}function j(n){return f(n)||e.isBuffer(n)||n&&typeof n==="object"&&typeof n.length==="number"}function M(e){if(e<16)return"0"+e.toString(16);return e.toString(16)}function p(a,n){var e,i=a.length;var r=null;n=n||Infinity;var t=[];var l=0;for(;l<i;l++){e=a.charCodeAt(l);if(e>55295&&e<57344){if(r){if(e<56320){if((n-=3)>-1)t.push(239,191,189);r=e;continue}else{e=r-55296<<10|e-56320|65536;r=null}}else{if(e>56319){if((n-=3)>-1)t.push(239,191,189);continue}else if(l+1===i){if((n-=3)>-1)t.push(239,191,189);continue}else{r=e;continue}}}else if(r){if((n-=3)>-1)t.push(239,191,189);r=null}if(e<128){if((n-=1)<0)break;t.push(e)}else if(e<2048){if((n-=2)<0)break;t.push(e>>6|192,e&63|128)}else if(e<65536){if((n-=3)<0)break;t.push(e>>12|224,e>>6&63|128,e&63|128)}else if(e<2097152){if((n-=4)<0)break;t.push(e>>18|240,e>>12&63|128,e>>6&63|128,e&63|128)}else{throw new Error("Invalid code point")}}return t}function D(n){var t=[];for(var e=0;e<n.length;e++){t.push(n.charCodeAt(e)&255)}return t}function N(r,i){var e,l,a;var n=[];for(var t=0;t<r.length;t++){if((i-=2)<0)break;e=r.charCodeAt(t);l=e>>8;a=e%256;n.push(a);n.push(l)}return n}function y(e){return u.toByteArray(E(e))}function a(t,r,l,n,a){if(a)n-=n%a;for(var e=0;e<n;e++){if(e+l>=r.length||e>=t.length)break;r[e+l]=t[e]}return e}function b(e){try{return decodeURIComponent(e)}catch(n){return String.fromCharCode(65533)}}},{"base64-js":112,ieee754:113,"is-array":114}],112:[function(t,r,e){var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(a){"use strict";var s=typeof Uint8Array!=="undefined"?Uint8Array:Array;var c="+".charCodeAt(0);var i="/".charCodeAt(0);var t="0".charCodeAt(0);var l="a".charCodeAt(0);var r="A".charCodeAt(0);var o="-".charCodeAt(0);var u="_".charCodeAt(0);function e(n){var e=n.charCodeAt(0);if(e===c||e===o)return 62;if(e===i||e===u)return 63;if(e<t)return-1;if(e<t+10)return e-t+26+26;if(e<r+26)return e-r;if(e<l+26)return e-l+26}function f(n){var t,o,u,r,a,i;if(n.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var c=n.length;a="="===n.charAt(c-2)?2:"="===n.charAt(c-1)?1:0;i=new s(n.length*3/4-a);u=a>0?n.length-4:n.length;var f=0;function l(e){i[f++]=e}for(t=0,o=0;t<u;t+=4,o+=3){r=e(n.charAt(t))<<18|e(n.charAt(t+1))<<12|e(n.charAt(t+2))<<6|e(n.charAt(t+3));l((r&16711680)>>16);l((r&65280)>>8);l(r&255)}if(a===2){r=e(n.charAt(t))<<2|e(n.charAt(t+1))>>4;l(r&255)}else if(a===1){r=e(n.charAt(t))<<10|e(n.charAt(t+1))<<4|e(n.charAt(t+2))>>2;l(r>>8&255);l(r&255)}return i}function p(e){var a,i=e.length%3,t="",r,s;function l(e){return n.charAt(e)}function o(e){return l(e>>18&63)+l(e>>12&63)+l(e>>6&63)+l(e&63)}for(a=0,s=e.length-i;a<s;a+=3){r=(e[a]<<16)+(e[a+1]<<8)+e[a+2];t+=o(r)}switch(i){case 1:r=e[e.length-1];t+=l(r>>2);t+=l(r<<4&63);t+="==";break;case 2:r=(e[e.length-2]<<8)+e[e.length-1];t+=l(r>>10);t+=l(r>>4&63);t+=l(r<<2&63);t+="=";break}return t}a.toByteArray=f;a.fromByteArray=p})(typeof e==="undefined"?this.base64js={}:e)},{}],113:[function(n,t,e){e.read=function(o,s,p,a,f){var e,t,d=f*8-a-1,c=(1<<d)-1,u=c>>1,n=-7,r=p?f-1:0,i=p?-1:1,l=o[s+r];r+=i;e=l&(1<<-n)-1;l>>=-n;n+=d;for(;n>0;e=e*256+o[s+r],r+=i,n-=8);t=e&(1<<-n)-1;e>>=-n;n+=a;for(;n>0;t=t*256+o[s+r],r+=i,n-=8);if(e===0){e=1-u}else if(e===c){return t?NaN:(l?-1:1)*Infinity}else{t=t+Math.pow(2,a);e=e-u}return(l?-1:1)*t*Math.pow(2,e-a)};e.write=function(c,n,f,m,t,d){var e,r,l,s=d*8-t-1,o=(1<<s)-1,a=o>>1,p=t===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=m?0:d-1,u=m?1:-1,h=n<0||n===0&&1/n<0?1:0;n=Math.abs(n);if(isNaN(n)||n===Infinity){r=isNaN(n)?1:0;e=o}else{e=Math.floor(Math.log(n)/Math.LN2);if(n*(l=Math.pow(2,-e))<1){e--;l*=2}if(e+a>=1){n+=p/l}else{n+=p*Math.pow(2,1-a)}if(n*l>=2){e++;l/=2}if(e+a>=o){r=0;e=o}else if(e+a>=1){r=(n*l-1)*Math.pow(2,t);e=e+a}else{r=n*Math.pow(2,a-1)*Math.pow(2,t);e=0}}for(;t>=8;c[f+i]=r&255,i+=u,r/=256,t-=8);e=e<<t|r;s+=t;for(;s>0;c[f+i]=e&255,i+=u,e/=256,s-=8);c[f+i-u]|=h*128}},{}],114:[function(r,e,l){var n=Array.isArray;var t=Object.prototype.toString;e.exports=n||function(e){return!!e&&"[object Array]"==t.call(e)}},{}],115:[function(i,l,s){function e(){this._events=this._events||{};this._maxListeners=this._maxListeners||undefined}l.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 s,l,a,i,e,o;if(!this._events)this._events={};if(u==="error"){if(!this._events.error||t(this._events.error)&&!this._events.error.length){s=arguments[1];if(s instanceof Error){throw s}throw TypeError('Uncaught, unspecified "error" event.')}}l=this._events[u];if(r(l))return false;if(n(l)){switch(arguments.length){case 1:l.call(this);break;case 2:l.call(this,arguments[1]);break;case 3:l.call(this,arguments[1],arguments[2]);break;default:a=arguments.length;i=new Array(a-1);for(e=1;e<a;e++)i[e-1]=arguments[e];l.apply(this,i)}}else if(t(l)){a=arguments.length;i=new Array(a-1);for(e=1;e<a;e++)i[e-1]=arguments[e];o=l.slice();a=o.length;for(e=0;e<a;e++)o[e].apply(this,i)}return true};e.prototype.addListener=function(l,a){var i;if(!n(a))throw TypeError("listener must be a function");if(!this._events)this._events={};if(this._events.newListener)this.emit("newListener",l,n(a.listener)?a.listener:a);if(!this._events[l])this._events[l]=a;else if(t(this._events[l]))this._events[l].push(a);else this._events[l]=[this._events[l],a];if(t(this._events[l])&&!this._events[l].warned){var i;if(!r(this._maxListeners)){i=this._maxListeners}else{i=e.defaultMaxListeners}if(i&&i>0&&this._events[l].length>i){this._events[l].warned=true;console.error("(node) warning: possible EventEmitter memory "+"leak detected. %d listeners added. "+"Use emitter.setMaxListeners() to increase limit.",this._events[l].length);if(typeof console.trace==="function"){console.trace()}}}return this};e.prototype.on=e.prototype.addListener;e.prototype.once=function(r,e){if(!n(e))throw TypeError("listener must be a function");var l=false;function t(){this.removeListener(r,t);if(!l){l=true;e.apply(this,arguments)}}t.listener=e;this.on(r,t);return this};e.prototype.removeListener=function(l,r){var e,i,s,a;if(!n(r))throw TypeError("listener must be a function");if(!this._events||!this._events[l])return this;e=this._events[l];s=e.length;i=-1;if(e===r||n(e.listener)&&e.listener===r){delete this._events[l];if(this._events.removeListener)this.emit("removeListener",l,r)}else if(t(e)){for(a=s;a-->0;){if(e[a]===r||e[a].listener&&e[a].listener===r){i=a;break}}if(i<0)return this;if(e.length===1){e.length=0;delete this._events[l]}else{e.splice(i,1)}if(this._events.removeListener)this.emit("removeListener",l,r)}return this};e.prototype.removeAllListeners=function(e){var r,t;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(r in this._events){if(r==="removeListener")continue;this.removeAllListeners(r)}this.removeAllListeners("removeListener");this._events={};return this}t=this._events[e];if(n(t)){this.removeListener(e,t)}else{while(t.length)this.removeListener(e,t[t.length-1])}delete this._events[e];return this};e.prototype.listeners=function(e){var t;if(!this._events||!this._events[e])t=[];else if(n(this._events[e]))t=[this._events[e]];else t=this._events[e].slice();return t};e.listenerCount=function(e,r){var t;if(!e._events||!e._events[r])t=0;else if(n(e._events[r]))t=1;else t=e._events[r].length;return t};function n(e){return typeof e==="function"}function a(e){return typeof e==="number"}function t(e){return typeof e==="object"&&e!==null}function r(e){return e===void 0}},{}],116:[function(n,e,t){if(typeof Object.create==="function"){e.exports=function r(e,n){e.super_=n;e.prototype=Object.create(n.prototype,{constructor:{value:e,enumerable:false,writable:true,configurable:true}})}}else{e.exports=function l(e,n){e.super_=n;var t=function(){};t.prototype=n.prototype;e.prototype=new t;e.prototype.constructor=e}}},{}],117:[function(n,e,t){e.exports=Array.isArray||function(e){return Object.prototype.toString.call(e)=="[object Array]"}},{}],118:[function(n,t,e){(function(l){function r(e,l){var t=0;for(var n=e.length-1;n>=0;n--){var r=e[n];if(r==="."){e.splice(n,1)}else if(r===".."){e.splice(n,1);t++}else if(t){e.splice(n,1);t--}}if(l){for(;t--;t){e.unshift("..")}}return e}var a=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var n=function(e){return a.exec(e).slice(1)};e.resolve=function(){var e="",n=false;for(var a=arguments.length-1;a>=-1&&!n;a--){var i=a>=0?arguments[a]:l.cwd();if(typeof i!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!i){continue}e=i+"/"+e;n=i.charAt(0)==="/"}e=r(t(e.split("/"),function(e){return!!e}),!n).join("/");return(n?"/":"")+e||"."};e.normalize=function(n){var l=e.isAbsolute(n),a=i(n,-1)==="/";n=r(t(n.split("/"),function(e){return!!e}),!l).join("/");if(!n&&!l){n="."}if(n&&a){n+="/"}return(l?"/":"")+n};e.isAbsolute=function(e){return e.charAt(0)==="/"};e.join=function(){var n=Array.prototype.slice.call(arguments,0);return e.normalize(t(n,function(e,n){if(typeof e!=="string"){throw new TypeError("Arguments to path.join must be strings")}return e}).join("/"))};e.relative=function(r,l){r=e.resolve(r).substr(1);l=e.resolve(l).substr(1);function o(n){var e=0;for(;e<n.length;e++){if(n[e]!=="")break}var t=n.length-1;for(;t>=0;t--){if(n[t]!=="")break}if(e>t)return[];return n.slice(e,t-e+1)}var a=o(r.split("/"));var i=o(l.split("/"));var u=Math.min(a.length,i.length);var s=u;for(var n=0;n<u;n++){if(a[n]!==i[n]){s=n;break}}var t=[];for(var n=s;n<a.length;n++){t.push("..")}t=t.concat(i.slice(s));return t.join("/")};e.sep="/";e.delimiter=":";e.dirname=function(l){var t=n(l),r=t[0],e=t[1];if(!r&&!e){return"."}if(e){e=e.substr(0,e.length-1)}return r+e};e.basename=function(r,t){var e=n(r)[2];if(t&&e.substr(-1*t.length)===t){e=e.substr(0,e.length-t.length)}return e};e.extname=function(e){return n(e)[3]};function t(e,t){if(e.filter)return e.filter(t);var r=[];for(var n=0;n<e.length;n++){if(t(e[n],n,e))r.push(e[n])}return r}var i="ab".substr(-1)==="b"?function(e,n,t){return e.substr(n,t)}:function(n,e,t){if(e<0)e=n.length+e;return n.substr(e,t)}}).call(this,n("_process"))},{_process:119}],119:[function(i,l,s){var e=l.exports={};var t=[];var r=false;function a(){if(r){return}r=true;var n;var e=t.length;while(e){n=t;t=[];var l=-1;while(++l<e){n[l]()}e=t.length}r=false}e.nextTick=function(e){t.push(e);if(!r){setTimeout(a,0)}};e.title="browser";e.browser=true;e.env={};e.argv=[];e.version="";function n(){}e.on=n;e.addListener=n;e.once=n;e.off=n;e.removeListener=n;e.removeAllListeners=n;e.emit=n;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")};e.umask=function(){return 0}},{}],120:[function(e,n,t){n.exports=e("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":121}],121:[function(e,n,t){(function(i){n.exports=t;var s=Object.keys||function(n){var e=[];for(var t in n)e.push(t);return e};var l=e("core-util-is");l.inherits=e("inherits");var a=e("./_stream_readable");var r=e("./_stream_writable");l.inherits(t,a);u(s(r.prototype),function(e){if(!t.prototype[e])t.prototype[e]=r.prototype[e]});function t(e){if(!(this instanceof t))return new t(e);a.call(this,e);r.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",o)}function o(){if(this.allowHalfOpen||this._writableState.ended)return;i.nextTick(this.end.bind(this))}function u(n,t){for(var e=0,r=n.length;e<r;e++){t(n[e],e)}}}).call(this,e("_process"))},{"./_stream_readable":123,"./_stream_writable":125,_process:119,"core-util-is":126,inherits:116}],122:[function(n,l,a){l.exports=e;var t=n("./_stream_transform");var r=n("core-util-is");r.inherits=n("inherits");r.inherits(e,t);function e(n){if(!(this instanceof e))return new e(n);t.call(this,n)}e.prototype._transform=function(e,t,n){n(null,e)}},{"./_stream_transform":124,"core-util-is":126,inherits:116}],123:[function(e,n,t){(function(r){n.exports=t;var S=e("isarray");var s=e("buffer").Buffer;t.ReadableState=x;var o=e("events").EventEmitter;if(!o.listenerCount)o.listenerCount=function(e,n){return e.listeners(n).length};var a=e("stream");var h=e("core-util-is");h.inherits=e("inherits");var l;h.inherits(t,a);function x(n,r){n=n||{};var t=n.highWaterMark;this.highWaterMark=t||t===0?t: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=!!n.objectMode;this.defaultEncoding=n.defaultEncoding||"utf8";this.ranOut=false;this.awaitDrain=0;this.readingMore=false;this.decoder=null;this.encoding=null;if(n.encoding){if(!l)l=e("string_decoder/").StringDecoder;this.decoder=new l(n.encoding);this.encoding=n.encoding}}function t(e){if(!(this instanceof t))return new t(e);this._readableState=new x(e,this);this.readable=true;a.call(this)}t.prototype.push=function(n,e){var t=this._readableState;if(typeof n==="string"&&!t.objectMode){e=e||t.defaultEncoding;if(e!==t.encoding){n=new s(n,e);e=""}}return g(this,t,n,e,false)};t.prototype.unshift=function(e){var n=this._readableState;return g(this,n,e,"",true)};function g(t,e,n,s,r){var l=A(e,n);if(l){t.emit("error",l)}else if(n===null||n===undefined){e.reading=false;if(!e.ended)k(t,e)}else if(e.objectMode||n&&n.length>0){if(e.ended&&!r){var a=new Error("stream.push() after EOF");t.emit("error",a)}else if(e.endEmitted&&r){var a=new Error("stream.unshift() after end event");t.emit("error",a)}else{if(e.decoder&&!r&&!s)n=e.decoder.write(n);
e.length+=e.objectMode?1:n.length;if(r){e.buffer.unshift(n)}else{e.reading=false;e.buffer.push(n)}if(e.needReadable)i(t);C(t,e)}}else if(!r){e.reading=false}return _(e)}function _(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}t.prototype.setEncoding=function(n){if(!l)l=e("string_decoder/").StringDecoder;this._readableState.decoder=new l(n);this._readableState.encoding=n};var b=8388608;function R(e){if(e>=b){e=b}else{e--;for(var n=1;n<32;n<<=1)e|=e>>n;e++}return e}function v(n,e){if(e.length===0&&e.ended)return 0;if(e.objectMode)return n===0?0:1;if(n===null||isNaN(n)){if(e.flowing&&e.buffer.length)return e.buffer[0].length;else return e.length}if(n<=0)return 0;if(n>e.highWaterMark)e.highWaterMark=R(n);if(n>e.length){if(!e.ended){e.needReadable=true;return 0}else return e.length}return n}t.prototype.read=function(n){var e=this._readableState;e.calledRead=true;var l=n;var t;if(typeof n!=="number"||n>0)e.emittedReadable=false;if(n===0&&e.needReadable&&(e.length>=e.highWaterMark||e.ended)){i(this);return null}n=v(n,e);if(n===0&&e.ended){t=null;if(e.length>0&&e.decoder){t=p(n,e);e.length-=t.length}if(e.length===0)d(this);return t}var r=e.needReadable;if(e.length-n<=e.highWaterMark)r=true;if(e.ended||e.reading)r=false;if(r){e.reading=true;e.sync=true;if(e.length===0)e.needReadable=true;this._read(e.highWaterMark);e.sync=false}if(r&&!e.reading)n=v(l,e);if(n>0)t=p(n,e);else t=null;if(t===null){e.needReadable=true;n=0}e.length-=n;if(e.length===0&&!e.ended)e.needReadable=true;if(e.ended&&!e.endEmitted&&e.length===0)d(this);return t};function A(t,e){var n=null;if(!s.isBuffer(e)&&"string"!==typeof e&&e!==null&&e!==undefined&&!t.objectMode){n=new TypeError("Invalid non-string/buffer chunk")}return n}function k(t,e){if(e.decoder&&!e.ended){var n=e.decoder.end();if(n&&n.length){e.buffer.push(n);e.length+=e.objectMode?1:n.length}}e.ended=true;if(e.length>0)i(t);else d(t)}function i(n){var e=n._readableState;e.needReadable=false;if(e.emittedReadable)return;e.emittedReadable=true;if(e.sync)r.nextTick(function(){m(n)});else m(n)}function m(e){e.emit("readable")}function C(n,e){if(!e.readingMore){e.readingMore=true;r.nextTick(function(){E(n,e)})}}function E(t,e){var n=e.length;while(!e.reading&&!e.flowing&&!e.ended&&e.length<e.highWaterMark){t.read(0);if(n===e.length)break;else n=e.length}e.readingMore=false}t.prototype._read=function(e){this.emit("error",new Error("not implemented"))};t.prototype.pipe=function(e,d){var t=this;var n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1;var y=(!d||d.end!==false)&&e!==r.stdout&&e!==r.stderr;var h=y?g:u;if(n.endEmitted)r.nextTick(h);else t.once("end",h);e.on("unpipe",m);function m(e){if(e!==t)return;u()}function g(){e.end()}var p=w(t);e.on("drain",p);function u(){e.removeListener("close",i);e.removeListener("finish",a);e.removeListener("drain",p);e.removeListener("error",l);e.removeListener("unpipe",m);t.removeListener("end",g);t.removeListener("end",u);if(!e._writableState||e._writableState.needDrain)p()}function l(n){s();e.removeListener("error",l);if(o.listenerCount(e,"error")===0)e.emit("error",n)}if(!e._events||!e._events.error)e.on("error",l);else if(S(e._events.error))e._events.error.unshift(l);else e._events.error=[l,e._events.error];function i(){e.removeListener("finish",a);s()}e.once("close",i);function a(){e.removeListener("close",i);s()}e.once("finish",a);function s(){t.unpipe(e)}e.emit("pipe",t);if(!n.flowing){this.on("readable",c);n.flowing=true;r.nextTick(function(){f(t)})}return e};function w(e){return function(){var t=this;var n=e._readableState;n.awaitDrain--;if(n.awaitDrain===0)f(e)}}function f(n){var e=n._readableState;var t;e.awaitDrain=0;function r(n,l,a){var r=n.write(t);if(false===r){e.awaitDrain++}}while(e.pipesCount&&null!==(t=n.read())){if(e.pipesCount===1)r(e.pipes,0,null);else y(e.pipes,r);n.emit("data",t);if(e.awaitDrain>0)return}if(e.pipesCount===0){e.flowing=false;if(o.listenerCount(n,"data")>0)u(n);return}e.ranOut=true}function c(){if(this._readableState.ranOut){this._readableState.ranOut=false;f(this)}}t.prototype.unpipe=function(n){var e=this._readableState;if(e.pipesCount===0)return this;if(e.pipesCount===1){if(n&&n!==e.pipes)return this;if(!n)n=e.pipes;e.pipes=null;e.pipesCount=0;this.removeListener("readable",c);e.flowing=false;if(n)n.emit("unpipe",this);return this}if(!n){var r=e.pipes;var l=e.pipesCount;e.pipes=null;e.pipesCount=0;this.removeListener("readable",c);e.flowing=false;for(var t=0;t<l;t++)r[t].emit("unpipe",this);return this}var t=I(e.pipes,n);if(t===-1)return this;e.pipes.splice(t,1);e.pipesCount-=1;if(e.pipesCount===1)e.pipes=e.pipes[0];n.emit("unpipe",this);return this};t.prototype.on=function(n,t){var r=a.prototype.on.call(this,n,t);if(n==="data"&&!this._readableState.flowing)u(this);if(n==="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){i(this,e)}}}return r};t.prototype.addListener=t.prototype.on;t.prototype.resume=function(){u(this);this.read(0);this.emit("resume")};t.prototype.pause=function(){u(this,true);this.emit("pause")};function u(e,l){var i=e._readableState;if(i.flowing){throw new Error("Cannot switch to old mode now.")}var n=l||false;var t=false;e.readable=true;e.pipe=a.prototype.pipe;e.on=e.addListener=a.prototype.on;e.on("readable",function(){t=true;var r;while(!n&&null!==(r=e.read()))e.emit("data",r);if(r===null){t=false;e._readableState.needReadable=true}});e.pause=function(){n=true;this.emit("pause")};e.resume=function(){n=false;if(t)r.nextTick(function(){e.emit("readable")});else this.read(0);this.emit("resume")};e.emit("readable")}t.prototype.wrap=function(e){var n=this._readableState;var l=false;var t=this;e.on("end",function(){if(n.decoder&&!n.ended){var e=n.decoder.end();if(e&&e.length)t.push(e)}t.push(null)});e.on("data",function(r){if(n.decoder)r=n.decoder.write(r);if(n.objectMode&&(r===null||r===undefined))return;else if(!n.objectMode&&(!r||!r.length))return;var a=t.push(r);if(!a){l=true;e.pause()}});for(var r in e){if(typeof e[r]==="function"&&typeof this[r]==="undefined"){this[r]=function(n){return function(){return e[n].apply(e,arguments)}}(r)}}var a=["error","close","destroy","pause","resume"];y(a,function(n){e.on(n,t.emit.bind(t,n))});t._read=function(n){if(l){l=false;e.resume()}};return t};t._fromList=p;function p(t,a){var e=a.buffer;var o=a.length;var u=!!a.decoder;var f=!!a.objectMode;var n;if(e.length===0)return null;if(o===0)n=null;else if(f)n=e.shift();else if(!t||t>=o){if(u)n=e.join("");else n=s.concat(e,o);e.length=0}else{if(t<e[0].length){var r=e[0];n=r.slice(0,t);e[0]=r.slice(t)}else if(t===e[0].length){n=e.shift()}else{if(u)n="";else n=new s(t);var i=0;for(var c=0,p=e.length;c<p&&i<t;c++){var r=e[0];var l=Math.min(t-i,r.length);if(u)n+=r.slice(0,l);else r.copy(n,i,0,l);if(l<r.length)e[0]=r.slice(l);else e.shift();i+=l}}}return n}function d(n){var e=n._readableState;if(e.length>0)throw new Error("endReadable called on non-empty stream");if(!e.endEmitted&&e.calledRead){e.ended=true;r.nextTick(function(){if(!e.endEmitted&&e.length===0){e.endEmitted=true;n.readable=false;n.emit("end")}})}}function y(n,t){for(var e=0,r=n.length;e<r;e++){t(n[e],e)}}function I(n,t){for(var e=0,r=n.length;e<r;e++){if(n[e]===t)return e}return-1}}).call(this,e("_process"))},{_process:119,buffer:111,"core-util-is":126,events:115,inherits:116,isarray:117,stream:131,"string_decoder/":132}],124:[function(n,a,o){a.exports=e;var t=n("./_stream_duplex");var r=n("core-util-is");r.inherits=n("inherits");r.inherits(e,t);function i(n,e){this.afterTransform=function(n,t){return s(e,n,t)};this.needTransform=false;this.transforming=false;this.writecb=null;this.writechunk=null}function s(e,a,r){var t=e._transformState;t.transforming=false;var l=t.writecb;if(!l)return e.emit("error",new Error("no writecb in Transform class"));t.writechunk=null;t.writecb=null;if(r!==null&&r!==undefined)e.push(r);if(l)l(a);var n=e._readableState;n.reading=false;if(n.needReadable||n.length<n.highWaterMark){e._read(n.highWaterMark)}}function e(n){if(!(this instanceof e))return new e(n);t.call(this,n);var a=this._transformState=new i(n,this);var r=this;this._readableState.needReadable=true;this._readableState.sync=false;this.once("finish",function(){if("function"===typeof this._flush)this._flush(function(e){l(r,e)});else l(r)})}e.prototype.push=function(e,n){this._transformState.needTransform=false;return t.prototype.push.call(this,e,n)};e.prototype._transform=function(e,n,t){throw new Error("not implemented")};e.prototype._write=function(t,r,l){var e=this._transformState;e.writecb=l;e.writechunk=t;e.writeencoding=r;if(!e.transforming){var n=this._readableState;if(e.needTransform||n.needReadable||n.length<n.highWaterMark)this._read(n.highWaterMark)}};e.prototype._read=function(n){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 l(e,n){if(n)return e.emit("error",n);var t=e._writableState;var l=e._readableState;var r=e._transformState;if(t.length)throw new Error("calling transform done when ws.length != 0");if(r.transforming)throw new Error("calling transform done when still transforming");return e.push(null)}},{"./_stream_duplex":121,"core-util-is":126,inherits:116}],125:[function(e,n,t){(function(r){n.exports=t;var l=e("buffer").Buffer;t.WritableState=s;var a=e("core-util-is");a.inherits=e("inherits");var i=e("stream");a.inherits(t,i);function d(e,n,t){this.chunk=e;this.encoding=n;this.callback=t}function s(e,t){e=e||{};var n=e.highWaterMark;this.highWaterMark=n||n===0?n:16*1024;this.objectMode=!!e.objectMode;this.highWaterMark=~~this.highWaterMark;this.needDrain=false;this.ending=false;this.ended=false;this.finished=false;var r=e.decodeStrings===false;this.decodeStrings=!r;this.defaultEncoding=e.defaultEncoding||"utf8";this.length=0;this.writing=false;this.sync=true;this.bufferProcessing=false;this.onwrite=function(e){g(t,e)};this.writecb=null;this.writelen=0;this.buffer=[];this.errorEmitted=false}function t(n){var r=e("./_stream_duplex");if(!(this instanceof t)&&!(this instanceof r))return new t(n);this._writableState=new s(n,this);this.writable=true;i.call(this)}t.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe. Not readable."))};function y(n,l,t){var e=new Error("write after end");n.emit("error",e);r.nextTick(function(){t(e)})}function b(a,i,e,s){var n=true;if(!l.isBuffer(e)&&"string"!==typeof e&&e!==null&&e!==undefined&&!i.objectMode){var t=new TypeError("Invalid non-string/buffer chunk");a.emit("error",t);r.nextTick(function(){s(t)});n=false}return n}t.prototype.write=function(r,e,n){var t=this._writableState;var a=false;if(typeof e==="function"){n=e;e=null}if(l.isBuffer(r))e="buffer";else if(!e)e=t.defaultEncoding;if(typeof n!=="function")n=function(){};if(t.ended)y(this,t,n);else if(b(this,t,r,n))a=w(this,t,r,e,n);return a};function E(n,e,t){if(!n.objectMode&&n.decodeStrings!==false&&typeof e==="string"){e=new l(e,t)}return e}function w(s,e,n,t,r){n=E(e,n,t);if(l.isBuffer(n))t="buffer";var a=e.objectMode?1:n.length;e.length+=a;var i=e.length<e.highWaterMark;if(!i)e.needDrain=true;if(e.writing)e.buffer.push(new d(n,t,r));else o(s,e,a,n,t,r);return i}function o(n,e,t,r,l,a){e.writelen=t;e.writecb=a;e.writing=true;e.sync=true;n._write(r,l,e.onwrite);e.sync=false}function m(n,a,l,e,t){if(l)r.nextTick(function(){t(e)});else t(e);n._writableState.errorEmitted=true;n.emit("error",e)}function h(e){e.writing=false;e.writecb=null;e.length-=e.writelen;e.writelen=0}function g(n,a){var e=n._writableState;var i=e.sync;var t=e.writecb;h(e);if(a)m(n,e,i,a,t);else{var l=c(n,e);if(!l&&!e.bufferProcessing&&e.buffer.length)x(n,e);if(i){r.nextTick(function(){u(n,e,l,t)})}else{u(n,e,l,t)}}}function u(e,n,t,r){if(!t)v(e,n);r();if(t)f(e,n)}function v(n,e){if(e.length===0&&e.needDrain){e.needDrain=false;n.emit("drain")}}function x(l,e){e.bufferProcessing=true;for(var n=0;n<e.buffer.length;n++){var t=e.buffer[n];var r=t.chunk;var a=t.encoding;var i=t.callback;var s=e.objectMode?1:r.length;o(l,e,s,r,a,i);if(e.writing){n++;break}}e.bufferProcessing=false;if(n<e.buffer.length)e.buffer=e.buffer.slice(n);else e.buffer.length=0}t.prototype._write=function(n,t,e){e(new Error("not implemented"))};t.prototype.end=function(e,n,t){var r=this._writableState;if(typeof e==="function"){t=e;e=null;n=null}else if(typeof n==="function"){t=n;n=null}if(typeof e!=="undefined"&&e!==null)this.write(e,n);if(!r.ending&&!r.finished)p(this,r,t)};function c(n,e){return e.ending&&e.length===0&&!e.finished&&!e.writing}function f(e,n){var t=c(e,n);if(t){n.finished=true;e.emit("finish")}return t}function p(t,e,n){e.ending=true;f(t,e);if(n){if(e.finished)r.nextTick(n);else t.once("finish",n)}e.ended=true}}).call(this,e("_process"))},{"./_stream_duplex":121,_process:119,buffer:111,"core-util-is":126,inherits:116,stream:131}],126:[function(n,t,e){(function(f){function u(e){return Array.isArray(e)}e.isArray=u;function r(e){return typeof e==="boolean"}e.isBoolean=r;function l(e){return e===null}e.isNull=l;function a(e){return e==null}e.isNullOrUndefined=a;function i(e){return typeof e==="number"}e.isNumber=i;function s(e){return typeof e==="string"}e.isString=s;function o(e){return typeof e==="symbol"}e.isSymbol=o;function y(e){return e===void 0}e.isUndefined=y;function c(e){return n(e)&&t(e)==="[object RegExp]"}e.isRegExp=c;function n(e){return typeof e==="object"&&e!==null}e.isObject=n;function p(e){return n(e)&&t(e)==="[object Date]"}e.isDate=p;function d(e){return n(e)&&(t(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 g(e){return f.isBuffer(e)}e.isBuffer=g;function t(e){return Object.prototype.toString.call(e)}}).call(this,n("buffer").Buffer)},{buffer:111}],127:[function(e,n,t){n.exports=e("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":122}],128:[function(n,t,e){var r=n("stream");e=t.exports=n("./lib/_stream_readable.js");e.Stream=r;e.Readable=e;e.Writable=n("./lib/_stream_writable.js");e.Duplex=n("./lib/_stream_duplex.js");e.Transform=n("./lib/_stream_transform.js");e.PassThrough=n("./lib/_stream_passthrough.js")},{"./lib/_stream_duplex.js":121,"./lib/_stream_passthrough.js":122,"./lib/_stream_readable.js":123,"./lib/_stream_transform.js":124,"./lib/_stream_writable.js":125,stream:131}],129:[function(e,n,t){n.exports=e("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":124}],130:[function(e,n,t){n.exports=e("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":125}],131:[function(n,r,a){r.exports=e;var t=n("events").EventEmitter;var l=n("inherits");l(e,t);e.Readable=n("readable-stream/readable.js");e.Writable=n("readable-stream/writable.js");e.Duplex=n("readable-stream/duplex.js");e.Transform=n("readable-stream/transform.js");e.PassThrough=n("readable-stream/passthrough.js");e.Stream=e;function e(){t.call(this)}e.prototype.pipe=function(n,i){var e=this;function s(t){if(n.writable){if(false===n.write(t)&&e.pause){e.pause()}}}e.on("data",s);function o(){if(e.readable&&e.resume){e.resume()}}n.on("drain",o);if(!n._isStdio&&(!i||i.end!==false)){e.on("end",u);e.on("close",c)}var l=false;function u(){if(l)return;l=true;n.end()}function c(){if(l)return;l=true;if(typeof n.destroy==="function")n.destroy()}function a(e){r();if(t.listenerCount(this,"error")===0){throw e}}e.on("error",a);n.on("error",a);function r(){e.removeListener("data",s);n.removeListener("drain",o);e.removeListener("end",u);e.removeListener("close",c);e.removeListener("error",a);n.removeListener("error",a);e.removeListener("end",r);e.removeListener("close",r);n.removeListener("close",r)}e.on("end",r);e.on("close",r);n.on("close",r);n.emit("pipe",e);return n}},{events:115,inherits:116,"readable-stream/duplex.js":120,"readable-stream/passthrough.js":127,"readable-stream/readable.js":128,"readable-stream/transform.js":129,"readable-stream/writable.js":130}],132:[function(t,u,r){var n=t("buffer").Buffer;var l=n.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&&!l(e)){throw new Error("Unknown encoding: "+e)}}var e=r.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=s;break;case"base64":this.surrogateSize=3;this.detectIncompleteChar=o;break;default:this.write=i;return}this.charBuffer=new n(6);this.charReceived=0;this.charLength=0};e.prototype.write=function(e){var n="";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);n=this.charBuffer.slice(0,this.charLength).toString(this.encoding);var l=n.charCodeAt(n.length-1);if(l>=55296&&l<=56319){this.charLength+=this.surrogateSize;n="";continue}this.charReceived=this.charLength=0;if(e.length===0){return n}break}this.detectIncompleteChar(e);var t=e.length;if(this.charLength){e.copy(this.charBuffer,0,e.length-this.charReceived,t);t-=this.charReceived}n+=e.toString(this.encoding,0,t);var t=n.length-1;var l=n.charCodeAt(t);if(l>=55296&&l<=56319){var r=this.surrogateSize;this.charLength+=r;this.charReceived+=r;this.charBuffer.copy(this.charBuffer,r,0,r);e.copy(this.charBuffer,0,0,r);return n.substring(0,t)}return n};e.prototype.detectIncompleteChar=function(n){var e=n.length>=3?3:n.length;for(;e>0;e--){var t=n[n.length-e];if(e==1&&t>>5==6){this.charLength=2;break}if(e<=2&&t>>4==14){this.charLength=3;break}if(e<=3&&t>>3==30){this.charLength=4;break}}this.charReceived=e};e.prototype.end=function(e){var n="";if(e&&e.length)n=this.write(e);if(this.charReceived){var t=this.charReceived;var r=this.charBuffer;var l=this.encoding;n+=r.slice(0,t).toString(l)}return n};function i(e){return e.toString(this.encoding)}function s(e){this.charReceived=e.length%2;this.charLength=this.charReceived?2:0}function o(e){this.charReceived=e.length%3;this.charLength=this.charReceived?3:0}},{buffer:111}],133:[function(n,e,t){e.exports=function r(e){return e&&typeof e==="object"&&typeof e.copy==="function"&&typeof e.fill==="function"&&typeof e.readUInt8==="function"}},{}],134:[function(n,t,e){(function(a,L){var _=/%[sdj%]/g;e.format=function(i){if(!p(i)){var o=[];for(var e=0;e<arguments.length;e++){o.push(r(arguments[e]))}return o.join(" ")}var e=1;var n=arguments;var u=n.length;var a=String(i).replace(_,function(t){if(t==="%%")return"%";if(e>=u)return t;switch(t){case"%s":return String(n[e++]);case"%d":return Number(n[e++]);case"%j":try{return JSON.stringify(n[e++])}catch(r){return"[Circular]"}default:return t}});for(var t=n[e];e<u;t=n[++e]){if(s(t)||!l(t)){a+=" "+t}else{a+=" "+r(t)}}return a};e.deprecate=function(r,n){if(t(L.process)){return function(){return e.deprecate(r,n).apply(this,arguments)}}if(a.noDeprecation===true){return r}var l=false;function i(){if(!l){if(a.throwDeprecation){throw new Error(n)}else if(a.traceDeprecation){console.trace(n)}else{console.error(n)}l=true}return r.apply(this,arguments)}return i};var c={};var v;e.debuglog=function(n){if(t(v))v=a.env.NODE_DEBUG||"";n=n.toUpperCase();if(!c[n]){if(new RegExp("\\b"+n+"\\b","i").test(v)){var r=a.pid;c[n]=function(){var t=e.format.apply(e,arguments);console.error("%s %d: %s",n,r,t)}}else{c[n]=function(){}}}return c[n]};function r(l,r){var n={seen:[],stylize:k};if(arguments.length>=3)n.depth=arguments[2];if(arguments.length>=4)n.colors=arguments[3];if(g(r)){n.showHidden=r}else if(r){e._extend(n,r)}if(t(n.showHidden))n.showHidden=false;if(t(n.depth))n.depth=2;if(t(n.colors))n.colors=false;if(t(n.customInspect))n.customInspect=true;if(n.colors)n.stylize=I;return f(n,l,n.depth)}e.inspect=r;r.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]};r.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function I(n,t){var e=r.styles[t];if(e){return"["+r.colors[e][0]+"m"+n+"["+r.colors[e][1]+"m"}else{return n}}function k(e,n){return e}function O(n){var e={};n.forEach(function(n,t){e[n]=true});return e}function f(t,n,a){if(t.customInspect&&n&&o(n.inspect)&&n.inspect!==e.inspect&&!(n.constructor&&n.constructor.prototype===n)){var s=n.inspect(a,t);if(!p(s)){s=f(t,s,a)}return s}var y=R(t,n);if(y){return y}var r=Object.keys(n);var v=O(r);if(t.showHidden){r=Object.getOwnPropertyNames(n)}if(i(n)&&(r.indexOf("message")>=0||r.indexOf("description")>=0)){return d(n)}if(r.length===0){if(o(n)){var b=n.name?": "+n.name:"";return t.stylize("[Function"+b+"]","special")}if(u(n)){return t.stylize(RegExp.prototype.toString.call(n),"regexp")}if(x(n)){return t.stylize(Date.prototype.toString.call(n),"date")}if(i(n)){return d(n)}}var l="",h=false,c=["{","}"];if(w(n)){h=true;c=["[","]"]}if(o(n)){var E=n.name?": "+n.name:"";l=" [Function"+E+"]"}if(u(n)){l=" "+RegExp.prototype.toString.call(n)}if(x(n)){l=" "+Date.prototype.toUTCString.call(n)}if(i(n)){l=" "+d(n)}if(r.length===0&&(!h||n.length==0)){return c[0]+l+c[1]}if(a<0){if(u(n)){return t.stylize(RegExp.prototype.toString.call(n),"regexp")}else{return t.stylize("[Object]","special")}}t.seen.push(n);var g;if(h){g=A(t,n,a,v,r)}else{g=r.map(function(e){return m(t,n,a,v,e,h)})}t.seen.pop();return P(g,l,c)}function R(n,e){if(t(e))return n.stylize("undefined","undefined");if(p(e)){var r="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(r,"string")}if(E(e))return n.stylize(""+e,"number");if(g(e))return n.stylize(""+e,"boolean");if(s(e))return n.stylize("null","null")}function d(e){return"["+Error.prototype.toString.call(e)+"]"}function A(r,e,l,a,i){var n=[];for(var t=0,s=e.length;t<s;++t){if(b(e,String(t))){n.push(m(r,e,l,a,String(t),true))}else{n.push("")}}i.forEach(function(t){if(!t.match(/^\d+$/)){n.push(m(r,e,l,a,t,true))}});return n}function m(r,i,o,c,a,u){var e,n,l;l=Object.getOwnPropertyDescriptor(i,a)||{value:i[a]};if(l.get){if(l.set){n=r.stylize("[Getter/Setter]","special")}else{n=r.stylize("[Getter]","special")}}else{if(l.set){n=r.stylize("[Setter]","special")}}if(!b(c,a)){e="["+a+"]"}if(!n){if(r.seen.indexOf(l.value)<0){if(s(o)){n=f(r,l.value,null)}else{n=f(r,l.value,o-1)}if(n.indexOf("\n")>-1){if(u){n=n.split("\n").map(function(e){return" "+e}).join("\n").substr(2)}else{n="\n"+n.split("\n").map(function(e){return" "+e}).join("\n")}}}else{n=r.stylize("[Circular]","special")}}if(t(e)){if(u&&a.match(/^\d+$/)){return n}e=JSON.stringify(""+a);if(e.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){e=e.substr(1,e.length-2);e=r.stylize(e,"name")}else{e=e.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");e=r.stylize(e,"string")}}return e+": "+n}function P(n,t,e){var r=0;var l=n.reduce(function(n,e){r++;if(e.indexOf("\n")>=0)r++;return n+e.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(l>60){return e[0]+(t===""?"":t+"\n ")+" "+n.join(",\n ")+" "+e[1]}return e[0]+t+" "+n.join(", ")+" "+e[1]}function w(e){return Array.isArray(e)}e.isArray=w;function g(e){return typeof e==="boolean"}e.isBoolean=g;function s(e){return e===null}e.isNull=s;function C(e){return e==null}e.isNullOrUndefined=C;function E(e){return typeof e==="number"}e.isNumber=E;function p(e){return typeof e==="string"}e.isString=p;function S(e){return typeof e==="symbol"}e.isSymbol=S;function t(e){return e===void 0}e.isUndefined=t;function u(e){return l(e)&&y(e)==="[object RegExp]"}e.isRegExp=u;function l(e){return typeof e==="object"&&e!==null}e.isObject=l;function x(e){return l(e)&&y(e)==="[object Date]"}e.isDate=x;function i(e){return l(e)&&(y(e)==="[object Error]"||e instanceof Error)}e.isError=i;function o(e){return typeof e==="function"}e.isFunction=o;function T(e){return e===null||typeof e==="boolean"||typeof e==="number"||typeof e==="string"||typeof e==="symbol"||typeof e==="undefined"}e.isPrimitive=T;e.isBuffer=n("./support/isBuffer");function y(e){return Object.prototype.toString.call(e)}function h(e){return e<10?"0"+e.toString(10):e.toString(10)}var j=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function M(){var e=new Date;var n=[h(e.getHours()),h(e.getMinutes()),h(e.getSeconds())].join(":");return[e.getDate(),j[e.getMonth()],n].join(" ")}e.log=function(){console.log("%s - %s",M(),e.format.apply(e,arguments))};e.inherits=n("inherits");e._extend=function(n,e){if(!e||!l(e))return n;var t=Object.keys(e);var r=t.length;while(r--){n[t[r]]=e[t[r]]}return n};function b(e,n){return Object.prototype.hasOwnProperty.call(e,n)}}).call(this,n("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":133,_process:119,inherits:116}],135:[function(n,e,t){!function(n,M,r){"use strict";var O="Object",It="Function",N="Array",on="String",En="Number",xn="RegExp",Nn="Date",xt="Map",Vn="Set",ot="WeakMap",pt="WeakSet",j="Symbol",In="Promise",Gn="Math",Dt="Arguments",l="prototype",Hn="constructor",U="toString",ct=U+"Tag",bt="toLocaleString",Ft="hasOwnProperty",At="forEach",Mn="iterator",ln="@@"+Mn,jt="process",Pt="createElement",Lt=n[It],i=n[O],R=n[N],y=n[on],Tt=n[En],tn=n[xn],Zt=n[Nn],rt=n[xt],kt=n[Vn],nt=n[ot],_t=n[pt],x=n[j],d=n[Gn],Ln=n.TypeError,Ut=n.setTimeout,jn=n.setImmediate,Zn=n.clearImmediate,Qn=n[jt],mt=Qn&&Qn.nextTick,wn=n.document,dt=wn&&wn.documentElement,Qt=n.navigator,Bn=n.define,p=R[l],T=i[l],fn=Lt[l],$=1/0,hn=".";function f(e){return e!=null&&(typeof e=="object"||typeof e=="function")}function v(e){return typeof e=="function"}var en=o(/./.test,/\[native code\]\s*\}\s*$/,1);var qt={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},Jt=T[U];function J(e,n,t){if(e&&!s(e=t?e:e[l],yn))a(e,yn,n)}function pn(e){return e==r?e===r?"Undefined":"Null":Jt.call(e).slice(8,-1)}function Sn(n){var t=pn(n),e;return t==O&&(e=n[yn])?s(qt,e)?"~"+e:e:t}var z=fn.call,it=fn.apply,Y;function Tn(){var e=arguments.length,t=R(e),n=0,r=gn._,l=false;while(e>n)if((t[n]=arguments[n++])===r)l=true;return at(this,t,e,l,r,false)}function at(e,n,r,t,l,a,i){P(e);return function(){var c=a?i:this,f=arguments.length,o=0,u=0,s;if(!t&&!f)return B(e,n,c);s=n.slice();if(t)for(;r>o;o++)if(s[o]===l)s[o]=arguments[u++];while(f>u)s.push(arguments[u++]);return B(e,s,c)}}function o(e,n,t){P(e);if(~t&&n===r)return e;switch(t){case 1:return function(t){return e.call(n,t)};case 2:return function(t,r){return e.call(n,t,r)};case 3:return function(t,r,l){return e.call(n,t,r,l)}}return function(){return e.apply(n,arguments)}}function B(n,e,t){var l=t===r;switch(e.length|0){case 0:return l?n():n.call(t);case 1:return l?n(e[0]):n.call(t,e[0]);case 2:return l?n(e[0],e[1]):n.call(t,e[0],e[1]);case 3:return l?n(e[0],e[1],e[2]):n.call(t,e[0],e[1],e[2]);case 4:return l?n(e[0],e[1],e[2],e[3]):n.call(t,e[0],e[1],e[2],e[3]);case 5:return l?n(e[0],e[1],e[2],e[3],e[4]):n.call(t,e[0],e[1],e[2],e[3],e[4])}return n.apply(t,e)}function zt(e,r){var n=W((arguments.length<3?e:P(arguments[2]))[l]),t=it.call(e,n,r);return f(t)?t:n}var W=i.create,nn=i.getPrototypeOf,_n=i.setPrototypeOf,E=i.defineProperty,Kt=i.defineProperties,G=i.getOwnPropertyDescriptor,mn=i.keys,qn=i.getOwnPropertyNames,ft=i.getOwnPropertySymbols,s=o(z,T[Ft],2),Fn=i;function k(e){return Fn(w(e))}function $t(e){return e}function bn(){return this}function On(e,n){if(s(e,n))return e[n]}function Xn(e){return ft?qn(e).concat(ft(e)):qn(e)}var Ct=i.assign||function(s,c){var e=i(w(s)),o=arguments.length,n=1;while(o>n){var t=Fn(arguments[n++]),r=mn(t),u=r.length,l=0,a;while(u>l)e[a=r[l++]]=t[a]}return e};function Un(l,a){var e=k(l),n=mn(e),i=n.length,t=0,r;while(i>t)if(e[r=n[t++]]===a)return r}function un(e){return y(e).split(",")}var Et=p.push,rr=p.unshift,tr=p.slice,nr=p.splice,er=p.indexOf,X=p[At];function st(e){var t=e==1,a=e==2,s=e==3,n=e==4,l=e==6,u=e==5||l;return function(y){var h=i(w(this)),v=arguments[1],p=Fn(h),x=o(y,v,3),g=S(p.length),c=0,d=t?R(g):a?[]:r,f,m;for(;g>c;c++)if(u||c in p){f=p[c];m=x(f,c,h);if(e){if(t)d[c]=m;else if(m)switch(e){case 3:return true;case 5:return f;case 6:return c;case 2:d.push(f)}else if(n)return false}}return l?-1:s||n?n:d}}function Bt(e){return function(r){var t=k(this),l=S(t.length),n=V(arguments[1],l);if(e&&r!=r){for(;l>n;n++)if(Jn(t[n]))return e||n}else for(;l>n;n++)if(e||n in t){if(t[n]===r)return e||n}return!e&&-1}}function Dn(e,n){return typeof e=="function"?e:n}var An=9007199254740991,Xt=d.ceil,yt=d.floor,vt=d.max,q=d.min,wt=d.random,St=d.trunc||function(e){return(e>0?yt:Xt)(e)};function Jn(e){return e!=e}function kn(e){return isNaN(e)?0:St(e)}function S(e){return e>0?q(kn(e),An):0}function V(e,n){var e=kn(e);return e<0?vt(e+n,0):q(e,n)}function Rn(n,e,t){var r=f(e)?function(n){return e[n]}:e;return function(e){return y(t?e:this).replace(n,r)}}function Wn(e){return function(s){var t=y(w(this)),n=kn(s),i=t.length,l,a;if(n<0||n>=i)return e?"":r;l=t.charCodeAt(n);return l<55296||l>56319||n+1===i||(a=t.charCodeAt(n+1))<56320||a>57343?e?t.charAt(n):l:e?t.slice(n,n+2):(l-55296<<10)+(a-56320)+65536}}var Gt="Reduce of empty object with no initial value";function H(t,e,n){if(!t)throw Ln(n?e+n:e)}function w(e){if(e==r)throw Ln("Function called on null or undefined");return e}function P(e){H(v(e),e," is not a function!");return e}function A(e){H(f(e),e," is not an object!");return e}function Cn(e,n,t){H(e instanceof n,t,": use the 'new' operator!")}function dn(e,n){return{enumerable:!(e&1),configurable:!(e&2),writable:!(e&4),value:n}}function ht(e,n,t){e[n]=t;return e}function gt(e){return K?function(n,t,r){return E(n,t,dn(e,r))}:ht}function Kn(e){return j+"("+e+")_"+(++Vt+wt())[U](36)}function F(e,n){return x&&x[e]||(n?x:_)(j+hn+e)}var K=!!function(){try{return E({},hn,T)}catch(e){}}(),Vt=0,a=gt(1),b=x?ht:a,_=x||Kn;function Q(e,n){for(var t in n)a(e,t,n[t]);return e}var Pn=F("unscopables"),tt=p[Pn]||{};var Z=F(Mn),yn=F(ct),Ht=ln in p,c=_("iter"),D=1,I=2,rn={},Mt={},Nt=Z in p,Ot="keys"in p&&!("next"in[].keys());cn(Mt,bn);function cn(e,n){a(e,Z,n);Ht&&a(e,ln,n)}function an(e,n,t,r){e[l]=W(r||Mt,{next:dn(1,t)});J(e,n+" Iterator")}function lt(r,t,a,i){var e=r[l],n=On(e,Z)||On(e,ln)||i&&On(e,i)||a;if(M){cn(e,n);if(n!==a){var o=nn(n.call(new r));J(o,t+" Iterator",true);s(e,ln)&&cn(o,bn)}}rn[t]=n;rn[t+" Iterator"]=bn;return n}function et(a,e,i,o,s,u){function r(e){return function(){return new i(this,e)}}an(i,e,o);var l=r(D+I),n=r(I);if(s==I)n=lt(a,e,n,"values");else l=lt(a,e,l,"entries");if(s){t(C+h*Ot,e,{entries:l,keys:u?n:r(D),values:n})}}function u(e,n){return{value:n,done:!!e}}function $n(r){var e=i(r),t=n[j],l=(t&&t[Mn]||ln)in e;return l||Z in e||s(rn,Sn(e))}function sn(e){var t=n[j],r=e[t&&t[Mn]||ln],l=r||e[Z]||rn[Sn(e)];return A(l.call(e))}function zn(e,n,t){return t?B(e,n):e(n)}function vn(t,e,r,l){var a=sn(t),i=o(r,l,e?2:1),n;while(!(n=a.next()).done)if(zn(i,n.value,e)===false)return}var Wt=pn(Qn)==jt,m={},gn=M?n:m,Yt=n.core,Rt,h=1,L=2,g=4,C=8,ut=16,Yn=32;function t(i,s,p){var t,c,e,u,f=i&L,r=f?n:i&g?n[s]:(n[s]||T)[l],d=f?m:m[s]||(m[s]={});if(f)p=s;for(t in p){c=!(i&h)&&r&&t in r&&(!v(r[t])||en(r[t]));e=(c?r:p)[t];if(i&ut&&c)u=o(e,n);else if(i&Yn&&!M&&r[t]==e){u=function(n){return this instanceof e?new e(n):e(n)};u[l]=e[l]}else u=i&C&&v(e)?o(z,e):e;if(d[t]!=e)a(d,t,u);if(M&&r&&!c){if(f)r[t]=e;
else delete r[t]&&a(r,t,e)}}}if(typeof e!="undefined"&&e.exports)e.exports=m;else if(v(Bn)&&Bn.amd)Bn(function(){return m});else Rt=true;if(Rt||M){m.noConflict=function(){n.core=Yt;return m};n.core=m}t(L+h,{global:n});!function(r,e,n){if(!en(x)){x=function(t){H(!(this instanceof x),j+" is not a "+Hn);var e=Kn(t);K&&n&&E(T,e,{configurable:true,set:function(n){a(this,e,n)}});return b(W(x[l]),r,e)};a(x[l],U,function(){return this[r]})}t(L+Yn,{Symbol:x});var i={"for":function(n){return s(e,n+="")?e[n]:e[n]=x(n)},iterator:Z,keyFor:Tn.call(Un,e),toStringTag:yn=F(ct,true),unscopables:Pn,pure:_,set:b,useSetter:function(){n=true},useSimple:function(){n=false}};X.call(un("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive"),function(e){i[e]=F(e)});t(g,j,i);J(x,j);t(L,{Reflect:{ownKeys:Xn}})}(_("tag"),{},true);!function(j,P,nn,_){var Z=n.RangeError,cn=Tt.isInteger||function(e){return!f(e)&&P(e)&&yt(e)===e},W=d.sign||function bn(e){return(e=+e)==0||e!=e?e:e<0?-1:1},F=d.pow,Q=d.abs,v=d.exp,x=d.log,B=d.sqrt,mn=y.fromCharCode,gn=Wn(true);var ln={assign:Ct,is:function(e,n){return e===n?e!==0||1/e===1/n:e!=e&&n!=n}};"__proto__"in T&&function(n,e){try{e=o(z,G(T,"__proto__").set,2);e({},p)}catch(t){n=true}ln.setPrototypeOf=_n=_n||function(r,t){A(r);H(t===null||f(t),t,": can't set as prototype!");if(n)r.__proto__=t;else e(r,t);return r}}();t(g,O,ln);function an(e){return!P(e=+e)||e==0?e:e<0?-an(-e):x(e+B(e*e+1))}t(g,En,{EPSILON:F(2,-52),isFinite:function(e){return typeof e=="number"&&P(e)},isInteger:cn,isNaN:Jn,isSafeInteger:function(e){return cn(e)&&Q(e)<=An},MAX_SAFE_INTEGER:An,MIN_SAFE_INTEGER:-An,parseFloat:parseFloat,parseInt:parseInt});t(g,Gn,{acosh:function(e){return(e=+e)<1?NaN:x(e+B(e*e-1))},asinh:an,atanh:function(e){return(e=+e)==0?e:x((1+e)/(1-e))/2},cbrt:function(e){return W(e=+e)*F(Q(e),1/3)},clz32:function(e){return(e>>>=0)?32-e[U](2).length:32},cosh:function(e){return(v(e=+e)+v(-e))/2},expm1:function(e){return(e=+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(i,s){var r=0,n=arguments.length,l=n,a=R(n),t=-$,e;while(n--){e=a[n]=+arguments[n];if(e==$||e==-$)return $;if(e>t)t=e}t=e||1;while(l--)r+=F(a[l]/t,2);return t*B(r)},imul:function(a,i){var e=65535,n=+a,t=+i,r=e&n,l=e&t;return 0|r*l+((e&n>>>16)*l+r*(e&t>>>16)<<16>>>0)},log1p:function(e){return(e=+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:W,sinh:function(e){return(e=+e)==0?e:(v(e)-v(-e))/2},tanh:function(e){return P(e=+e)?e==0?e:(v(e)-v(-e))/(v(e)+v(-e)):W(e)},trunc:St});J(d,Gn,true);function Y(e){if(pn(e)==xn)throw Ln()}t(g,on,{fromCodePoint:function(l){var n=[],r=arguments.length,t=0,e;while(r>t){e=+arguments[t++];if(V(e,1114111)!==e)throw Z(e+" is not a valid code point");n.push(e<65536?mn(e):mn(((e-=65536)>>10)+55296,e%1024+56320))}return n.join("")},raw:function(r){var t=k(r.raw),l=S(t.length),a=arguments.length,n=[],e=0;while(l>e){n.push(y(t[e++]));if(e<a)n.push(y(arguments[e]))}return n.join("")}});t(C,on,{codePointAt:Wn(false),endsWith:function(e){Y(e);var n=y(w(this)),t=arguments[1],l=S(n.length),a=t===r?l:q(S(t),l);e+="";return n.slice(a-e.length,a)===e},includes:function(e){Y(e);return!!~y(w(this)).indexOf(e,arguments[1])},repeat:function(r){var n=y(w(this)),t="",e=kn(r);if(0>e||e==$)throw Z("Count can't be negative");for(;e>0;(e>>>=1)&&(n+=n))if(e&1)t+=n;return t},startsWith:function(e){Y(e);var n=y(w(this)),t=S(q(arguments[1],n.length));e+="";return n.slice(t,t+e.length)===e}});et(y,on,function(e){b(this,c,{o:y(e),i:0})},function(){var e=this[c],t=e.o,r=e.i,n;if(r>=t.length)return u(1);n=gn.call(t,r);e.i+=n.length;return u(0,n)});t(g,N,{from:function(d){var n=i(w(d)),t=new(Dn(this,R)),u=arguments[1],f=arguments[2],l=u!==r,s=l?o(u,f,2):r,e=0,c;if($n(n))for(var p=sn(n),a;!(a=p.next()).done;e++){t[e]=l?s(a.value,e):a.value}else for(c=S(n.length);c>e;e++){t[e]=l?s(n[e],e):n[e]}t.length=e;return t},of:function(){var e=0,n=arguments.length,t=new(Dn(this,R))(n);while(n>e)t[e]=arguments[e++];t.length=n;return t}});t(C,N,{copyWithin:function(u,c){var t=i(w(this)),l=S(t.length),e=V(u,l),n=V(c,l),o=arguments[2],f=o===r?l:V(o,l),a=q(f-n,l-e),s=1;if(n<e&&e<n+a){s=-1;n=n+a-1;e=e+a-1}while(a-->0){if(n in t)t[e]=t[n];else delete t[e];e+=s;n+=s}return t},fill:function(a){var e=i(w(this)),n=S(e.length),t=V(arguments[1],n),l=arguments[2],s=l===r?n:V(l,n);while(s>t)e[t++]=a;return e},find:st(5),findIndex:st(6)});et(R,N,function(e,n){b(this,c,{o:k(e),i:0,k:n})},function(){var n=this[c],t=n.o,l=n.k,e=n.i++;if(!t||e>=t.length)return n.o=r,u(1);if(l==D)return u(0,e);if(l==I)return u(0,t[e]);return u(0,[e,t[e]])},I);rn[Dt]=rn[N];J(n.JSON,"JSON",true);function e(r,n){var e=i[r],l=m[O][r],a=0,s={};if(!l||en(l)){s[r]=n==1?function(n){return f(n)?e(n):n}:n==2?function(n){return f(n)?e(n):true}:n==3?function(n){return f(n)?e(n):false}:n==4?function(n,t){return e(k(n),t)}:function(n){return e(k(n))};try{e(hn)}catch(o){a=1}t(g+h*a,O,s)}}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");if(M){nn[yn]=hn;if(pn(nn)!=hn)a(T,U,function(){return"[object "+Sn(this)+"]"});_ in fn||E(fn,_,{configurable:true,get:function(){var e=y(this).match(/^\s*function ([^ (]*)/),n=e?e[1]:"";s(this,_)||E(this,_,dn(5,n));return n},set:function(e){s(this,_)||E(this,_,dn(0,e))}});var vn=tn;var L=function wn(e,n){return new vn(pn(e)==xn&&n!==r?e.source:e,n)};if(K&&!function(){try{return tn(/a/g,"i")=="/a/i"}catch(e){}}()){X.call(qn(tn),function(e){e in L||E(L,e,{configurable:true,get:function(){return tn[e]},set:function(n){tn[e]=n}})});j[Hn]=L;L[l]=j;a(n,xn,L)}if(/./g.flags!="g")E(j,"flags",{configurable:true,get:Rn(/^.*\/(\w*)$/,"$1")});X.call(un("find,findIndex,fill,copyWithin,entries,keys,values"),function(e){tt[e]=true});Pn in p||a(p,Pn,tt)}}(tn[l],isFinite,{},"name");v(jn)&&v(Zn)||function(f){var p=n.postMessage,u=n.addEventListener,c=n.MessageChannel,l=0,t={},e,a,i;jn=function(n){var r=[],a=1;while(arguments.length>a)r.push(arguments[a++]);t[++l]=function(){B(v(n)?n:Lt(n),r)};e(l);return l};Zn=function(e){delete t[e]};function r(e){if(s(t,e)){var n=t[e];delete t[e];n()}}function d(e){r(e.data)}if(Wt){e=function(e){mt(Tn.call(r,e))}}else if(u&&v(p)&&!n.importScripts){e=function(e){p(e,"*")};u("message",d,false)}else if(v(c)){a=new c;i=a.port2;a.port1.onmessage=d;e=o(i.postMessage,i,1)}else if(wn&&f in wn[Pt]("script")){e=function(e){dt.appendChild(wn[Pt]("script"))[f]=function(){dt.removeChild(this);r(e)}}}else{e=function(e){Ut(Tn.call(r,e),0)}}}("onreadystatechange");t(L+ut,{setImmediate:jn,clearImmediate:Zn});!function(e,n){v(e)&&v(e.resolve)&&e.resolve(n=new e(function(){}))==n||function(c,i){function s(n){var e;if(f(n))e=n.then;return v(e)?e:false}function t(n){var e=n.chain;e.length&&c(function(){var t=n.msg,l=n.state==1,r=0;while(e.length>r)!function(e){var r=l?e.ok:e.fail,n,a;try{if(r){n=r===true?t:r(t);if(n===e.P){e.rej(Ln(In+"-chain cycle"))}else if(a=s(n)){a.call(n,e.res,e.rej)}else e.res(n)}else e.rej(t)}catch(i){e.rej(i)}}(e[r++]);e.length=0})}function u(l){var e=this,a,r;if(e.done)return;e.done=true;e=e.def||e;try{if(a=s(l)){r={def:e,done:false};a.call(l,o(u,r,1),o(n,r,1))}else{e.msg=l;e.state=1;t(e)}}catch(i){n.call(r||{def:e,done:false},i)}}function n(n){var e=this;if(e.done)return;e.done=true;e=e.def||e;e.msg=n;e.state=2;t(e)}e=function(l){P(l);Cn(this,e,In);var t={chain:[],state:0,done:false,msg:r};a(this,i,t);try{l(o(u,t,1),o(n,t,1))}catch(s){n.call(t,s)}};Q(e[l],{then:function(r,l){var e={ok:v(r)?r:true,fail:v(l)?l:false},a=e.P=new this[Hn](function(n,t){e.res=P(n);e.rej=P(t)}),n=this[i];n.chain.push(e);n.state&&t(n);return a},"catch":function(e){return this.then(r,e)}});Q(e,{all:function(t){var n=this,e=[];return new n(function(a,i){vn(t,false,Et,e);var r=e.length,l=R(r);if(r)X.call(e,function(e,t){n.resolve(e).then(function(e){l[t]=e;--r||a(l)},i)});else a(l)})},race:function(n){var e=this;return new e(function(t,r){vn(n,false,function(n){e.resolve(n).then(t,r)})})},reject:function(e){return new this(function(t,n){n(e)})},resolve:function(e){return f(e)&&nn(e)===this[l]?e:new this(function(n,t){n(e)})}})}(mt||jn,_("def"));J(e,In);t(L+h*!en(e),{Promise:e})}(n[In]);!function(){var e=_("uid"),p=_("data"),n=_("weak"),d=_("last"),i=_("first"),m=K?_("size"):"size",v=0;function y(n,o,T,A,g,f){var _=g?"set":"add",x=n&&n[l],C={};function S(e,n){if(n!=r)vn(n,g,e[_],e);return e}function y(e,n){var t=x[e];M&&a(x,e,function(e,r){var l=t.call(this,e===0?0:e,r);return n?this:l})}if(!en(n)||!(f||!Ot&&s(x,"entries"))){n=f?function(t){Cn(this,n,o);b(this,e,v++);S(this,t)}:function(t){var e=this;Cn(e,n,o);b(e,p,W(null));b(e,m,0);b(e,d,r);b(e,i,r);S(e,t)};Q(Q(n[l],T),A);f||E(n[l],"size",{get:function(){return w(this[m])}})}else{var P=n,k=new n,j=k[_](f?{}:-0,1),R;if(!Nt||!n.length){n=function(e){Cn(this,n,o);return S(new P,e)};n[l]=x}f||k[At](function(n,e){R=1/e===-$});if(R){y("delete");y("has");g&&y("get")}if(R||j!==k)y(_,true)}J(n,o);C[o]=n;t(L+Yn+h*!en(n),C);f||et(n,o,function(e,n){b(this,c,{o:e,k:n})},function(){var n=this[c],t=n.o,l=n.k,e=n.l;while(e&&e.r)e=e.p;if(!t||!(n.l=e=e?e.n:t[i]))return n.o=r,u(1);if(l==D)return u(0,e.k);if(l==I)return u(0,e.v);return u(0,[e.k,e.v])},g?D+I:I,!g);return n}function g(n,t){if(!f(n))return(typeof n=="string"?"S":"P")+n;if(!s(n,e)){if(t)a(n,e,++v);else return""}return"O"+n[e]}function x(e,a,s){var t=g(a,true),r=e[p],l=e[d],n;if(t in r)r[t].v=s;else{n=r[t]={k:a,v:s,p:l};if(!e[i])e[i]=n;if(l)l.n=n;e[d]=n;e[m]++}return e}function S(e,l){var a=e[p],n=a[l],t=n.n,r=n.p;delete a[l];n.r=true;if(r)r.n=t;if(t)t.p=r;if(e[i]==n)e[i]=t;if(e[d]==n)e[d]=r;e[m]--}var k={clear:function(){for(var e in this[p])S(this,e)},"delete":function(t){var e=g(t),n=e in this[p];if(n)S(this,e);return n},forEach:function(n){var t=o(n,arguments[1],3),e;while(e=e?e.n:this[i]){t(e.v,e.k,this);while(e&&e.r)e=e.p}},has:function(e){return g(e)in this[p]}};rt=y(rt,xt,{get:function(n){var e=this[p][g(n)];return e&&e.v},set:function(e,n){return x(this,e===0?0:e,n)}},k,true);kt=y(kt,Vn,{add:function(e){return x(this,e=e===0?0:e,e)}},k);function R(r,t,l){s(A(t),n)||a(t,n,{});t[n][r[e]]=l;return r}function C(t){return f(t)&&s(t,n)&&s(t[n],this[e])}var T={"delete":function(t){return C.call(this,t)&&delete t[n][this[e]]},has:C};nt=y(nt,ot,{get:function(t){if(f(t)&&s(t,n))return t[n][this[e]]},set:function(e,n){return R(this,e,n)}},T,true,true);_t=y(_t,pt,{add:function(e){return R(this,e,true)}},T,false,true)}();!function(){function e(e){var n=[],t;for(t in e)n.push(t);b(this,c,{o:e,a:n,i:0})}an(e,O,function(){var e=this[c],n=e.a,t;do{if(e.i>=n.length)return u(1)}while(!((t=n[e.i++])in e.o));return u(0,t)});function n(e){return function(n){A(n);try{return e.apply(r,arguments),true}catch(t){return false}}}function l(n,t){var a=arguments.length<3?n:arguments[2],e=G(A(n),t),i;if(e)return e.get?e.get.call(a):e.value;return f(i=nn(n))?l(i,t,a):r}function a(r,n,l){var t=arguments.length<4?r:arguments[3],e=G(A(r),n),i;if(e){if(e.writable===false)return false;if(e.set)return e.set.call(t,l),true}if(f(i=nn(r)))return a(i,n,l,t);e=G(t,n)||dn(0);e.value=l;return E(t,n,e),true}var s={apply:o(z,it,3),construct:zt,defineProperty:n(E),deleteProperty:function(e,n){var t=G(A(e),n);return t&&!t.configurable?false:delete e[n]},enumerate:function(n){return new e(A(n))},get:l,getOwnPropertyDescriptor:G,getPrototypeOf:nn,has:function(e,n){return n in e},isExtensible:i.isExtensible||function(e){return!!A(e)},ownKeys:Xn,preventExtensions:n(i.preventExtensions||$t),set:a};if(_n)s.setPrototypeOf=function(e,n){return _n(A(e),n),true};t(L,{Reflect:{}});t(g,"Reflect",s)}();!function(){t(C,N,{includes:Bt(true)});t(C,on,{at:Wn(true)});function e(e){return function(a){var i=k(a),t=mn(a),r=t.length,n=0,l=R(r),s;if(e)while(r>n)l[n]=[s=t[n++],i[s]];else while(r>n)l[n]=i[t[n++]];return l}}t(g,O,{values:e(false),entries:e(true)});t(g,xn,{escape:Rn(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(e){Y=F(e+"Get",true);var n=F(e+Vn,true),r=F(e+"Delete",true);t(g,j,{referenceGet:Y,referenceSet:n,referenceDelete:r});a(fn,Y,bn);function i(t){if(t){var e=t[l];a(e,Y,e.get);a(e,n,e.set);a(e,r,e["delete"])}}i(rt);i(nt)}("reference");!function(y){function n(e){var n=W(null);if(e!=r){if($n(e)){for(var a=sn(e),l,t;!(l=a.next()).done;){t=l.value;n[t[0]]=t[1]}}else Ct(n,e)}return n}n[l]=null;function d(e,n){b(this,c,{o:k(e),a:mn(e),i:0,k:n})}an(d,y,function(){var e=this[c],t=e.o,r=e.a,l=e.k,n;do{if(e.i>=r.length)return u(1)}while(!s(t,n=r[e.i++]));if(l==D)return u(0,n);if(l==I)return u(0,t[n]);return u(0,[n,t[n]])});function a(e){return function(n){return new d(n,e)}}function e(e){var l=e==1,t=e==4;return function(p,d,m){var h=o(d,m,3),f=k(p),u=l||e==7||e==2?new(Dn(this,n)):r,a,c,i;for(a in f)if(s(f,a)){c=f[a];i=h(c,a,p);if(e){if(l)u[a]=i;else if(i)switch(e){case 2:u[a]=c;break;case 3:return true;case 5:return c;case 6:return a;case 7:u[i[0]]=i[1]}else if(t)return false}}return e==3||t?t:u}}function m(e){return function(p,d,a){P(d);var l=k(p),o=mn(l),m=o.length,u=0,t,c,f;if(e)t=a==r?new(Dn(this,n)):i(a);else if(arguments.length<3){H(m,Gt);t=l[o[u++]]}else t=i(a);while(m>u)if(s(l,c=o[u++])){f=d(t,l[c],c,p);if(e){if(f===false)break}else t=f}return t}}var g=e(6);function v(n,e){return(e==e?Un(n,e):g(n,Jn))!==r}var p={keys:a(D),values:a(I),entries:a(D+I),forEach:e(0),map:e(1),filter:e(2),some:e(3),every:e(4),find:e(5),findKey:g,mapPairs:e(7),reduce:m(false),turn:m(true),keyOf:Un,includes:v,has:s,get:On,set:gt(0),isDict:function(e){return f(e)&&nn(e)===n[l]}};if(Y)for(var x in p)!function(e){function n(){for(var n=[this],t=0;t<arguments.length;)n.push(arguments[t++]);return B(e,n)}e[Y]=function(){return n}}(p[x]);t(L+h,{Dict:Q(n,p)})}("Dict");!function(e,a){function n(t,r){if(!(this instanceof n))return new n(t,r);this[c]=sn(t);this[e]=!!r}an(n,"Wrapper",function(){return this[c].next()});var i=n[l];cn(i,function(){return this[c]});function s(t){function n(n,t,r){this[c]=sn(n);this[e]=n[e];this[a]=o(t,r,n[e]?2:1)}an(n,"Chain",t,i);cn(n[l],bn);return n}var f=s(function(){var n=this[c].next();return n.done?n:u(0,zn(this[a],n.value,this[e]))});var p=s(function(){for(;;){var n=this[c].next();if(n.done||zn(this[a],n.value,this[e]))return n}});Q(i,{of:function(n,t){vn(this,this[e],n,t)},array:function(e,t){var n=[];vn(e!=r?this.map(e,t):this,false,Et,n);return n},filter:function(e,n){return new p(this,e,n)},map:function(e,n){return new f(this,e,n)}});n.isIterable=$n;n.getIterator=sn;t(L+h,{$for:n})}("entries",_("fn"));!function(e,l){m._=gn._=gn._||{};t(C+h,It,{part:Tn,by:function(i){var e=this,l=gn._,s=false,n=arguments.length,u=i===l,t=+!u,c=t,r,a;if(u){r=e;e=z}else r=i;if(n<2)return o(e,r,-1);a=R(n-c);while(n>t)if((a[t-c]=arguments[t++])===l)s=true;return at(e,a,n,s,l,true,r)},only:function(e,n){var t=P(this),r=S(e),l=arguments.length>1;return function(){var a=q(r,arguments.length),i=R(a),e=0;while(a>e)i[e]=arguments[e++];return B(t,i,l?n:this)}}});function n(i){var n=this,t={};return a(n,e,function(e){if(e===r||!(e in n))return l.call(n);return s(t,e)?t[e]:t[e]=o(n[e],n,-1)})[e](i)}a(gn._,U,function(){return e});a(T,e,n);K||a(p,e,n)}(K?Kn("tie"):bt,T[bt]);!function(){function e(e,n){var t=Xn(k(n)),a=t.length,r=0,l;while(a>r)E(e,l=t[r++],G(n,l));return e}t(g+h,O,{isObject:f,classof:Sn,define:e,make:function(n,t){return e(W(n),t)}})}();t(C+h,N,{turn:function(n,t){P(n);var l=t==r?[]:i(t),a=Fn(this),s=S(a.length),e=0;while(s>e)if(n(l,a[e],e++,this)===false)break;return l}});if(M)tt.turn=true;!function(n){function e(e,t){X.call(un(e),function(e){if(e in p)n[e]=o(z,p[e],t)})}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");t(g,N,n)}({});!function(e){function n(e){b(this,c,{l:S(e),i:0})}an(n,En,function(){var e=this[c],n=e.i++;return n<e.l?u(0,n):u(1)});lt(Tt,En,function(){return new n(this)});e.random=function(e){var n=+this,t=e==r?0:+e,l=q(n,t);return wt()*(vt(n,t)-l)+l};X.call(un("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(n){var t=d[n];if(t)e[n]=function(){var e=[+this],n=0;while(arguments.length>n)e.push(arguments[n++]);return B(t,e)}});t(C+h,En,e)}({});!function(){var e={"&":"&","<":"<",">":">",'"':""","'":"'"},r={},n;for(n in e)r[e[n]]=n;t(C+h,on,{escapeHTML:Rn(/[&<>"']/g,e),unescapeHTML:Rn(/&(?:amp|lt|gt|quot|apos);/g,r)})}();!function(d,p,n,r,u,i,o,l,c){function f(t){return function(m,p){var h=this,f=n[s(n,p)?p:r];function a(e){return h[t+e]()}return y(m).replace(d,function(n){switch(n){case"s":return a(u);case"ss":return e(a(u));case"m":return a(i);case"mm":return e(a(i));case"h":return a(o);case"hh":return e(a(o));case"D":return a(Nn);case"DD":return e(a(Nn));case"W":return f[0][a("Day")];case"N":return a(l)+1;case"NN":return e(a(l)+1);case"M":return f[2][a(l)];case"MM":return f[1][a(l)];case"Y":return a(c);case"YY":return e(a(c)%100)}return n})}}function e(e){return e>9?e:"0"+e}function a(r,e){function t(t){var n=[];X.call(un(e.months),function(e){n.push(e.replace(p,"$"+t))});return n}n[r]=[un(e.weekdays),t(1),t(2)];return m}t(C+h,Nn,{format:f("get"),formatUTC:f("getUTC")});a(r,{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:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});m.locale=function(e){return s(n,e)?r=e:r};m.addLocale=a}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(typeof self!="undefined"&&self.Math===Math?self:Function("return this")(),false)},{}],136:[function(n,t,e){(function(t,n){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],n)}else if(typeof e!=="undefined"){n(e)}else{n(t.estraverse={})}})(this,function r(t){"use strict";var c,i,s,d,g,u,n,r,l;function h(){}i=Array.isArray;if(!i){i=function k(e){return Object.prototype.toString.call(e)==="[object Array]"}}function m(t){var r={},e,n;for(e in t){if(t.hasOwnProperty(e)){n=t[e];if(typeof n==="object"&&n!==null){r[e]=m(n)}else{r[e]=n}}}return r}function v(n){var t={},e;for(e in n){if(n.hasOwnProperty(e)){t[e]=n[e]}}return t}h(v);function E(l,a){var n,e,t,r;e=l.length;t=0;while(e){n=e>>>1;r=t+n;if(a(l[r])){e=n}else{t=r+1;e-=n+1}}return t}function x(l,a){var n,e,t,r;e=l.length;t=0;while(e){n=e>>>1;r=t+n;if(a(l[r])){t=r+1;e-=n+1}else{e=n}}return t}h(x);g=Object.create||function(){function e(){}return function(n){e.prototype=n;return new e}}();u=Object.keys||function(t){var e=[],n;for(n in t){e.push(n)}return e};function b(e,n){u(n).forEach(function(t){e[t]=n[t]});return e}c={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",AwaitExpression:"AwaitExpression",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"};d={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AwaitExpression:["argument"],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"]};n={};r={};l={};s={Break:n,Skip:r,Remove:l};function o(e,n){this.parent=e;this.key=n}o.prototype.replace=function I(e){this.parent[this.key]=e};o.prototype.remove=function R(){if(i(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function a(e,n,t,r){this.node=e;this.path=n;this.wrap=t;this.ref=r}function e(){}e.prototype.path=function C(){var e,r,n,l,t,a;function s(t,e){if(i(e)){for(n=0,l=e.length;n<l;++n){t.push(e[n])}}else{t.push(e)}}if(!this.__current.path){return null}t=[];for(e=2,r=this.__leavelist.length;e<r;++e){a=this.__leavelist[e];s(t,a.path)}s(t,this.__current.path);return t};e.prototype.type=function(){var e=this.current();return e.type||this.__current.wrap};e.prototype.parents=function A(){var e,t,n;n=[];for(e=1,t=this.__leavelist.length;e<t;++e){n.push(this.__leavelist[e].node)}return n};e.prototype.current=function T(){return this.__current.node};e.prototype.__execute=function L(n,t){var r,e;e=undefined;r=this.__current;this.__current=t;this.__state=null;if(n){e=n.call(this,t.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=r;return e};e.prototype.notify=function P(e){this.__state=e};e.prototype.skip=function(){this.notify(r)};e.prototype["break"]=function(){this.notify(n)};e.prototype.remove=function(){this.notify(l)};e.prototype.__initialize=function(n,e){this.visitor=e;this.root=n;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=e.fallback==="iteration";this.__keys=d;if(e.keys){this.__keys=b(g(this.__keys),e.keys)}};function f(e){if(e==null){return false}return typeof e==="object"&&typeof e.type==="string"}function y(e,n){return(e===c.ObjectExpression||e===c.ObjectPattern)&&"properties"===n}e.prototype.traverse=function j(b,x){var s,h,e,d,g,c,p,m,l,o,t,v;this.__initialize(b,x);v={};s=this.__worklist;h=this.__leavelist;s.push(new a(b,null,null,null));h.push(new a(null,null,null,null));while(s.length){e=s.pop();if(e===v){e=h.pop();c=this.__execute(x.leave,e);if(this.__state===n||c===n){return}continue}if(e.node){c=this.__execute(x.enter,e);if(this.__state===n||c===n){return}s.push(v);h.push(e);if(this.__state===r||c===r){continue}d=e.node;g=e.wrap||d.type;o=this.__keys[g];if(!o){if(this.__fallback){o=u(d)}else{throw new Error("Unknown node type "+g+".")}}m=o.length;while((m-=1)>=0){p=o[m];t=d[p];if(!t){continue}if(i(t)){l=t.length;while((l-=1)>=0){if(!t[l]){continue}if(y(g,o[m])){e=new a(t[l],[p,l],"Property",null)}else if(f(t[l])){e=new a(t[l],[p,l],null,null)}else{continue}s.push(e)}}else if(f(t)){s.push(new a(t,p,null,null))}}}}};e.prototype.replace=function M(E,w){function S(n){var t,r,e,l;if(n.ref.remove()){r=n.ref.key;l=n.ref.parent;t=p.length;while(t--){e=p[t];if(e.ref&&e.ref.parent===l){if(e.ref.key<r){break}--e.ref.key}}}}var p,b,m,v,t,e,x,c,d,s,_,g,h;this.__initialize(E,w);_={};p=this.__worklist;b=this.__leavelist;g={root:E};e=new a(E,null,null,new o(g,"root"));p.push(e);b.push(e);while(p.length){e=p.pop();if(e===_){e=b.pop();t=this.__execute(w.leave,e);if(t!==undefined&&t!==n&&t!==r&&t!==l){e.ref.replace(t)}if(this.__state===l||t===l){S(e)}if(this.__state===n||t===n){return g.root}continue}t=this.__execute(w.enter,e);if(t!==undefined&&t!==n&&t!==r&&t!==l){e.ref.replace(t);e.node=t}if(this.__state===l||t===l){S(e);e.node=null}if(this.__state===n||t===n){return g.root}m=e.node;if(!m){continue}p.push(_);b.push(e);if(this.__state===r||t===r){continue}v=e.wrap||m.type;d=this.__keys[v];if(!d){if(this.__fallback){d=u(m)}else{throw new Error("Unknown node type "+v+".")}}x=d.length;while((x-=1)>=0){h=d[x];s=m[h];if(!s){continue}if(i(s)){c=s.length;while((c-=1)>=0){if(!s[c]){continue}if(y(v,d[x])){e=new a(s[c],[h,c],"Property",new o(s,c))}else if(f(s[c])){e=new a(s[c],[h,c],null,new o(s,c))}else{continue}p.push(e)}}else if(f(s)){p.push(new a(s,h,null,new o(m,h)))}}}return g.root};function p(n,t){var r=new e;return r.traverse(n,t)}function w(n,t){var r=new e;return r.replace(n,t)}function _(e,t){var n;n=E(t,function r(n){return n.range[0]>e.range[0]});e.extendedRange=[e.range[0],e.range[1]];if(n!==t.length){e.extendedRange[1]=t[n].range[0]}n-=1;if(n>=0){e.extendedRange[0]=t[n].range[1]}return e}function S(r,l,o){var n=[],i,a,t,e;if(!r.range){throw new Error("attachComments needs range information")}if(!o.length){if(l.length){for(t=0,a=l.length;t<a;t+=1){i=m(l[t]);i.extendedRange=[0,r.range[0]];n.push(i)}r.leadingComments=n}return r}for(t=0,a=l.length;t<a;t+=1){n.push(_(m(l[t]),o))}e=0;p(r,{enter:function(t){var r;while(e<n.length){r=n[e];if(r.extendedRange[1]>t.range[0]){break}if(r.extendedRange[1]===t.range[0]){if(!t.leadingComments){t.leadingComments=[]}t.leadingComments.push(r);n.splice(e,1)}else{e+=1}}if(e===n.length){return s.Break}if(n[e].extendedRange[0]>t.range[1]){return s.Skip}}});e=0;p(r,{leave:function(t){var r;while(e<n.length){r=n[e];if(t.range[1]<r.extendedRange[0]){break}if(t.range[1]===r.extendedRange[0]){if(!t.trailingComments){t.trailingComments=[]}t.trailingComments.push(r);n.splice(e,1)}else{e+=1}}if(e===n.length){return s.Break}if(n[e].extendedRange[0]>t.range[1]){return s.Skip}}});return r}t.version="1.8.1-dev";t.Syntax=c;t.traverse=p;t.replace=w;t.attachComments=S;t.VisitorKeys=d;t.VisitorOption=s;t.Controller=e;t.cloneEnvironment=function(){return r({})};return t})},{}],137:[function(n,e,t){(function(){"use strict";function r(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 l(e){if(e==null){return false}switch(e.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function n(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 n(e)||e!=null&&e.type==="FunctionDeclaration"}function t(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 i(n){var e;if(n.type!=="IfStatement"){return false}if(n.alternate==null){return false}e=n.consequent;do{if(e.type==="IfStatement"){if(e.alternate==null){return true}}e=t(e)}while(e);return false}e.exports={isExpression:r,isStatement:n,isIterationStatement:l,isSourceElement:a,isProblematicIfStatement:i,trailingStatement:t}})()},{}],138:[function(n,e,t){(function(){"use strict";var n,t;n={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};
function r(e){return e>=48&&e<=57}function l(e){return r(e)||97<=e&&e<=102||65<=e&&e<=70}function a(e){return e>=48&&e<=55}t=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function i(e){return e===32||e===9||e===11||e===12||e===160||e>=5760&&t.indexOf(e)>=0}function s(e){return e===10||e===13||e===8232||e===8233}function o(e){return e>=97&&e<=122||e>=65&&e<=90||e===36||e===95||e===92||e>=128&&n.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&&n.NonAsciiIdentifierPart.test(String.fromCharCode(e))}e.exports={isDecimalDigit:r,isHexDigit:l,isOctalDigit:a,isWhiteSpace:i,isLineTerminator:s,isIdentifierStart:o,isIdentifierPart:u}})()},{}],139:[function(e,n,t){(function(){"use strict";var l=e("./code");function o(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,n){if(!n&&e==="yield"){return false}return t(e,n)}function t(e,n){if(n&&o(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 i(e,n){return e==="null"||e==="true"||e==="false"||a(e,n)}function s(e,n){return e==="null"||e==="true"||e==="false"||t(e,n)}function u(e){return e==="eval"||e==="arguments"}function r(n){var t,r,e;if(n.length===0){return false}e=n.charCodeAt(0);if(!l.isIdentifierStart(e)||e===92){return false}for(t=1,r=n.length;t<r;++t){e=n.charCodeAt(t);if(!l.isIdentifierPart(e)||e===92){return false}}return true}function c(e,n){return r(e)&&!i(e,n)}function f(e,n){return r(e)&&!s(e,n)}n.exports={isKeywordES5:a,isKeywordES6:t,isReservedWordES5:i,isReservedWordES6:s,isRestrictedWord:u,isIdentifierName:r,isIdentifierES5:c,isIdentifierES6:f}})()},{"./code":138}],140:[function(e,t,n){(function(){"use strict";n.ast=e("./ast");n.code=e("./code");n.keyword=e("./keyword")})()},{"./ast":137,"./code":138,"./keyword":139}],141:[function(n,t,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}},{}],142:[function(t,e,n){(function(t){(function(){var u;var A=[],P=[];var Q=0;var R=+new Date+"";var T=75;var U=40;var N=" \f "+"\n\r\u2028\u2029"+" ";var X=/\b__p \+= '';/g,nn=/\b(__p \+=) '' \+/g,en=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var Z=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var K=/\w*$/;var $=/^\s*function[ \n\r\t]+\w/;var F=/<%=([\s\S]+?)%>/g;var tn=RegExp("^["+N+"]*0+(?=.$)");var _=/($^)/;var M=/\bthis\b/;var W=/['\n\r\t\u2028\u2029\\]/g;var J=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var q=0;var b="[object Arguments]",E="[object Array]",x="[object Boolean]",v="[object Date]",B="[object Function]",y="[object Number]",o="[object Object]",g="[object RegExp]",d="[object String]";var s={};s[B]=false;s[b]=s[E]=s[x]=s[v]=s[y]=s[o]=s[g]=s[d]=true;var k={leading:false,maxWait:0,trailing:false};var O={configurable:false,enumerable:false,value:null,writable:false};var l={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var V={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var f=l[typeof window]&&window||this;var w=l[typeof n]&&n&&!n.nodeType&&n;var I=l[typeof e]&&e&&!e.nodeType&&e;var z=I&&I.exports===w&&w;var p=l[typeof t]&&t;if(p&&(p.global===p||p.window===p)){f=p}function m(e,t,r){var n=(r||0)-1,l=e?e.length:0;while(++n<l){if(e[n]===t){return n}}return-1}function S(e,t){var n=typeof t;e=e.cache;if(n=="boolean"||t==null){return e[t]?0:-1}if(n!="number"&&n!="string"){n="object"}var r=n=="number"?t:R+t;e=(e=e[n])&&e[r];return n=="object"?e&&m(e,t)>-1?0:-1:e?0:-1}function G(n){var t=this.cache,e=typeof n;if(e=="boolean"||n==null){t[n]=true}else{if(e!="number"&&e!="string"){e="object"}var r=e=="number"?n:R+n,l=t[e]||(t[e]={});if(e=="object"){(l[r]||(l[r]=[])).push(n)}else{l[r]=true}}}function D(e){return e.charCodeAt(0)}function H(r,l){var a=r.criteria,i=l.criteria,t=-1,s=a.length;while(++t<s){var e=a[t],n=i[t];if(e!==n){if(e>n||typeof e=="undefined"){return 1}if(e<n||typeof n=="undefined"){return-1}}}return r.index-l.index}function L(e){var l=-1,r=e.length,a=e[0],i=e[r/2|0],s=e[r-1];if(a&&typeof a=="object"&&i&&typeof i=="object"&&s&&typeof s=="object"){return false}var n=j();n["false"]=n["null"]=n["true"]=n["undefined"]=false;var t=j();t.array=e;t.cache=n;t.push=G;while(++l<r){t.push(e[l])}return t}function Y(e){return"\\"+V[e]}function i(){return A.pop()||[]}function j(){return P.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 a(e){e.length=0;if(A.length<U){A.push(e)}}function h(e){var n=e.cache;if(n){h(n)}e.array=e.cache=e.criteria=e.object=e.number=e.string=e.value=null;if(P.length<U){P.push(e)}}function r(n,e,t){e||(e=0);if(typeof t=="undefined"){t=n?n.length:0}var r=-1,l=t-e||0,a=Array(l<0?0:l);while(++r<l){a[r]=n[e+r]}return a}function C(n){n=n?c.defaults(f.Object(),n,c.pick(f,J)):f;var z=n.Array,al=n.Boolean,Zn=n.Date,Nn=n.Function,Cn=n.Math,rl=n.Number,gn=n.Object,Rn=n.RegExp,un=n.String,sn=n.TypeError;var yn=[];var at=gn.prototype;var tl=n._;var A=at.toString;var el=Rn("^"+un(A).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var Zr=Cn.ceil,Pn=n.clearTimeout,Vr=Cn.floor,Dr=Nn.prototype.toString,hn=fn(hn=gn.getPrototypeOf)&&hn,P=at.hasOwnProperty,xn=yn.push,wn=n.setTimeout,ft=yn.splice,Mr=yn.unshift;var dt=function(){try{var n={},e=fn(e=gn.defineProperty)&&e,t=e(n,n,n)&&e}catch(r){}return t}();var Tn=fn(Tn=gn.create)&&Tn,Wn=fn(Wn=z.isArray)&&Wn,jr=n.isFinite,Tr=n.isNaN,jn=fn(jn=gn.keys)&&jn,rn=Cn.max,En=Cn.min,nt=n.parseInt,ut=Cn.random;var on={};on[E]=z;on[x]=al;on[v]=Zn;on[B]=Nn;on[o]=gn;on[y]=rl;on[g]=Rn;on[d]=un;function e(e){return e&&typeof e=="object"&&!w(e)&&P.call(e,"__wrapped__")?e:new dn(e)}function dn(e,n){this.__chain__=!!n;this.__wrapped__=e}dn.prototype=e.prototype;var kn=e.support={};kn.funcDecomp=!fn(n.WinRTError)&&M.test(C);kn.funcNames=typeof Nn.name=="string";e.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:F,variable:"",imports:{_:e}};function Cr(e){var n=e[0],l=e[2],a=e[4];function t(){if(l){var e=r(l);xn.apply(e,arguments)}if(this instanceof t){var i=vn(n.prototype),s=n.apply(i,e||arguments);return I(s)?s:i}return n.apply(a,e||arguments)}Hn(t,e);return t}function et(e,f,m,l,o){if(m){var n=m(e);if(typeof n!="undefined"){return n}}var E=I(e);if(E){var p=A.call(e);if(!s[p]){return e}var u=on[p];switch(p){case x:case v:return new u(+e);case y:case d:return new u(e);case g:n=u(e.source,K.exec(e));n.lastIndex=e.lastIndex;return n}}else{return e}var c=w(e);if(f){var b=!l;l||(l=i());o||(o=i());var h=l.length;while(h--){if(l[h]==e){return o[h]}}n=c?u(e.length):{}}else{n=c?r(e):Fn({},e)}if(c){if(P.call(e,"index")){n.index=e.index}if(P.call(e,"input")){n.input=e.input}}if(!f){return n}l.push(e);o.push(n);(c?U:t)(e,function(e,t){n[t]=et(e,f,m,l,o)});if(b){a(l);a(o)}return n}function vn(e,n){return I(e)?Tn(e):{}}if(!Tn){vn=function(){function e(){}return function(t){if(I(t)){e.prototype=t;var r=new e;e.prototype=null}return r||n.Object()}}()}function G(e,t,l){if(typeof e!="function"){return Gn}if(typeof t=="undefined"||!("prototype"in e)){return e}var n=e.__bindData__;if(typeof n=="undefined"){if(kn.funcNames){n=!e.name}n=n||!kn.funcDecomp;if(!n){var r=Dr.call(e);if(!kn.funcNames){n=!$.test(r)}if(!n){n=M.test(r);Hn(e,n)}}}if(n===false||n!==true&&n[1]&1){return e}switch(l){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,l){return e.call(t,n,r,l)};case 4:return function(n,r,l,a){return e.call(t,n,r,l,a)}}return yt(e,t)}function kt(e){var t=e[0],n=e[1],s=e[2],a=e[3],i=e[4],u=e[5];var c=n&1,f=n&2,o=n&4,p=n&8,d=t;function l(){var m=c?i:this;if(s){var e=r(s);xn.apply(e,arguments)}if(a||o){e||(e=r(arguments));if(a){xn.apply(e,a)}if(o&&e.length<u){n|=16&~32;return kt([t,p?n:n&~3,e,null,i,u])}}e||(e=arguments);if(f){t=m[d]}if(this instanceof l){m=vn(t.prototype);var h=t.apply(m,e);return I(h)?h:m}return t.apply(m,e)}Hn(l,e);return l}function bn(n,e){var l=-1,t=Ln(),a=n?n.length:0,r=a>=T&&t===m,i=[];if(r){var s=L(e);if(s){t=S;e=s}else{r=false}}while(++l<a){var o=n[l];if(t(e,o)<0){i.push(o)}}if(r){h(e)}return i}function cn(t,a,r,u){var l=(u||0)-1,c=t?t.length:0,n=[];while(++l<c){var e=t[l];if(e&&typeof e=="object"&&typeof e.length=="number"&&(w(e)||An(e))){if(!a){e=cn(e,a,r)}var i=-1,s=e.length,o=n.length;n.length+=s;while(++i<s){n[o++]=e[i]}}else if(!r){n.push(e)}}return n}function mn(e,n,h,c,t,s){if(h){var r=h(e,n);if(typeof r!="undefined"){return!!r}}if(e===n){return e!==0||1/e==1/n}var M=typeof e,j=typeof n;if(e===e&&!(e&&l[M])&&!(n&&l[j])){return false}if(e==null||n==null){return e===n}var m=A.call(e),S=A.call(n);if(m==b){m=o}if(S==b){S=o}if(m!=S){return false}switch(m){case x:case v:return+e==+n;case y:return e!=+e?n!=+n:e==0?1/e==1/n:e==+n;case g:case d:return e==un(n)}var R=m==E;if(!R){var I=P.call(e,"__wrapped__"),k=P.call(n,"__wrapped__");if(I||k){return mn(I?e.__wrapped__:e,k?n.__wrapped__:n,h,c,t,s)}if(m!=o){return false}var _=e.constructor,w=n.constructor;if(_!=w&&!(p(_)&&_ instanceof _&&p(w)&&w instanceof w)&&("constructor"in e&&"constructor"in n)){return false}}var L=!t;t||(t=i());s||(s=i());var f=t.length;while(f--){if(t[f]==e){return s[f]==n}}var u=0;r=true;t.push(e);s.push(n);if(R){f=e.length;u=n.length;r=u==f;if(r||c){while(u--){var C=f,T=n[u];if(c){while(C--){if(r=mn(e[C],T,h,c,t,s)){break}}}else if(!(r=mn(e[u],T,h,c,t,s))){break}}}}else{an(n,function(l,n,a){if(P.call(a,n)){u++;return r=P.call(e,n)&&mn(e[n],l,h,c,t,s)}});if(r&&!c){an(e,function(t,e,n){if(P.call(n,e)){return r=--u>-1}})}}t.pop();s.pop();if(L){a(t);a(s)}return r}function st(l,a,e,n,r){(w(a)?U:t)(a,function(a,u){var c,f,i=a,t=l[u];if(a&&((f=w(a))||tt(a))){var s=n.length;while(s--){if(c=n[s]==a){t=r[s];break}}if(!c){var o;if(e){i=e(t,a);if(o=typeof i!="undefined"){t=i}}if(!o){t=f?w(t)?t:[]:tt(t)?t:{}}n.push(a);r.push(t);if(!o){st(t,a,e,n,r)}}}else{if(e){i=e(t,a);if(typeof i=="undefined"){i=a}}if(typeof i!="undefined"){t=i}}l[u]=t})}function Qn(e,n){return e+Vr(ut()*(n-e+1))}function Kn(t,f,n){var r=-1,u=Ln(),p=t?t.length:0,c=[];var l=!f&&p>=T&&u===m,e=n||l?i():c;if(l){var d=L(e);u=S;e=d}while(++r<p){var s=t[r],o=n?n(s,r,t):s;if(f?!r||e[e.length-1]!==o:u(e,o)<0){if(n||l){e.push(o)}c.push(s)}}if(l){a(e.array);h(e)}else if(n){a(e)}return c}function $n(n){return function(r,l,u){var a={};l=e.createCallback(l,u,3);var i=-1,s=r?r.length:0;if(typeof s=="number"){while(++i<s){var o=r[i];n(a,o,l(o,i,r),r)}}else{t(r,function(e,r,t){n(a,e,l(e,r,t),t)})}return a}}function ln(t,n,l,a,o,u){var c=n&1,m=n&2,f=n&4,h=n&8,i=n&16,s=n&32;if(!m&&!p(t)){throw new sn}if(i&&!l.length){n&=~16;i=l=false}if(s&&!a.length){n&=~32;s=a=false}var e=t&&t.__bindData__;if(e&&e!==true){e=r(e);if(e[2]){e[2]=r(e[2])}if(e[3]){e[3]=r(e[3])}if(c&&!(e[1]&1)){e[4]=o}if(!c&&e[1]&1){n|=8}if(f&&!(e[1]&4)){e[5]=u}if(i){xn.apply(e[2]||(e[2]=[]),l)}if(s){Mr.apply(e[3]||(e[3]=[]),a)}e[1]|=n;return ln.apply(null,e)}var d=n==1||n===17?Cr:kt;return d([t,n,l,a,o,u])}function Rr(e){return Un[e]}function Ln(){var n=(n=e.indexOf)===bt?m:n;return n}function fn(e){return typeof e=="function"&&el.test(e)}var Hn=!dt?ot:function(e,n){O.value=n;dt(e,"__bindData__",O)};function xt(e){var n,t;if(!(e&&A.call(e)==o)||(n=e.constructor,p(n)&&!(n instanceof n))){return false}an(e,function(n,e){t=e});return typeof t=="undefined"||P.call(e,t)}function xr(e){return Ct[e]}function An(e){return e&&typeof e=="object"&&typeof e.length=="number"&&A.call(e)==b||false}var w=Wn||function(e){return e&&typeof e=="object"&&typeof e.length=="number"&&A.call(e)==E||false};var yr=function(r){var n,t=r,e=[];if(!t)return e;if(!l[typeof r])return e;for(n in t){if(P.call(t,n)){e.push(n)}}return e};var V=!jn?yr:function(e){if(!I(e)){return[]}return jn(e)};var Un={"&":"&","<":"<",">":">",'"':""","'":"'"};var Ct=vt(Un);var ur=Rn("("+V(Ct).join("|")+")","g"),sr=Rn("["+V(Un).join("")+"]","g");var Fn=function(c,d,f){var r,e=c,a=e;if(!e)return a;var t=arguments,o=0,n=typeof f=="number"?2:t.length;if(n>3&&typeof t[n-2]=="function"){var s=G(t[--n-1],t[n--],2)}else if(n>2&&typeof t[n-1]=="function"){s=t[--n]}while(++o<n){e=t[o];if(e&&l[typeof e]){var u=-1,i=l[typeof e]&&V(e),p=i?i.length:0;while(++u<p){r=i[u];a[r]=s?s(a[r],e[r]):e[r]}}}return a};function lr(r,e,n,t){if(typeof e!="boolean"&&e!=null){t=n;n=e;e=false}return et(r,e,typeof n=="function"&&G(n,t,1))}function rr(n,e,t){return et(n,true,typeof e=="function"&&G(e,t,1))}function tr(t,e){var n=vn(t);return e?Fn(n,e):n}var Xn=function(o,p,c){var n,e=o,t=e;if(!e)return t;var a=arguments,i=0,u=typeof c=="number"?2:a.length;while(++i<u){e=a[i];if(e&&l[typeof e]){var s=-1,r=l[typeof e]&&V(e),f=r?r.length:0;while(++s<f){n=r[s];if(typeof t[n]=="undefined")t[n]=e[n]}}}return t};function er(l,n,a){var r;n=e.createCallback(n,a,3);t(l,function(t,e,l){if(n(t,e,l)){r=e;return false}});return r}function Zt(r,n,l){var t;n=e.createCallback(n,l,3);ht(r,function(r,e,l){if(n(r,e,l)){t=e;return false}});return t}var an=function(a,e,i){var r,n=a,t=n;if(!n)return t;if(!l[typeof n])return t;e=e&&typeof i=="undefined"?e:G(e,i,3);for(r in n){if(e(n[r],r,a)===false)return t}return t};function Yt(n,t,l){var e=[];an(n,function(n,t){e.push(t,n)});var r=e.length;t=G(t,l,3);while(r--){if(t(e[r--],e[r],n)===false){break}}return n}var t=function(i,n,s){var r,e=i,t=e;if(!e)return t;if(!l[typeof e])return t;n=n&&typeof s=="undefined"?n:G(n,s,3);var o=-1,a=l[typeof e]&&V(e),u=a?a.length:0;while(++o<u){r=a[o];if(n(e[r],r,i)===false)return t}return t};function ht(e,n,a){var t=V(e),r=t.length;n=G(n,a,3);while(r--){var l=t[r];if(n(e[l],l,e)===false){break}}return e}function In(n){var e=[];an(n,function(n,t){if(p(n)){e.push(t)}});return e.sort()}function zt(e,n){return e?P.call(e,n):false}function vt(e){var n=-1,t=V(e),a=t.length,r={};while(++n<a){var l=t[n];r[e[l]]=l}return r}function Wt(e){return e===true||e===false||e&&typeof e=="object"&&A.call(e)==x||false}function Gt(e){return e&&typeof e=="object"&&A.call(e)==v||false}function Jt(e){return e&&e.nodeType===1||false}function Xt(e){var r=true;if(!e){return r}var n=A.call(e),l=e.length;if(n==E||n==d||n==b||n==o&&typeof l=="number"&&p(e.splice)){return!l}t(e,function(){return r=false});return r}function Ut(n,t,e,r){return mn(n,t,typeof e=="function"&&G(e,r,2))}function Pt(e){return jr(e)&&!Tr(parseFloat(e))}function p(e){return typeof e=="function"}function I(e){return!!(e&&l[typeof e])}function _r(e){return At(e)&&e!=+e}function Lt(e){return e===null}function At(e){return typeof e=="number"||e&&typeof e=="object"&&A.call(e)==y||false}var tt=!hn?xt:function(e){if(!(e&&A.call(e)==o)){return false}var t=e.valueOf,n=fn(t)&&(n=hn(t))&&hn(n);return n?e==n||hn(e)==n:xt(e)};function gl(e){return e&&typeof e=="object"&&A.call(e)==g||false}function _n(e){return typeof e=="string"||e&&typeof e=="object"&&A.call(e)==d||false}function jt(e){return typeof e=="undefined"}function Mt(l,n,a){var r={};n=e.createCallback(n,a,3);t(l,function(t,e,l){r[e]=n(t,e,l)});return r}function Ot(t){var n=arguments,e=2;if(!I(t)){return t}if(typeof n[2]!="number"){e=n.length}if(e>3&&typeof n[e-2]=="function"){var l=G(n[--e-1],n[e--],2)}else if(e>2&&typeof n[e-1]=="function"){l=n[--e]}var c=r(arguments,1,e),s=-1,o=i(),u=i();while(++s<e){st(t,c[s],l,o,u)}a(o);a(u);return t}function Dt(r,t,s){var l={};if(typeof t!="function"){var n=[];an(r,function(t,e){n.push(e)});n=bn(n,cn(arguments,true,false,1));var a=-1,o=n.length;while(++a<o){var i=n[a];l[i]=r[i]}}else{t=e.createCallback(t,s,3);an(r,function(e,n,r){if(!t(e,n,r)){l[n]=e}})}return l}function Nt(n){var e=-1,t=V(n),r=t.length,l=z(r);while(++e<r){var a=t[e];l[e]=[a,n[a]]}return l}function Ft(n,t,s){var r={};if(typeof t!="function"){var a=-1,i=cn(arguments,true,false,1),o=I(n)?i.length:0;while(++a<o){var l=i[a];if(l in n){r[l]=n[l]}}}else{t=e.createCallback(t,s,3);an(n,function(e,n,l){if(t(e,n,l)){r[n]=e}})}return r}function Bt(r,l,n,s){var a=w(r);if(n==null){if(a){n=[]}else{var i=r&&r.constructor,o=i&&i.prototype;n=vn(o)}}if(l){l=e.createCallback(l,s,4);(a?U:t)(r,function(e,t,r){return l(n,e,t,r)})}return n}function Mn(n){var e=-1,t=V(n),r=t.length,l=z(r);while(++e<r){l[e]=n[t[e]]}return l}function Vt(t){var e=arguments,n=-1,r=cn(e,true,false,1),l=e[2]&&e[2][e[1]]===t?1:r.length,a=z(l);while(++n<l){a[n]=t[r[n]]}return a}function wt(e,r,n){var s=-1,a=Ln(),i=e?e.length:0,l=false;n=(n<0?rn(0,i+n):n)||0;if(w(e)){l=a(e,r,n)>-1}else if(typeof i=="number"){l=(_n(e)?e.indexOf(r,n):a(e,r,n))>-1}else{t(e,function(e){if(++s>=n){return!(l=e===r)}})}return l}var qt=$n(function(e,t,n){P.call(e,n)?e[n]++:e[n]=1});function Et(n,r,s){var l=true;r=e.createCallback(r,s,3);var a=-1,i=n?n.length:0;if(typeof i=="number"){while(++a<i){if(!(l=!!r(n[a],a,n))){break}}}else{t(n,function(e,n,t){return l=!!r(e,n,t)})}return l}function Dn(n,r,o){var l=[];r=e.createCallback(r,o,3);var a=-1,i=n?n.length:0;if(typeof i=="number"){while(++a<i){var s=n[a];if(r(s,a,n)){l.push(s)}}}else{t(n,function(e,n,t){if(r(e,n,t)){l.push(e)}})}return l}function Yn(n,r,o){r=e.createCallback(r,o,3);var l=-1,a=n?n.length:0;if(typeof a=="number"){while(++l<a){var i=n[l];if(r(i,l,n)){return i}}}else{var s;t(n,function(e,n,t){if(r(e,n,t)){s=e;return false}});return s}}function Ht(r,n,l){var t;n=e.createCallback(n,l,3);On(r,function(e,r,l){if(n(e,r,l)){t=e;return false}});return t}function U(e,n,l){var r=-1,a=e?e.length:0;n=n&&typeof l=="undefined"?n:G(n,l,3);if(typeof a=="number"){while(++r<a){if(n(e[r],r,e)===false){break}}}else{t(e,n)}return e}function On(e,r,a){var n=e?e.length:0;r=r&&typeof a=="undefined"?r:G(r,a,3);if(typeof n=="number"){while(n--){if(r(e[n],n,e)===false){break}}}else{var l=V(e);n=l.length;t(e,function(a,e,t){e=l?l[--n]:--n;return r(t[e],e,t)})}return e}var $t=$n(function(e,t,n){(P.call(e,n)?e[n]:e[n]=[]).push(t)});var Kt=$n(function(e,n,t){e[t]=n});function Qt(e,n){var a=r(arguments,2),i=-1,s=typeof n=="function",t=e?e.length:0,l=z(typeof t=="number"?t:0);U(e,function(e){l[++i]=(s?n:e[n]).apply(e,a)});return l}function Sn(n,l,s){var r=-1,i=n?n.length:0;l=e.createCallback(l,s,3);if(typeof i=="number"){var a=z(i);while(++r<i){a[r]=l(n[r],r,n)}}else{a=[];t(n,function(e,n,t){a[++r]=l(e,n,t)})}return a}function ct(t,n,l){var a=-Infinity,r=a;if(typeof n!="function"&&l&&l[n]===t){n=null}if(n==null&&w(t)){var i=-1,o=t.length;while(++i<o){var s=t[i];if(s>r){r=s}}}else{n=n==null&&_n(t)?D:e.createCallback(n,l,3);U(t,function(e,l,i){var t=n(e,l,i);if(t>a){a=t;r=e}})}return r}function nr(t,n,l){var a=Infinity,r=a;if(typeof n!="function"&&l&&l[n]===t){n=null}if(n==null&&w(t)){var i=-1,o=t.length;while(++i<o){var s=t[i];if(s<r){r=s}}}else{n=n==null&&_n(t)?D:e.createCallback(n,l,3);U(t,function(e,l,i){var t=n(e,l,i);if(t<a){a=t;r=e}})}return r}var Vn=Sn;function zn(r,l,n,o){if(!r)return n;var i=arguments.length<3;l=e.createCallback(l,o,4);var a=-1,s=r.length;if(typeof s=="number"){if(i){n=r[++a]}while(++a<s){n=l(n,r[a],a,r)}}else{t(r,function(e,t,r){n=i?(i=false,e):l(n,e,t,r)})}return n}function it(l,n,t,a){var r=arguments.length<3;n=e.createCallback(n,a,4);On(l,function(e,l,a){t=r?(r=false,e):n(t,e,l,a)});return t}function ar(t,n,r){n=e.createCallback(n,r,3);return Dn(t,function(e,t,r){return!n(e,t,r)})}function ir(e,t,r){if(e&&typeof e.length!="number"){e=Mn(e)}if(t==null||r){return e?e[Qn(0,e.length-1)]:u}var n=lt(e);n.length=En(rn(0,t),n.length);return n}function lt(n){var t=-1,r=n?n.length:0,e=z(typeof r=="number"?r:0);U(n,function(r){var n=Qn(0,++t);e[t]=e[n];e[n]=r});return e}function or(e){var n=e?e.length:0;return typeof n=="number"?n:V(e).length}function rt(n,r,s){var l;r=e.createCallback(r,s,3);var a=-1,i=n?n.length:0;if(typeof i=="number"){while(++a<i){if(l=r(n[a],a,n)){break}}}else{t(n,function(e,n,t){return!(l=r(e,n,t))})}return!!l}function cr(l,r,c){var u=-1,s=w(r),n=l?l.length:0,t=z(typeof n=="number"?n:0);
if(!s){r=e.createCallback(r,c,3)}U(l,function(n,l,a){var e=t[++u]=j();if(s){e.criteria=Sn(r,function(e){return n[e]})}else{(e.criteria=i())[0]=r(n,l,a)}e.index=u;e.value=n});n=t.length;t.sort(H);while(n--){var o=t[n];t[n]=o.value;if(!s){a(o.criteria)}h(o)}return t}function fr(e){if(e&&typeof e.length=="number"){return r(e)}return Mn(e)}var pr=Dn;function dr(e){var n=-1,l=e?e.length:0,t=[];while(++n<l){var r=e[n];if(r){t.push(r)}}return t}function mr(e){return bn(e,cn(arguments,true,true,1))}function hr(n,r,l){var t=-1,a=n?n.length:0;r=e.createCallback(r,l,3);while(++t<a){if(r(n[t],t,n)){return t}}return-1}function gr(n,r,l){var t=n?n.length:0;r=e.createCallback(r,l,3);while(t--){if(r(n[t],t,n)){return t}}return-1}function Jn(n,t,i){var l=0,s=n?n.length:0;if(typeof t!="number"&&t!=null){var a=-1;t=e.createCallback(t,i,3);while(++a<s&&t(n[a],a,n)){l++}}else{l=t;if(l==null||i){return n?n[0]:u}}return r(n,0,En(rn(0,l),s))}function vr(n,e,t,r){if(typeof e!="boolean"&&e!=null){r=t;t=typeof e!="function"&&r&&r[e]===n?null:e;e=false}if(t!=null){n=Sn(n,t,r)}return cn(n,e)}function bt(n,t,e){if(typeof e=="number"){var l=n?n.length:0;e=e<0?rn(0,l+e):e||0}else if(e){var r=gt(n,t);return n[r]===t?r:-1}return m(n,t,e)}function br(t,n,s){var l=0,a=t?t.length:0;if(typeof n!="number"&&n!=null){var i=a;n=e.createCallback(n,s,3);while(i--&&n(t[i],i,t)){l++}}else{l=n==null||s?1:n||l}return r(t,0,En(rn(0,a-l),a))}function Er(){var s=[],t=-1,l=arguments.length,r=i(),u=Ln(),d=u===m,o=i();while(++t<l){var e=arguments[t];if(w(e)||An(e)){s.push(e);r.push(d&&e.length>=T&&L(t?s[t]:o))}}var c=s[0],f=-1,g=c?c.length:0,p=[];e:while(++f<g){var n=r[0];e=c[f];if((n?S(n,e):u(o,e))<0){t=l;(n||o).push(e);while(--t){n=r[t];if((n?S(n,e):u(s[t],e))<0){continue e}}p.push(e)}}while(l--){n=r[l];if(n){h(n)}}a(r);a(o);return p}function wr(n,t,s){var l=0,a=n?n.length:0;if(typeof t!="number"&&t!=null){var i=a;t=e.createCallback(t,s,3);while(i--&&t(n[i],i,n)){l++}}else{l=t;if(l==null||s){return n?n[a-1]:u}}return r(n,rn(0,a-l))}function Tt(t,r,n){var e=t?t.length:0;if(typeof n=="number"){e=(n<0?rn(0,e+n):En(n,e-1))+1}while(e--){if(t[e]===r){return e}}return-1}function Sr(e){var t=arguments,r=0,a=t.length,l=e?e.length:0;while(++r<a){var n=-1,i=t[r];while(++n<l){if(e[n]===i){ft.call(e,n--,1);l--}}}return e}function kr(e,t,n){e=+e||0;n=typeof n=="number"?n:+n||1;if(t==null){t=e;e=0}var r=-1,l=rn(0,Zr((t-e)/(n||1))),a=z(l);while(++r<l){a[r]=e;e+=n}return a}function Ir(n,r,s){var t=-1,l=n?n.length:0,a=[];r=e.createCallback(r,s,3);while(++t<l){var i=n[t];if(r(i,t,n)){a.push(i);ft.call(n,t--,1);l--}}return a}function Bn(t,n,i){if(typeof n!="number"&&n!=null){var l=0,a=-1,s=t?t.length:0;n=e.createCallback(n,i,3);while(++a<s&&n(t[a],a,t)){l++}}else{l=n==null||i?1:rn(0,n)}return r(t,l)}function gt(r,l,n,s){var t=0,a=r?r.length:t;n=n?e.createCallback(n,s,1):Gn;l=n(l);while(t<a){var i=t+a>>>1;n(r[i])<l?t=i+1:a=i}return t}function Ar(){return Kn(cn(arguments,true,true))}function St(l,n,t,r){if(typeof n!="boolean"&&n!=null){r=t;t=typeof n!="function"&&r&&r[n]===l?null:n;n=false}if(t!=null){t=e.createCallback(t,r,3)}return Kn(l,n,t)}function Lr(e){return bn(e,r(arguments,1))}function Pr(){var t=-1,r=arguments.length;while(++t<r){var e=arguments[t];if(w(e)||An(e)){var n=n?Kn(bn(n,e).concat(bn(e,n))):e}}return n||[]}function _t(){var e=arguments.length>1?arguments:arguments[0],n=-1,t=e?ct(Vn(e,"length")):0,r=z(t<0?0:t);while(++n<t){r[n]=Vn(e,n)}return r}function pt(e,n){var r=-1,a=e?e.length:0,l={};if(!n&&a&&!w(e[0])){n=[]}while(++r<a){var t=e[r];if(n){l[t]=n[r]}else if(t){l[t[0]]=t[1]}}return l}function Or(n,e){if(!p(e)){throw new sn}return function(){if(--n<1){return e.apply(this,arguments)}}}function yt(e,n){return arguments.length>2?ln(e,17,r(arguments,2),null,n):ln(e,1,null,null,n)}function Nr(e){var n=arguments.length>1?cn(arguments,true,false,1):In(e),t=-1,l=n.length;while(++t<l){var r=n[t];e[r]=ln(e[r],1,null,null,e)}return e}function Fr(e,n){return arguments.length>2?ln(n,19,r(arguments,2),null,e):ln(n,3,null,null,e)}function Br(){var e=arguments,n=e.length;while(n--){if(!p(e[n])){throw new sn}}return function(){var n=arguments,t=e.length;while(t--){n=[e[t].apply(this,n)]}return n[0]}}function Ur(n,e){e=typeof e=="number"?e:+e||n.length;return ln(n,4,null,null,null,e)}function mt(s,a,l){var t,n,o,i,r,e,m,f=0,d=false,c=true;if(!p(s)){throw new sn}a=rn(0,a)||0;if(l===true){var h=true;c=false}else if(I(l)){h=l.leading;d="maxWait"in l&&(rn(a,l.maxWait)||0);c="trailing"in l?l.trailing:c}var g=function(){var l=a-(pn()-i);if(l<=0){if(n){Pn(n)}var c=m;n=e=m=u;if(c){f=pn();o=s.apply(r,t);if(!e&&!n){t=r=null}}}else{e=wn(g,l)}};var y=function(){if(e){Pn(e)}n=e=m=u;if(c||d!==a){f=pn();o=s.apply(r,t);if(!e&&!n){t=r=null}}};return function(){t=arguments;i=pn();r=this;m=c&&(e||!h);if(d===false){var p=h&&!e}else{if(!n&&!h){f=i}var u=d-(i-f),l=u<=0;if(l){if(n){n=Pn(n)}f=i;o=s.apply(r,t)}else if(!n){n=wn(y,u)}}if(l&&e){e=Pn(e)}else if(!e&&a!==d){e=wn(g,a)}if(p){l=true;o=s.apply(r,t)}if(l&&!e&&!n){t=r=null}return o}}function Xr(e){if(!p(e)){throw new sn}var n=r(arguments,1);return wn(function(){e.apply(u,n)},1)}function qr(e,n){if(!p(e)){throw new sn}var t=r(arguments,2);return wn(function(){e.apply(u,t)},n)}function Jr(n,t){if(!p(n)){throw new sn}var e=function(){var r=e.cache,l=t?t.apply(this,arguments):R+arguments[0];return P.call(r,l)?r[l]:r[l]=n.apply(this,arguments)};e.cache={};return e}function Gr(e){var t,n;if(!p(e)){throw new sn}return function(){if(t){return n}t=true;n=e.apply(this,arguments);e=null;return n}}function Wr(e){return ln(e,16,r(arguments,1))}function Hr(e){return ln(e,32,null,r(arguments,1))}function zr(r,l,e){var n=true,t=true;if(!p(r)){throw new sn}if(e===false){n=false}else if(I(e)){n="leading"in e?e.leading:n;t="trailing"in e?e.trailing:t}k.leading=n;k.maxWait=l;k.trailing=t;return mt(r,l,k)}function Yr(e,n){return ln(n,16,[e])}function $r(e){return function(){return e}}function Kr(e,a,i){var r=typeof e;if(e==null||r=="function"){return G(e,a,i)}if(r!="object"){return It(e)}var t=V(e),l=t[0],n=e[l];if(t.length==1&&n===n&&!I(n)){return function(t){var e=t[l];return n===e&&(n!==0||1/n==1/e)}}return function(l){var n=t.length,r=false;while(n--){if(!(r=mn(l[t[n]],e[t[n]],null,true))){break}}return r}}function Qr(e){return e==null?"":un(e).replace(sr,Rr)}function Gn(e){return e}function qn(r,n,t){var a=true,i=n&&In(n);if(!n||!t&&!i.length){if(t==null){t=n}l=dn;n=r;r=e;i=In(n)}if(t===false){a=false}else if(I(t)&&"chain"in t){a=t.chain}var l=r,s=p(l);U(i,function(e){var t=r[e]=n[e];if(s){l.prototype[e]=function(){var n=this.__chain__,i=this.__wrapped__,s=[i];xn.apply(s,arguments);var e=t.apply(r,s);if(a||n){if(i===e&&I(e)){return this}e=new l(e);e.__chain__=n}return e}}})}function nl(){n._=tl;return this}function ot(){}var pn=fn(pn=Zn.now)&&pn||function(){return(new Zn).getTime()};var ll=nt(N+"08")==8?nt:function(e,n){return nt(_n(e)?e.replace(tn,""):e,n||0)};function It(e){return function(n){return n[e]}}function il(e,n,r){var a=e==null,t=n==null;if(r==null){if(typeof e=="boolean"&&t){r=e;e=1}else if(!t&&typeof n=="boolean"){r=n;t=true}}if(a&&t){n=1}e=+e||0;if(t){n=e;e=0}else{n=+n||0}if(r||e%1||n%1){var l=ut();return En(e+l*(n-e+parseFloat("1e-"+((l+"").length-1))),n)}return Qn(e,n)}function sl(e,n){if(e){var t=e[n];return p(t)?e[n]():t}}function ol(l,c,t){var o=e.templateSettings;l=un(l||"");t=Xn({},t,o);var p=Xn({},t.imports,o.imports),v=V(p),g=Mn(p);var i,m=0,f=t.interpolate||_,n="__p += '";var h=Rn((t.escape||_).source+"|"+f.source+"|"+(f===F?Z:_).source+"|"+(t.evaluate||_).source+"|$","g");l.replace(h,function(t,r,e,o,a,s){e||(e=o);n+=l.slice(m,s).replace(W,Y);if(r){n+="' +\n__e("+r+") +\n'"}if(a){i=true;n+="';\n"+a+";\n__p += '"}if(e){n+="' +\n((__t = ("+e+")) == null ? '' : __t) +\n'"}m=s+t.length;return t});n+="';\n";var r=t.variable,s=r;if(!s){r="obj";n="with ("+r+") {\n"+n+"\n}\n"}n=(i?n.replace(X,""):n).replace(nn,"$1").replace(en,"$1;");n="function("+r+") {\n"+(s?"":r+" || ("+r+" = {});\n")+"var __t, __p = '', __e = _.escape"+(i?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+n+"return __p\n}";var y="\n/*\n//# sourceURL="+(t.sourceURL||"/lodash/template/source["+q++ +"]")+"\n*/";try{var a=Nn(v,"return "+n+y).apply(u,g)}catch(d){d.source=n;throw d}if(c){return a(c)}a.source=n;return a}function ul(e,n,l){e=(e=+e)>-1?e:0;var t=-1,r=z(e);n=G(n,l,1);while(++t<e){r[t]=n(t)}return r}function cl(e){return e==null?"":un(e).replace(ur,xr)}function fl(e){var n=++Q;return un(e==null?"":e)+n}function pl(e){e=new dn(e);e.__chain__=true;return e}function dl(e,n){n(e);return e}function ml(){this.__chain__=true;return this}function hl(){return un(this.__wrapped__)}function Rt(){return this.__wrapped__}e.after=Or;e.assign=Fn;e.at=Vt;e.bind=yt;e.bindAll=Nr;e.bindKey=Fr;e.chain=pl;e.compact=dr;e.compose=Br;e.constant=$r;e.countBy=qt;e.create=tr;e.createCallback=Kr;e.curry=Ur;e.debounce=mt;e.defaults=Xn;e.defer=Xr;e.delay=qr;e.difference=mr;e.filter=Dn;e.flatten=vr;e.forEach=U;e.forEachRight=On;e.forIn=an;e.forInRight=Yt;e.forOwn=t;e.forOwnRight=ht;e.functions=In;e.groupBy=$t;e.indexBy=Kt;e.initial=br;e.intersection=Er;e.invert=vt;e.invoke=Qt;e.keys=V;e.map=Sn;e.mapValues=Mt;e.max=ct;e.memoize=Jr;e.merge=Ot;e.min=nr;e.omit=Dt;e.once=Gr;e.pairs=Nt;e.partial=Wr;e.partialRight=Hr;e.pick=Ft;e.pluck=Vn;e.property=It;e.pull=Sr;e.range=kr;e.reject=ar;e.remove=Ir;e.rest=Bn;e.shuffle=lt;e.sortBy=cr;e.tap=dl;e.throttle=zr;e.times=ul;e.toArray=fr;e.transform=Bt;e.union=Ar;e.uniq=St;e.values=Mn;e.where=pr;e.without=Lr;e.wrap=Yr;e.xor=Pr;e.zip=_t;e.zipObject=pt;e.collect=Sn;e.drop=Bn;e.each=U;e.eachRight=On;e.extend=Fn;e.methods=In;e.object=pt;e.select=Dn;e.tail=Bn;e.unique=St;e.unzip=_t;qn(e);e.clone=lr;e.cloneDeep=rr;e.contains=wt;e.escape=Qr;e.every=Et;e.find=Yn;e.findIndex=hr;e.findKey=er;e.findLast=Ht;e.findLastIndex=gr;e.findLastKey=Zt;e.has=zt;e.identity=Gn;e.indexOf=bt;e.isArguments=An;e.isArray=w;e.isBoolean=Wt;e.isDate=Gt;e.isElement=Jt;e.isEmpty=Xt;e.isEqual=Ut;e.isFinite=Pt;e.isFunction=p;e.isNaN=_r;e.isNull=Lt;e.isNumber=At;e.isObject=I;e.isPlainObject=tt;e.isRegExp=gl;e.isString=_n;e.isUndefined=jt;e.lastIndexOf=Tt;e.mixin=qn;e.noConflict=nl;e.noop=ot;e.now=pn;e.parseInt=ll;e.random=il;e.reduce=zn;e.reduceRight=it;e.result=sl;e.runInContext=C;e.size=or;e.some=rt;e.sortedIndex=gt;e.template=ol;e.unescape=cl;e.uniqueId=fl;e.all=Et;e.any=rt;e.detect=Yn;e.findWhere=Yn;e.foldl=zn;e.foldr=it;e.include=wt;e.inject=zn;qn(function(){var n={};t(e,function(r,t){if(!e.prototype[t]){n[t]=r}});return n}(),false);e.first=Jn;e.last=wr;e.sample=ir;e.take=Jn;e.head=Jn;t(e,function(t,n){var r=n!=="sample";if(!e.prototype[n]){e.prototype[n]=function(e,n){var l=this.__chain__,a=t(this.__wrapped__,e,n);return!l&&(e==null||n&&!(r&&typeof e=="function"))?a:new dn(a,l)}}});e.VERSION="2.4.1";e.prototype.chain=ml;e.prototype.toString=hl;e.prototype.value=Rt;e.prototype.valueOf=Rt;U(["join","pop","shift"],function(n){var t=yn[n];e.prototype[n]=function(){var e=this.__chain__,n=t.apply(this.__wrapped__,arguments);return e?new dn(n,e):n}});U(["push","reverse","sort","unshift"],function(n){var t=yn[n];e.prototype[n]=function(){t.apply(this.__wrapped__,arguments);return this}});U(["concat","slice","splice"],function(n){var t=yn[n];e.prototype[n]=function(){return new dn(t.apply(this.__wrapped__,arguments),this.__chain__)}});return e}var c=C();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){f._=c;define(function(){return c})}else if(w&&I){if(z){(I.exports=c)._=c}else{w._=c}}else{f._=c}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],143:[function(x,v,c){"use strict";var s=Object;var r=Object.defineProperty;var l=Object.create;function n(e,n,t){if(r)try{r.call(s,e,n,{value:t})}catch(l){e[n]=t}else{e[n]=t}}function e(e){if(e){n(e,"call",e.call);n(e,"apply",e.apply)}return e}e(r);e(l);var t=e(Object.prototype.hasOwnProperty);var p=e(Number.prototype.toString);var f=e(String.prototype.slice);var o=function(){};function a(e){if(l){return l.call(s,e)}o.prototype=e||null;return new o}var d=Math.random;var i=a(null);function u(){do var e=g(f.call(p.call(d(),36),2));while(t.call(i,e));return i[e]=e}function g(n){var e={};e[n]=true;return Object.keys(e)[0]}n(c,"makeUniqueKey",u);var y=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function b(l){for(var e=y(l),n=0,r=0,a=e.length;n<a;++n){if(!t.call(i,e[n])){if(n>r){e[r]=e[n]}++r}}e.length=r;return e};function m(e){return a(null)}function h(r){var e=u();var l=a(null);r=r||m;function s(a){var t;function i(e,n){if(e===l){return n?t=null:t||(t=r(a))}}n(a,e,i)}function i(n){if(!t.call(n,e))s(n);return n[e](l)}i.forget=function(n){if(t.call(n,e))n[e](l,true)};return i}n(c,"makeAccessor",h)},{}],144:[function(s,x,y){var l=s("assert");var i=s("recast").types;var b=i.builtInTypes.array;var e=i.builders;var n=i.namedTypes;var a=s("./leap");var u=s("./meta");var f=s("./util");var d=f.runtimeProperty("keys");var o=Object.prototype.hasOwnProperty;function c(e){l.ok(this instanceof c);n.Identifier.assert(e);Object.defineProperties(this,{contextId:{value:e},listing:{value:[]},marked:{value:[true]},finalLoc:{value:t()},tryEntries:{value:[]}});Object.defineProperties(this,{leapManager:{value:new a.LeapManager(this)}})}var r=c.prototype;y.Emitter=c;function t(){return e.literal(-1)}r.mark=function(e){n.Literal.assert(e);var t=this.listing.length;if(e.value===-1){e.value=t}else{l.strictEqual(e.value,t)}this.marked[t]=true;return e};r.emit=function(t){if(n.Expression.check(t))t=e.expressionStatement(t);n.Statement.assert(t);this.listing.push(t)};r.emitAssign=function(e,n){this.emit(this.assign(e,n));return e};r.assign=function(n,t){return e.expressionStatement(e.assignmentExpression("=",n,t))};r.contextProperty=function(n,t){return e.memberExpression(this.contextId,t?e.literal(n):e.identifier(n),!!t)};var m={prev:true,next:true,sent:true,rval:true};r.isVolatileContextProperty=function(e){if(n.MemberExpression.check(e)){if(e.computed){return true}if(n.Identifier.check(e.object)&&n.Identifier.check(e.property)&&e.object.name===this.contextId.name&&o.call(m,e.property.name)){return true}}return false};r.stop=function(e){if(e){this.setReturnValue(e)}this.jump(this.finalLoc)};r.setReturnValue=function(e){n.Expression.assert(e.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(e))};r.clearPendingException=function(t,r){n.Literal.assert(t);var l=e.callExpression(this.contextProperty("catch",true),[t]);if(r){this.emitAssign(r,l)}else{this.emit(l)}};r.jump=function(n){this.emitAssign(this.contextProperty("next"),n);this.emit(e.breakStatement())};r.jumpIf=function(t,r){n.Expression.assert(t);n.Literal.assert(r);this.emit(e.ifStatement(t,e.blockStatement([this.assign(this.contextProperty("next"),r),e.breakStatement()])))};r.jumpIfNot=function(t,l){n.Expression.assert(t);n.Literal.assert(l);var r;if(n.UnaryExpression.check(t)&&t.operator==="!"){r=t.argument}else{r=e.unaryExpression("!",t)}this.emit(e.ifStatement(r,e.blockStatement([this.assign(this.contextProperty("next"),l),e.breakStatement()])))};var h=0;r.makeTempVar=function(){return this.contextProperty("t"+h++)};r.getContextFunction=function(n){return e.functionExpression(n||null,[this.contextId],e.blockStatement([this.getDispatchLoop()]),false,false)};r.getDispatchLoop=function(){var r=this;var n=[];var l;var t=false;r.listing.forEach(function(a,i){if(r.marked.hasOwnProperty(i)){n.push(e.switchCase(e.literal(i),l=[]));t=false}if(!t){l.push(a);if(g(a))t=true}});this.finalLoc.value=this.listing.length;n.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")),n))};function g(e){return n.BreakStatement.check(e)||n.ContinueStatement.check(e)||n.ReturnStatement.check(e)||n.ThrowStatement.check(e)}r.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var n=0;return e.arrayExpression(this.tryEntries.map(function(t){var r=t.firstLoc.value;l.ok(r>=n,"try entries out of order");n=r;var a=t.catchEntry;var i=t.finallyEntry;var s=[t.firstLoc,a?a.firstLoc:null];if(i){s[2]=i.firstLoc}return e.arrayExpression(s)}))};r.explode=function(t,a){l.ok(t instanceof i.NodePath);var e=t.value;var r=this;n.Node.assert(e);if(n.Statement.check(e))return r.explodeStatement(t);if(n.Expression.check(e))return r.explodeExpression(t,a);if(n.Declaration.check(e))throw p(e);switch(e.type){case"Program":return t.get("body").map(r.explodeStatement,r);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))}r.explodeStatement=function(s,p){l.ok(s instanceof i.NodePath);var o=s.value;var r=this;n.Statement.assert(o);if(p){n.Identifier.assert(p)}else{p=null}if(n.BlockStatement.check(o)){return s.get("body").each(r.explodeStatement,r)}if(!u.containsLeap(o)){r.emit(o);return}switch(o.type){case"ExpressionStatement":r.explodeExpression(s.get("expression"),true);break;case"LabeledStatement":var c=t();r.leapManager.withEntry(new a.LabeledEntry(c,o.label),function(){r.explodeStatement(s.get("body"),o.label)});r.mark(c);break;case"WhileStatement":var w=t();var c=t();r.mark(w);r.jumpIfNot(r.explodeExpression(s.get("test")),c);r.leapManager.withEntry(new a.LoopEntry(c,w,p),function(){r.explodeStatement(s.get("body"))});r.jump(w);r.mark(c);break;case"DoWhileStatement":var A=t();var C=t();var c=t();r.mark(A);r.leapManager.withEntry(new a.LoopEntry(c,C,p),function(){r.explode(s.get("body"))});r.mark(C);r.jumpIf(r.explodeExpression(s.get("test")),A);r.mark(c);break;case"ForStatement":var y=t();var P=t();var c=t();if(o.init){r.explode(s.get("init"),true)}r.mark(y);if(o.test){r.jumpIfNot(r.explodeExpression(s.get("test")),c)}else{}r.leapManager.withEntry(new a.LoopEntry(c,P,p),function(){r.explodeStatement(s.get("body"))});r.mark(P);if(o.update){r.explode(s.get("update"),true)}r.jump(y);r.mark(c);break;case"ForInStatement":n.Identifier.assert(o.left);var y=t();var c=t();var j=r.makeTempVar();r.emitAssign(j,e.callExpression(d,[r.explodeExpression(s.get("right"))]));r.mark(y);var R=r.makeTempVar();r.jumpIf(e.memberExpression(e.assignmentExpression("=",R,e.callExpression(j,[])),e.identifier("done"),false),c);r.emitAssign(o.left,e.memberExpression(R,e.identifier("value"),false));r.leapManager.withEntry(new a.LoopEntry(c,y,p),function(){r.explodeStatement(s.get("body"))});r.jump(y);r.mark(c);break;case"BreakStatement":r.emitAbruptCompletion({type:"break",target:r.leapManager.getBreakLoc(o.label)});break;case"ContinueStatement":r.emitAbruptCompletion({type:"continue",target:r.leapManager.getContinueLoc(o.label)});break;case"SwitchStatement":var M=r.emitAssign(r.makeTempVar(),r.explodeExpression(s.get("discriminant")));var c=t();var v=t();var _=v;var S=[];var T=o.cases||[];for(var g=T.length-1;g>=0;--g){var k=T[g];n.SwitchCase.assert(k);if(k.test){_=e.conditionalExpression(e.binaryExpression("===",M,k.test),S[g]=t(),_)}else{S[g]=v}}r.jump(r.explodeExpression(new i.NodePath(_,s,"discriminant")));r.leapManager.withEntry(new a.SwitchEntry(c),function(){s.get("cases").each(function(e){var t=e.value;var n=e.name;r.mark(S[n]);e.get("consequent").each(r.explodeStatement,r)})});r.mark(c);if(v.value===-1){r.mark(v);l.strictEqual(c.value,v.value)}break;case"IfStatement":var I=o.alternate&&t();var c=t();r.jumpIfNot(r.explodeExpression(s.get("test")),I||c);r.explodeStatement(s.get("consequent"));if(I){r.jump(c);r.mark(I);r.explodeStatement(s.get("alternate"))}r.mark(c);break;case"ReturnStatement":r.emitAbruptCompletion({type:"return",value:r.explodeExpression(s.get("argument"))});break;case"WithStatement":throw new Error(node.type+" not supported in generator functions.");case"TryStatement":var c=t();var h=o.handler;if(!h&&o.handlers){h=o.handlers[0]||null}var b=h&&t();var L=b&&new a.CatchEntry(b,h.param);var m=o.finalizer&&t();var E=m&&new a.FinallyEntry(m);var x=new a.TryEntry(r.getUnmarkedCurrentLoc(),L,E);r.tryEntries.push(x);r.updateContextPrevLoc(x.firstLoc);r.leapManager.withEntry(x,function(){r.explodeStatement(s.get("block"));if(b){if(m){r.jump(m)}else{r.jump(c)}r.updateContextPrevLoc(r.mark(b));var o=s.get("handler","body");var u=r.makeTempVar();r.clearPendingException(x.firstLoc,u);var t=o.scope;var a=h.param.name;n.CatchClause.assert(t.node);l.strictEqual(t.lookup(a),t);i.visit(o,{visitIdentifier:function(e){if(f.isReference(e,a)&&e.scope.lookup(a)===t){return u}this.traverse(e)},visitFunction:function(e){if(e.scope.declares(a)){return false}this.traverse(e)}});r.leapManager.withEntry(L,function(){r.explodeStatement(o)})}if(m){r.updateContextPrevLoc(r.mark(m));r.leapManager.withEntry(E,function(){r.explodeStatement(s.get("finalizer"))});r.emit(e.callExpression(r.contextProperty("finish"),[E.firstLoc]))}});r.mark(c);break;case"ThrowStatement":r.emit(e.throwStatement(r.explodeExpression(s.get("argument"))));break;default:throw new Error("unknown Statement of type "+JSON.stringify(o.type))}};r.emitAbruptCompletion=function(t){if(!v(t)){l.ok(false,"invalid completion record: "+JSON.stringify(t))}l.notStrictEqual(t.type,"normal","normal completions are not abrupt");var r=[e.literal(t.type)];if(t.type==="break"||t.type==="continue"){n.Literal.assert(t.target);r[1]=t.target}else if(t.type==="return"||t.type==="throw"){if(t.value){n.Expression.assert(t.value);r[1]=t.value}}this.emit(e.returnStatement(e.callExpression(this.contextProperty("abrupt"),r)))};function v(e){var t=e.type;if(t==="normal"){return!o.call(e,"target")}if(t==="break"||t==="continue"){return!o.call(e,"value")&&n.Literal.check(e.target)}if(t==="return"||t==="throw"){return o.call(e,"value")&&!o.call(e,"target")}return false}r.getUnmarkedCurrentLoc=function(){return e.literal(this.listing.length)};r.updateContextPrevLoc=function(e){if(e){n.Literal.assert(e);if(e.value===-1){e.value=this.listing.length}else{l.strictEqual(e.value,this.listing.length)}}else{e=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),e)};r.explodeExpression=function(a,d){l.ok(a instanceof i.NodePath);var s=a.value;if(s){n.Expression.assert(s)}else{return s}var r=this;var o;function f(e){n.Expression.assert(e);if(d){r.emit(e)}else{return e}}if(!u.containsLeap(s)){return f(s)}var b=u.containsLeap.onlyChildren(s);function c(n,a,t){l.ok(a instanceof i.NodePath);l.ok(!t||!n,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var e=r.explodeExpression(a,t);if(t){}else if(n||b&&(r.isVolatileContextProperty(e)||u.hasSideEffects(e))){e=r.emitAssign(n||r.makeTempVar(),e)}return e}switch(s.type){case"MemberExpression":return f(e.memberExpression(r.explodeExpression(a.get("object")),s.computed?c(null,a.get("property")):s.property,s.computed));case"CallExpression":var v=a.get("callee");var m=r.explodeExpression(v);if(!n.MemberExpression.check(v.node)&&n.MemberExpression.check(m)){m=e.sequenceExpression([e.literal(0),m])}return f(e.callExpression(m,a.get("arguments").map(function(e){return c(null,e)})));case"NewExpression":return f(e.newExpression(c(null,a.get("callee")),a.get("arguments").map(function(e){return c(null,e)})));case"ObjectExpression":return f(e.objectExpression(a.get("properties").map(function(n){return e.property(n.value.kind,n.value.key,c(null,n.get("value")))})));case"ArrayExpression":return f(e.arrayExpression(a.get("elements").map(function(e){return c(null,e)})));case"SequenceExpression":var x=s.expressions.length-1;a.get("expressions").each(function(e){if(e.name===x){o=r.explodeExpression(e,d)}else{r.explodeExpression(e,true)}});return o;case"LogicalExpression":var p=t();if(!d){o=r.makeTempVar()}var g=c(o,a.get("left"));if(s.operator==="&&"){r.jumpIfNot(g,p)}else{l.strictEqual(s.operator,"||");r.jumpIf(g,p)}c(o,a.get("right"),d);r.mark(p);return o;case"ConditionalExpression":var y=t();var p=t();var E=r.explodeExpression(a.get("test"));r.jumpIfNot(E,y);if(!d){o=r.makeTempVar()}c(o,a.get("consequent"),d);r.jump(p);r.mark(y);c(o,a.get("alternate"),d);r.mark(p);return o;case"UnaryExpression":return f(e.unaryExpression(s.operator,r.explodeExpression(a.get("argument")),!!s.prefix));case"BinaryExpression":return f(e.binaryExpression(s.operator,c(null,a.get("left")),c(null,a.get("right"))));case"AssignmentExpression":return f(e.assignmentExpression(s.operator,r.explodeExpression(a.get("left")),r.explodeExpression(a.get("right"))));case"UpdateExpression":return f(e.updateExpression(s.operator,r.explodeExpression(a.get("argument")),s.prefix));case"YieldExpression":var p=t();var h=s.argument&&r.explodeExpression(a.get("argument"));if(h&&s.delegate){var o=r.makeTempVar();r.emit(e.returnStatement(e.callExpression(r.contextProperty("delegateYield"),[h,e.literal(o.property.name),p])));r.mark(p);return o}r.emitAssign(r.contextProperty("next"),p);r.emit(e.returnStatement(h||null));r.mark(p);return r.contextProperty("sent");default:throw new Error("unknown Expression of type "+JSON.stringify(s.type))}}},{"./leap":146,"./meta":147,"./util":148,assert:110,recast:177}],145:[function(r,s,l){var a=r("assert");var t=r("recast").types;var n=t.namedTypes;var e=t.builders;var i=Object.prototype.hasOwnProperty;l.hoist=function(r){a.ok(r instanceof t.NodePath);n.Function.assert(r.value);var l={};function s(r,a){n.VariableDeclaration.assert(r);var t=[];r.declarations.forEach(function(n){l[n.id.name]=n.id;if(n.init){t.push(e.assignmentExpression("=",n.id,n.init))}else if(a){t.push(n.id)}});if(t.length===0)return null;if(t.length===1)return t[0];return e.sequenceExpression(t)}t.visit(r.get("body"),{visitVariableDeclaration:function(n){var t=s(n.value,false);if(t===null){n.replace()}else{return e.expressionStatement(t)}return false},visitForStatement:function(e){var t=e.value.init;if(n.VariableDeclaration.check(t)){e.get("init").replace(s(t,false))}this.traverse(e)},visitForInStatement:function(e){var t=e.value.left;if(n.VariableDeclaration.check(t)){e.get("left").replace(s(t,true))}this.traverse(e)},visitFunctionDeclaration:function(r){var t=r.value;l[t.id.name]=t.id;var i=r.parent.node;var a=e.expressionStatement(e.assignmentExpression("=",t.id,e.functionExpression(t.id,t.params,t.body,t.generator,t.expression)));if(n.BlockStatement.check(r.parent.node)){r.parent.get("body").unshift(a);r.replace()}else{r.replace(a)}return false},visitFunctionExpression:function(e){return false}});var u={};r.get("params").each(function(t){var e=t.value;if(n.Identifier.check(e)){u[e.name]=e}else{}});var o=[];Object.keys(l).forEach(function(n){if(!i.call(u,n)){o.push(e.variableDeclarator(l[n],null))}});if(o.length===0){return null}return e.variableDeclaration("var",o)}},{assert:110,recast:177}],146:[function(a,g,t){var r=a("assert");var p=a("recast").types;var n=p.namedTypes;var v=p.builders;var l=a("util").inherits;var y=Object.prototype.hasOwnProperty;function e(){r.ok(this instanceof e)}function u(t){e.call(this);n.Literal.assert(t);this.returnLoc=t}l(u,e);t.FunctionEntry=u;function h(r,l,t){e.call(this);n.Literal.assert(r);n.Literal.assert(l);if(t){n.Identifier.assert(t)}else{t=null}this.breakLoc=r;this.continueLoc=l;this.label=t}l(h,e);t.LoopEntry=h;function m(t){e.call(this);n.Literal.assert(t);this.breakLoc=t}l(m,e);t.SwitchEntry=m;function d(a,t,l){e.call(this);n.Literal.assert(a);if(t){r.ok(t instanceof c)}else{t=null}if(l){r.ok(l instanceof f)}else{l=null}r.ok(t||l);this.firstLoc=a;this.catchEntry=t;this.finallyEntry=l}l(d,e);t.TryEntry=d;function c(t,r){e.call(this);n.Literal.assert(t);n.Identifier.assert(r);this.firstLoc=t;this.paramId=r}l(c,e);t.CatchEntry=c;function f(t){e.call(this);n.Literal.assert(t);this.firstLoc=t}l(f,e);t.FinallyEntry=f;function o(t,r){e.call(this);n.Literal.assert(t);n.Identifier.assert(r);this.breakLoc=t;this.label=r}l(o,e);t.LabeledEntry=o;function s(e){r.ok(this instanceof s);var n=a("./emit").Emitter;r.ok(e instanceof n);this.emitter=e;this.entryStack=[new u(e.finalLoc)]}var i=s.prototype;t.LeapManager=s;i.withEntry=function(n,t){r.ok(n instanceof e);this.entryStack.push(n);try{t.call(this.emitter)}finally{var l=this.entryStack.pop();r.strictEqual(l,n)}};i._findLeapLocation=function(l,r){for(var n=this.entryStack.length-1;n>=0;--n){var e=this.entryStack[n];var t=e[l];if(t){if(r){if(e.label&&e.label.name===r.name){return t}}else if(e instanceof o){}else{return t}}}return null};i.getBreakLoc=function(e){return this._findLeapLocation("breakLoc",e)};i.getContinueLoc=function(e){return this._findLeapLocation("continueLoc",e)}},{"./emit":144,assert:110,recast:177,util:134}],147:[function(r,d,o){var f=r("assert");var u=r("private").makeAccessor();var l=r("recast").types;var c=l.builtInTypes.array;var t=l.namedTypes;var n=Object.prototype.hasOwnProperty;function i(e,i){function a(n){t.Node.assert(n);var e=false;function a(n){if(e){}else if(c.check(n)){n.some(a)}else if(t.Node.check(n)){f.strictEqual(e,false);e=r(n)}return e}l.eachField(n,function(n,e){a(e)});return e}function r(r){t.Node.assert(r);var l=u(r);if(n.call(l,e))return l[e];if(n.call(p,r.type))return l[e]=false;if(n.call(i,r.type))return l[e]=true;return l[e]=a(r)}r.onlyChildren=a;return r}var p={FunctionExpression:true};var s={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(n.call(e,a)){s[a]=e[a]}}o.hasSideEffects=i("hasSideEffects",s);o.containsLeap=i("containsLeap",e)},{assert:110,"private":143,recast:177}],148:[function(t,i,e){var s=t("assert");var r=t("recast").types;var a=r.namedTypes;var n=r.builders;var l=Object.prototype.hasOwnProperty;e.defaults=function(t){var a=arguments.length;var e;for(var r=1;r<a;++r){if(e=arguments[r]){for(var n in e){if(l.call(e,n)&&!l.call(t,n)){t[n]=e[n]}}}}return t};e.runtimeProperty=function(e){return n.memberExpression(n.identifier("regeneratorRuntime"),n.identifier(e),false)};e.isReference=function(e,r){var t=e.value;if(!a.Identifier.check(t)){return false}if(r&&t.name!==r){return false}var n=e.parent.value;switch(n.type){case"VariableDeclarator":return e.name==="init";case"MemberExpression":return e.name==="object"||n.computed&&e.name==="property";case"FunctionExpression":case"FunctionDeclaration":case"ArrowFunctionExpression":if(e.name==="id"){return false}if(n.params===e.parentPath&&n.params[e.name]===t){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:110,recast:177}],149:[function(r,E,p){var m=r("assert");var g=r("fs");var a=r("recast");var t=a.types;var n=t.namedTypes;var e=t.builders;var _=t.builtInTypes.array;var w=t.builtInTypes.object;var o=t.NodePath;var b=r("./hoist").hoist;var d=r("./emit").Emitter;var l=r("./util").runtimeProperty;var h=l("wrap");var s=l("mark");var y=l("values");var v=l("async");p.transform=function S(e,t){t=t||{};var r=e instanceof o?e:new o(e);i.visit(r,t);e=r.value;if(t.includeRuntime===true||t.includeRuntime==="if used"&&i.wasChangeReported()){x(n.File.check(e)?e.program:e)}t.madeChanges=i.wasChangeReported();return e};function x(e){n.Program.assert(e);var t=r("..").runtime.path;var i=g.readFileSync(t,"utf8");var s=a.parse(i,{sourceFileName:t}).program.body;var l=e.body;l.unshift.apply(l,s)
}var i=t.PathVisitor.fromMethodsObject({reset:function(n,e){this.options=e},visitFunction:function(r){this.traverse(r);var t=r.value;var i=t.async&&!this.options.disableAsync;if(!t.generator&&!i){return}this.reportChanged();t.generator=false;if(t.expression){t.expression=false;t.body=e.blockStatement([e.returnStatement(t.body)])}if(i){f.visit(r.get("body"))}var A=t.id||(t.id=r.scope.parent.declareTemporary("callee$"));var R=e.identifier(t.id.name+"$");var I=r.scope.declareTemporary("context$");var w=r.scope.declareTemporary("args$");var S=u(r,w);var a=b(r);if(S){a=a||e.variableDeclaration("var",[]);a.declarations.push(e.variableDeclarator(w,e.identifier("arguments")))}var y=new d(I);y.explode(r.get("body"));var p=[];if(a&&a.declarations.length>0){p.push(a)}var x=[y.getContextFunction(R),i?e.literal(null):A,e.thisExpression()];var E=y.getTryEntryList();if(E){x.push(E)}var k=e.callExpression(i?v:h,x);p.push(e.returnStatement(k));t.body=e.blockStatement(p);if(i){t.async=false;return}if(n.FunctionDeclaration.check(t)){var l=r.parent;while(l&&!(n.BlockStatement.check(l.value)||n.Program.check(l.value))){l=l.parent}if(!l){return}r.replace();t.type="FunctionExpression";var o=e.variableDeclaration("var",[e.variableDeclarator(t.id,e.callExpression(s,[t]))]);if(t.comments){o.comments=t.comments;t.comments=null}var g=l.get("body");var C=g.value.length;for(var m=0;m<C;++m){var _=g.get(m);if(!c(_)){_.insertBefore(o);return}}g.push(o)}else{n.FunctionExpression.assert(t);return e.callExpression(s,[t])}},visitForOfStatement:function(l){this.traverse(l);var t=l.value;var s=l.scope.declareTemporary("t$");var o=e.variableDeclarator(s,e.callExpression(y,[t.right]));var i=l.scope.declareTemporary("t$");var u=e.variableDeclarator(i,null);var r=t.left;var a;if(n.VariableDeclaration.check(r)){a=r.declarations[0].id;r.declarations.push(o,u)}else{a=r;r=e.variableDeclaration("var",[o,u])}n.Identifier.assert(a);var c=e.expressionStatement(e.assignmentExpression("=",a,e.memberExpression(i,e.identifier("value"),false)));if(n.BlockStatement.check(t.body)){t.body.body.unshift(c)}else{t.body=e.blockStatement([c,t.body])}return e.forStatement(r,e.unaryExpression("!",e.memberExpression(e.assignmentExpression("=",i,e.callExpression(e.memberExpression(s,e.identifier("next"),false),[])),e.identifier("done"),false)),null,t.body)}});function c(a){var e=a.value;n.Statement.assert(e);if(n.ExpressionStatement.check(e)&&n.Literal.check(e.expression)&&e.expression.value==="use strict"){return true}if(n.VariableDeclaration.check(e)){for(var r=0;r<e.declarations.length;++r){var l=e.declarations[r];if(n.CallExpression.check(l.init)&&t.astNodesAreEquivalent(l.init.callee,s)){return true}}}return false}function u(e,i){m.ok(e instanceof t.NodePath);var s=e.value;var r=false;var l=false;a.visit(e,{visitFunction:function(e){if(e.value===s){l=!e.scope.lookup("arguments");this.traverse(e)}else{return false}},visitIdentifier:function(e){if(e.value.name==="arguments"){var t=n.MemberExpression.check(e.parent.node)&&e.name==="property"&&!e.parent.node.computed;if(!t){e.replace(i);r=true;return false}}this.traverse(e)}});return r&&l}var f=t.PathVisitor.fromMethodsObject({visitFunction:function(e){return false},visitAwaitExpression:function(n){return e.yieldExpression(n.value.argument,false)}})},{"..":150,"./emit":144,"./hoist":145,"./util":148,assert:110,fs:109,recast:177}],150:[function(e,n,t){(function(m){var f=e("assert");var g=e("path");var y=e("fs");var d=e("through");var i=e("./lib/visit").transform;var h=e("./lib/util");var t=e("recast");var s=t.types;var b=/\bfunction\s*\*|\basync\b/;var p=/\b(let|const)\s+/;function r(l,n){var e=[];return d(t,r);function t(n){e.push(n)}function r(){this.queue(o(e.join(""),n).code);this.queue(null)}}n.exports=r;function l(){e("./runtime")}r.runtime=l;l.path=g.join(m,"runtime.js");function o(n,e){e=u(e);if(!b.test(n)){return{code:(e.includeRuntime===true?y.readFileSync(l.path,"utf-8")+"\n":"")+n}}var r=c(e);var p=t.parse(n,r);var o=new s.NodePath(p);var f=o.get("program");if(v(n,e)){a(f.node)}i(f,e);return t.print(o,r)}function u(n){n=h.defaults(n||{},{includeRuntime:false,supportBlockBinding:true});if(!n.esprima){n.esprima=e("esprima-fb")}f.ok(/harmony/.test(n.esprima.version),"Bad esprima version: "+n.esprima.version);return n}function c(n){var t={range:true};function e(e){if(e in n){t[e]=n[e]}}e("esprima");e("sourceFileName");e("sourceMapName");e("inputSourceMap");e("sourceRoot");return t}function v(n,t){var e=!!t.supportBlockBinding;if(e){if(!p.test(n)){e=false}}return e}function x(r,l){var e=c(u(l));var n=t.parse(r,e);a(n.program);return t.print(n,e).code}function a(n){s.namedTypes.Program.assert(n);var t=e("defs")(n,{ast:true,disallowUnknownReferences:false,disallowDuplicated:false,disallowVars:false,loopClosures:"iife"});if(t.errors){throw new Error(t.errors.join("\n"))}return n}r.varify=x;r.compile=o;r.transform=i}).call(this,"/node_modules/regenerator")},{"./lib/util":148,"./lib/visit":149,"./runtime":179,assert:110,defs:151,"esprima-fb":166,fs:109,path:118,recast:177,through:178}],151:[function(t,x,N){"use strict";var l=t("assert");var r=t("simple-is");var f=t("simple-fmt");var M=t("stringmap");var w=t("stringset");var _=t("alter");var a=t("ast-traverse");var I=t("breakable");var s=t("./scope");var n=t("./error");var e=n.getline;var i=t("./options");var k=t("./stats");var u=t("./jshint_globals/vars.js");function c(e){return r.someof(e,["const","let"])}function v(e){return r.someof(e,["var","const","let"])}function O(e){return e.type==="BlockStatement"&&r.noneof(e.$parent.type,["FunctionDeclaration","FunctionExpression"])}function b(e){return e.type==="ForStatement"&&e.init&&e.init.type==="VariableDeclaration"&&c(e.init.kind)}function E(e){return y(e)&&e.left.type==="VariableDeclaration"&&c(e.left.kind)}function y(e){return r.someof(e.type,["ForInStatement","ForOfStatement"])}function o(e){return r.someof(e.type,["FunctionDeclaration","FunctionExpression"])}function m(e){return r.someof(e.type,["ForStatement","ForInStatement","ForOfStatement","WhileStatement","DoWhileStatement"])}function p(n){var e=n.$parent;return n.$refToScope||n.type==="Identifier"&&!(e.type==="VariableDeclarator"&&e.id===n)&&!(e.type==="MemberExpression"&&e.computed===false&&e.property===n)&&!(e.type==="Property"&&e.key===n)&&!(e.type==="LabeledStatement"&&e.label===n)&&!(e.type==="CatchClause"&&e.param===n)&&!(o(e)&&e.id===n)&&!(o(e)&&r.someof(n,e.params))&&true}function g(e){return p(e)&&(e.$parent.type==="AssignmentExpression"&&e.$parent.left===e||e.$parent.type==="UpdateExpression"&&e.$parent.argument===e)}function R(t,a){l(!t.$scope);t.$parent=a;t.$scope=t.$parent?t.$parent.$scope:null;if(t.type==="Program"){t.$scope=new s({kind:"hoist",node:t,parent:null})}else if(o(t)){t.$scope=new s({kind:"hoist",node:t,parent:t.$parent.$scope});if(t.id){l(t.id.type==="Identifier");if(t.type==="FunctionDeclaration"){t.$parent.$scope.add(t.id.name,"fun",t.id,null)}else if(t.type==="FunctionExpression"){t.$scope.add(t.id.name,"fun",t.id,null)}else{l(false)}}t.params.forEach(function(e){t.$scope.add(e.name,"param",e,null)})}else if(t.type==="VariableDeclaration"){l(v(t.kind));t.declarations.forEach(function(r){l(r.type==="VariableDeclarator");var a=r.id.name;if(i.disallowVars&&t.kind==="var"){n(e(r),"var {0} is not allowed (use let or const)",a)}t.$scope.add(a,t.kind,r.id,r.range[1])})}else if(b(t)||E(t)){t.$scope=new s({kind:"block",node:t,parent:t.$parent.$scope})}else if(O(t)){t.$scope=new s({kind:"block",node:t,parent:t.$parent.$scope})}else if(t.type==="CatchClause"){var r=t.param;t.$scope=new s({kind:"catch-block",node:t,parent:t.$parent.$scope});t.$scope.add(r.name,"caught",r,null);t.$scope.closestHoistScope().markPropagates(r.name)}}function C(r,l,a){function t(t){for(var n in t){var r=t[n];var l=r?"var":"const";if(e.hasOwn(n)){e.remove(n)}e.add(n,l,{loc:{start:{line:-1}}},-1)}}var e=new s({kind:"hoist",node:{},parent:null});var i={undefined:false,Infinity:false,console:false};t(i);t(u.reservedVars);t(u.ecmaIdentifiers);if(l){l.forEach(function(e){if(!u[e]){n(-1,'environment "{0}" not found',e)}else{t(u[e])}})}if(a){t(a)}r.parent=e;e.children.push(r);return e}function A(o,u,t){var s=r.own(t,"analyze")?t.analyze:true;function c(t){if(!p(t)){return}u.add(t.name);var a=t.$scope.lookup(t.name);if(s&&!a&&i.disallowUnknownReferences){n(e(t),"reference to unknown global variable {0}",t.name)}if(s&&a&&r.someof(a.getKind(t.name),["const","let"])){var o=a.getFromPos(t.name);var c=t.range[0];l(r.finitenumber(o));l(r.finitenumber(c));if(c<o){if(!t.$scope.hasFunctionScopeBetween(a)){n(e(t),"{0} is referenced before its declaration",t.name)}}}t.$refToScope=a}a(o,{pre:c})}function T(t,i,r,n){function s(e){l(r.has(e));for(var n=0;;n++){var t=e+"$"+String(n);if(!r.has(t)){return t}}}function o(t){if(t.type==="VariableDeclaration"&&c(t.kind)){var a=t.$scope.closestHoistScope();var o=t.$scope;n.push({start:t.range[0],end:t.range[0]+t.kind.length,str:"var"});t.declarations.forEach(function(u){l(u.type==="VariableDeclarator");var c=u.id.name;i.declarator(t.kind);var p=o!==a&&(a.hasOwn(c)||a.doesPropagate(c));var f=p?s(c):c;o.remove(c);a.add(f,"var",u.id,u.range[1]);o.moves=o.moves||M();o.moves.set(c,{name:f,scope:a});r.add(f);if(f!==c){i.rename(c,f,e(u));u.id.originalName=c;u.id.name=f;n.push({start:u.id.range[0],end:u.id.range[1],str:f})}});t.kind="var"}}function u(e){if(!e.$refToScope){return}var t=e.$refToScope.moves&&e.$refToScope.moves.get(e.name);if(!t){return}e.$refToScope=t.scope;if(e.name!==t.name){e.originalName=e.name;e.name=t.name;if(e.alterop){var r=null;for(var a=0;a<n.length;a++){var i=n[a];if(i.node===e){r=i;break}}l(r);r.str=t.name}else{n.push({start:e.range[0],end:e.range[1],str:t.name})}}}a(t,{pre:o});a(t,{pre:u});t.$scope.traverse({pre:function(e){delete e.moves}})}function L(t){a(t,{pre:s});function r(r,t){return I(function(l){a(r,{pre:function(r){if(o(r)){return false}var i=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(r.type==="BreakStatement"){n(e(t),a,t.name,"break",e(r))}else if(r.type==="ContinueStatement"){n(e(t),a,t.name,"continue",e(r))}else if(r.type==="ReturnStatement"){n(e(t),a,t.name,"return",e(r))}else if(r.type==="YieldExpression"){n(e(t),a,t.name,"yield",e(r))}else if(r.type==="Identifier"&&r.name==="arguments"){n(e(t),a,t.name,"arguments",e(r))}else if(r.type==="VariableDeclaration"&&r.kind==="var"){n(e(t),a,t.name,"var",e(r))}else{i=false}if(i){l(true)}}});return false})}function s(t){var a=null;if(p(t)&&t.$refToScope&&c(t.$refToScope.getKind(t.name))){for(var s=t.$refToScope.node;;){if(o(s)){return}else if(m(s)){a=s;break}s=s.$parent;if(!s){return}}l(m(a));var f=t.$refToScope;var h=i.loopClosures==="iife";for(var u=t.$scope;u;u=u.parent){if(u===f){return}else if(o(u.node)){if(!h){var g='loop-variable {0} is captured by a loop-closure. Tried "loopClosures": "iife" in defs-config.json?';return n(e(t),g,t.name)}if(a.type==="ForStatement"&&f.node===a){var d=f.getNode(t.name);return n(e(d),"Not yet specced ES6 feature. {0} is declared in for-loop header and then captured in loop closure",d.name)}if(r(a.body,t)){return}a.$iify=true}}}}}function P(n,t,r){function e(e,l,n){var r={start:e,end:e,str:l};if(n){r.node=n}t.push(r)}a(n,{pre:function(n){if(!n.$iify){return}var i=n.body.type==="BlockStatement";var d=i?n.body.range[0]+1:n.body.range[0];var l=i?n.body.range[1]-1:n.body.range[1];var t=y(n)&&n.left.declarations[0].id.name;var s=f("(function({0}){",t?t:"");var o=f("}).call(this{0});",t?", "+t:"");var v=r.parse(s+o);var a=v.body[0];var p=a.expression.callee.object.body;if(i){var c=n.body;var m=c.body;c.body=[a];p.body=m}else{var h=n.body;n.body=a;p.body[0]=h}e(d,s);if(t){e(l,"}).call(this, ");var g=a.expression.arguments;var u=g[1];u.alterop=true;e(l,t,u);e(l,");")}else{e(l,o)}}})}function j(t){a(t,{pre:function(t){if(g(t)){var r=t.$scope.lookup(t.name);if(r&&r.getKind(t.name)==="const"){n(e(t),"can't assign to const variable {0}",t.name)}}}})}function D(e){a(e,{pre:function(e){if(g(e)){var n=e.$scope.lookup(e.name);if(n){n.markWrite(e.name)}}}});e.$scope.detectUnmodifiedLets()}function h(e,t){a(e,{pre:R});var r=C(e.$scope,i.environments,i.globals);var n=w();r.traverse({pre:function(e){n.addMany(e.decls.keys())}});A(e,n,t);return n}function d(e){a(e,{pre:function(e){for(var n in e){if(n[0]==="$"){delete e[n]}}}})}function S(t,c){for(var p in c){i[p]=c[p]}var o;if(r.object(t)){if(!i.ast){return{errors:["Can't produce string output when input is an AST. "+"Did you forget to set options.ast = true?"]}}o=t}else if(r.string(t)){try{o=i.parse(t,{loc:true,range:true})}catch(a){return{errors:[f("line {0} column {1}: Error during input file parsing\n{2}\n{3}",a.lineNumber,a.column,t.split("\n")[a.lineNumber-1],f.repeat(" ",a.column-1)+"^")]}}}else{return{errors:["Input was neither an AST object nor a string."]}}var e=o;n.reset();var m=h(e,{});L(e);j(e);var s=[];P(e,s,i);if(n.errors.length>=1){return{errors:n.errors}}if(s.length>0){d(e);m=h(e,{analyze:false})}l(n.errors.length===0);var u=new k;T(e,u,m,s);if(i.ast){d(e);return{stats:u,ast:e}}else{var g=_(t,s);return{stats:u,src:g}}}x.exports=S},{"./error":152,"./jshint_globals/vars.js":153,"./options":154,"./scope":155,"./stats":156,alter:157,assert:110,"ast-traverse":159,breakable:160,"simple-fmt":162,"simple-is":163,stringmap:164,stringset:165}],152:[function(t,r,a){"use strict";var n=t("simple-fmt");var l=t("assert");function e(t,a){l(arguments.length>=2);var r=arguments.length===2?String(a):n.apply(n,Array.prototype.slice.call(arguments,1));e.errors.push(t===-1?r:n("line {0}: {1}",t,r))}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();r.exports=e},{assert:110,"simple-fmt":162}],153:[function(n,t,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}},{}],154:[function(e,n,t){n.exports={disallowVars:false,disallowDuplicated:true,disallowUnknownReferences:true,parse:e("esprima-fb").parse}},{"esprima-fb":161}],155:[function(r,u,f){"use strict";var t=r("assert");var o=r("stringmap");var s=r("stringset");var n=r("simple-is");var a=r("simple-fmt");var l=r("./error");var i=l.getline;var c=r("./options");function e(e){t(n.someof(e.kind,["hoist","block","catch-block"]));t(n.object(e.node));t(e.parent===null||n.object(e.parent));this.kind=e.kind;this.node=e.node;this.parent=e.parent;this.children=[];this.decls=o();this.written=s();this.propagates=this.kind==="hoist"?s():null;if(this.parent){this.parent.children.push(this)}}e.prototype.print=function(e){e=e||0;var n=this;var t=this.decls.keys().map(function(e){return a("{0} [{1}]",e,n.decls.get(e).kind)}).join(", ");var r=this.propagates?this.propagates.items().join(", "):"";console.log(a("{0}{1}: {2}. propagates: {3}",a.repeat(" ",e),this.node.type,t,r));this.children.forEach(function(n){n.print(e+2)})};e.prototype.add=function(r,a,s,u){t(n.someof(a,["fun","param","var","caught","const","let"]));function o(e){return n.someof(e,["const","let"])}var e=this;if(n.someof(a,["fun","param","var"])){while(e.kind!=="hoist"){if(e.decls.has(r)&&o(e.decls.get(r).kind)){return l(i(s),"{0} is already declared",r)}e=e.parent}}if(e.decls.has(r)&&(c.disallowDuplicated||o(e.decls.get(r).kind)||o(a))){return l(i(s),"{0} is already declared",r)}var f={kind:a,node:s};if(u){t(n.someof(a,["var","const","let"]));f.from=u}e.decls.set(r,f)};e.prototype.getKind=function(e){t(n.string(e));var r=this.decls.get(e);return r?r.kind:null};e.prototype.getNode=function(e){t(n.string(e));var r=this.decls.get(e);return r?r.node:null};e.prototype.getFromPos=function(e){t(n.string(e));var r=this.decls.get(e);return r?r.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(t){function r(e){return n.someof(e.type,["FunctionDeclaration","FunctionExpression"])}for(var e=this;e;e=e.parent){if(e===t){return false}if(r(e.node)){return true}}throw new Error("wasn't inner scope of outer")};e.prototype.lookup=function(n){for(var e=this;e;e=e.parent){if(e.decls.has(n)){return e}else if(e.kind==="hoist"){e.propagates.add(n)}}return null};e.prototype.markWrite=function(e){t(n.string(e));this.written.add(e)};e.prototype.detectUnmodifiedLets=function(){var n=this;function e(t){if(t!==n){t.decls.keys().forEach(function(e){if(t.getKind(e)==="let"&&!t.written.has(e)){return l(i(t.getNode(e)),"{0} is declared as let but never modified so could be const",e)}})}t.children.forEach(function(n){e(n)})}e(this)};e.prototype.traverse=function(e){e=e||{};var n=e.pre;var t=e.post;function r(e){if(n){n(e)}e.children.forEach(function(e){r(e)});if(t){t(e)}}r(this)};u.exports=e},{"./error":152,"./options":154,assert:110,"simple-fmt":162,"simple-is":163,stringmap:164,stringset:165}],156:[function(n,r,i){var t=n("simple-fmt");var l=n("simple-is");var a=n("assert");function e(){this.lets=0;this.consts=0;this.renames=[]}e.prototype.declarator=function(e){a(l.someof(e,["const","let"]));if(e==="const"){this.consts++}else{this.lets++}};e.prototype.rename=function(e,n,t){this.renames.push({oldName:e,newName:n,line:t})};e.prototype.toString=function(){var n=this.renames.map(function(e){return e}).sort(function(e,n){return e.line-n.line});var r=n.map(function(e){return t("\nline {0}: {1} => {2}",e.line,e.oldName,e.newName)}).join("");var e=this.consts+this.lets;var l=e===0?"can't calculate const coverage (0 consts, 0 lets)":t("{0}% const coverage ({1} consts, {2} lets)",Math.floor(100*this.consts/e),this.consts,this.lets);return l+r+"\n"};r.exports=e},{assert:110,"simple-fmt":162,"simple-is":163}],157:[function(t,n,a){var e=t("assert");var r=t("stable");function l(l,s){"use strict";var u=Array.isArray||function(e){return Object.prototype.toString.call(e)==="[object Array]"};e(typeof l==="string");e(u(s));var o=r(s,function(e,n){return e.start-n.start});var a=[];var t=0;for(var i=0;i<o.length;i++){var n=o[i];e(t<=n.start);e(n.start<=n.end);a.push(l.slice(t,n.start));a.push(n.str);t=n.end}if(t<l.length){a.push(l.slice(t))}return a.join("")}if(typeof n!=="undefined"&&typeof n.exports!=="undefined"){n.exports=l}},{assert:110,stable:158}],158:[function(n,e,t){(function(){var n=function(e,n){return t(e.slice(),n)};n.inplace=function(e,l){var n=t(e,l);if(n!==e){r(n,null,e.length,e)}return e};function t(e,n){if(typeof n!=="function"){n=function(e,n){return String(e).localeCompare(n)}}var t=e.length;if(t<=1){return e}var l=new Array(t);for(var a=1;a<t;a*=2){r(e,n,a,l);var i=e;e=l;l=i}return e}var r=function(e,c,u,o){var l=e.length;var s=0;var f=u*2;var a,n,i;var t,r;for(a=0;a<l;a+=f){n=a+u;i=n+u;if(n>l)n=l;if(i>l)i=l;t=a;r=n;while(true){if(t<n&&r<i){if(c(e[t],e[r])<=0){o[s++]=e[t++]}else{o[s++]=e[r++]}}else if(t<n){o[s++]=e[t++]}else if(r<i){o[s++]=e[r++]}else{break}}}};if(typeof e!=="undefined"){e.exports=n}else{window.stable=n}})()},{}],159:[function(t,e,r){function n(a,e){"use strict";e=e||{};var t=e.pre;var r=e.post;var l=e.skipProperty;function n(e,o,a,u){if(!e||typeof e.type!=="string"){return}var c=undefined;if(t){c=t(e,o,a,u)}if(c!==false){for(var a in e){if(l?l(a,e):a[0]==="$"){continue}var i=e[a];if(Array.isArray(i)){for(var s=0;s<i.length;s++){n(i[s],e,a,s)}}else{n(i,e,a)}}}if(r){r(e,o,a,u)}}n(a,null)}if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=n}},{}],160:[function(t,e,r){var n=function(){"use strict";function e(e,n){this.val=e;this.brk=n}function n(){return function n(t){throw new e(t,n)}}function t(l){var r=n();try{return l(r)}catch(t){if(t instanceof e&&t.brk===r){return t.val}throw t}}return t}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=n}},{}],161:[function(n,t,e){(function(t,n){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],n)}else if(typeof e!=="undefined"){n(e)}else{n(t.esprima={})}})(this,function(En){"use strict";var u,C,Gn,l,J,i,_n,Fn,Nn,$,s,v,e,h,g,y,t,c,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};C={};C[u.BooleanLiteral]="Boolean";C[u.EOF]="<end>";C[u.Identifier]="Identifier";C[u.Keyword]="Keyword";C[u.NullLiteral]="Null";C[u.NumericLiteral]="Numeric";C[u.Punctuator]="Punctuator";C[u.StringLiteral]="String";C[u.XJSIdentifier]="XJSIdentifier";C[u.XJSText]="XJSText";C[u.RegularExpression]="RegularExpression";Gn=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="];l={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"};J={Data:1,Get:2,Set:4};$={"static":"static",prototype:"prototype"};i={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"};
_n={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 G(e,n){if(!e){throw new Error("ASSERT: "+n)}}function D(e){return e>=48&&e<=57}function Dn(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function U(e){return"01234567".indexOf(e)>=0}function st(e){return e===32||e===9||e===11||e===12||e===160||e>=5760&&" ".indexOf(String.fromCharCode(e))>0}function T(e){return e===10||e===13||e===8232||e===8233}function q(e){return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e===92||e>=128&&_n.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function an(e){return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===92||e>=128&&_n.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function Lr(e){switch(e){case"class":case"enum":case"export":case"extends":case"import":case"super":return true;default:return false}}function un(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 L(e){return e==="eval"||e==="arguments"}function Yr(e){if(v&&un(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 O(){var n,t,r;t=false;r=false;while(e<y){n=s.charCodeAt(e);if(r){++e;if(T(n)){r=false;if(n===13&&s.charCodeAt(e)===10){++e}++h;g=e}}else if(t){if(T(n)){if(n===13){++e}if(n!==13||s.charCodeAt(e)===10){++h;++e;g=e;if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}}else{n=s.charCodeAt(e++);if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}if(n===42){n=s.charCodeAt(e);if(n===47){++e;t=false}}}}else if(n===47){n=s.charCodeAt(e+1);if(n===47){e+=2;r=true}else if(n===42){e+=2;t=true;if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}else{break}}else if(st(n)){++e}else if(T(n)){++e;if(n===13&&s.charCodeAt(e)===10){++e}++h;g=e}else{break}}}function cn(a){var n,r,l,t=0;r=a==="u"?4:2;for(n=0;n<r;++n){if(e<y&&Dn(s[e])){l=s[e++];t=t*16+"0123456789abcdef".indexOf(l.toLowerCase())}else{return""}}return String.fromCharCode(t)}function zn(){var t,n,r,l;t=s[e];n=0;if(t==="}"){d({},i.UnexpectedToken,"ILLEGAL")}while(e<y){t=s[e++];if(!Dn(t)){break}n=n*16+"0123456789abcdef".indexOf(t.toLowerCase())}if(n>1114111||t!=="}"){d({},i.UnexpectedToken,"ILLEGAL")}if(n<=65535){return String.fromCharCode(n)}r=(n-65536>>10)+55296;l=(n-65536&1023)+56320;return String.fromCharCode(r,l)}function Yn(){var n,t;n=s.charCodeAt(e++);t=String.fromCharCode(n);if(n===92){if(s.charCodeAt(e)!==117){d({},i.UnexpectedToken,"ILLEGAL")}++e;n=cn("u");if(!n||n==="\\"||!q(n.charCodeAt(0))){d({},i.UnexpectedToken,"ILLEGAL")}t=n}while(e<y){n=s.charCodeAt(e);if(!an(n)){break}++e;t+=String.fromCharCode(n);if(n===92){t=t.substr(0,t.length-1);if(s.charCodeAt(e)!==117){d({},i.UnexpectedToken,"ILLEGAL")}++e;n=cn("u");if(!n||n==="\\"||!an(n.charCodeAt(0))){d({},i.UnexpectedToken,"ILLEGAL")}t+=n}}return t}function ar(){var n,t;n=e++;while(e<y){t=s.charCodeAt(e);if(t===92){e=n;return Yn()}if(an(t)){++e}else{break}}return s.slice(n,e)}function pr(){var r,n,t;r=e;n=s.charCodeAt(e)===92?Yn():ar();if(n.length===1){t=u.Identifier}else if(Yr(n)){t=u.Keyword}else if(n==="null"){t=u.NullLiteral}else if(n==="true"||n==="false"){t=u.BooleanLiteral}else{t=u.Identifier}return{type:t,value:n,lineNumber:h,lineStart:g,range:[r,e]}}function V(){var n=e,l=s.charCodeAt(e),c,t=s[e],r,o,f;switch(l){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(l===40){p.openParenToken=p.tokens.length}else if(l===123){p.openCurlyToken=p.tokens.length}}return{type:u.Punctuator,value:String.fromCharCode(l),lineNumber:h,lineStart:g,range:[n,e]};default:c=s.charCodeAt(e+1);if(c===61){switch(l){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(l)+String.fromCharCode(c),lineNumber:h,lineStart:g,range:[n,e]};case 33:case 61:e+=2;if(s.charCodeAt(e)===61){++e}return{type:u.Punctuator,value:s.slice(n,e),lineNumber:h,lineStart:g,range:[n,e]};default:break}}break}r=s[e+1];o=s[e+2];f=s[e+3];if(t===">"&&r===">"&&o===">"){if(f==="="){e+=4;return{type:u.Punctuator,value:">>>=",lineNumber:h,lineStart:g,range:[n,e]}}}if(t===">"&&r===">"&&o===">"){e+=3;return{type:u.Punctuator,value:">>>",lineNumber:h,lineStart:g,range:[n,e]}}if(t==="<"&&r==="<"&&o==="="){e+=3;return{type:u.Punctuator,value:"<<=",lineNumber:h,lineStart:g,range:[n,e]}}if(t===">"&&r===">"&&o==="="){e+=3;return{type:u.Punctuator,value:">>=",lineNumber:h,lineStart:g,range:[n,e]}}if(t==="."&&r==="."&&o==="."){e+=3;return{type:u.Punctuator,value:"...",lineNumber:h,lineStart:g,range:[n,e]}}if(t===r&&"+-<>&|".indexOf(t)>=0&&!a.inType){e+=2;return{type:u.Punctuator,value:t+r,lineNumber:h,lineStart:g,range:[n,e]}}if(t==="="&&r===">"){e+=2;return{type:u.Punctuator,value:"=>",lineNumber:h,lineStart:g,range:[n,e]}}if("<>=!+-*%&|^/".indexOf(t)>=0){++e;return{type:u.Punctuator,value:t,lineNumber:h,lineStart:g,range:[n,e]}}if(t==="."){++e;return{type:u.Punctuator,value:t,lineNumber:h,lineStart:g,range:[n,e]}}d({},i.UnexpectedToken,"ILLEGAL")}function qr(t){var n="";while(e<y){if(!Dn(s[e])){break}n+=s[e++]}if(n.length===0){d({},i.UnexpectedToken,"ILLEGAL")}if(q(s.charCodeAt(e))){d({},i.UnexpectedToken,"ILLEGAL")}return{type:u.NumericLiteral,value:parseInt("0x"+n,16),lineNumber:h,lineStart:g,range:[t,e]}}function Wr(r,l){var n,t;if(U(r)){t=true;n="0"+s[e++]}else{t=false;++e;n=""}while(e<y){if(!U(s[e])){break}n+=s[e++]}if(!t&&n.length===0){d({},i.UnexpectedToken,"ILLEGAL")}if(q(s.charCodeAt(e))||D(s.charCodeAt(e))){d({},i.UnexpectedToken,"ILLEGAL")}return{type:u.NumericLiteral,value:parseInt(n,8),octal:t,lineNumber:h,lineStart:g,range:[l,e]}}function Zn(){var t,r,n,l;n=s[e];G(D(n.charCodeAt(0))||n===".","Numeric literal must start with a decimal digit or a decimal point");r=e;t="";if(n!=="."){t=s[e++];n=s[e];if(t==="0"){if(n==="x"||n==="X"){++e;return qr(r)}if(n==="b"||n==="B"){++e;t="";while(e<y){n=s[e];if(n!=="0"&&n!=="1"){break}t+=s[e++]}if(t.length===0){d({},i.UnexpectedToken,"ILLEGAL")}if(e<y){n=s.charCodeAt(e);if(q(n)||D(n)){d({},i.UnexpectedToken,"ILLEGAL")}}return{type:u.NumericLiteral,value:parseInt(t,2),lineNumber:h,lineStart:g,range:[r,e]}}if(n==="o"||n==="O"||U(n)){return Wr(n,r)}if(n&&D(n.charCodeAt(0))){d({},i.UnexpectedToken,"ILLEGAL")}}while(D(s.charCodeAt(e))){t+=s[e++]}n=s[e]}if(n==="."){t+=s[e++];while(D(s.charCodeAt(e))){t+=s[e++]}n=s[e]}if(n==="e"||n==="E"){t+=s[e++];n=s[e];if(n==="+"||n==="-"){t+=s[e++]}if(D(s.charCodeAt(e))){while(D(s.charCodeAt(e))){t+=s[e++]}}else{d({},i.UnexpectedToken,"ILLEGAL")}}if(q(s.charCodeAt(e))){d({},i.UnexpectedToken,"ILLEGAL")}return{type:u.NumericLiteral,value:parseFloat(t),lineNumber:h,lineStart:g,range:[r,e]}}function St(){var t="",l,c,n,r,a,f,o=false;l=s[e];G(l==="'"||l==='"',"String literal must starts with a quote");c=e;++e;while(e<y){n=s[e++];if(n===l){l="";break}else if(n==="\\"){n=s[e++];if(!n||!T(n.charCodeAt(0))){switch(n){case"n":t+="\n";break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":case"x":if(s[e]==="{"){++e;t+=zn()}else{f=e;a=cn(n);if(a){t+=a}else{e=f;t+=n}}break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="";break;default:if(U(n)){r="01234567".indexOf(n);if(r!==0){o=true}if(e<y&&U(s[e])){o=true;r=r*8+"01234567".indexOf(s[e++]);if("0123".indexOf(n)>=0&&e<y&&U(s[e])){r=r*8+"01234567".indexOf(s[e++])}}t+=String.fromCharCode(r)}else{t+=n}break}}else{++h;if(n==="\r"&&s[e]==="\n"){++e}g=e}}else if(T(n.charCodeAt(0))){break}else{t+=n}}if(l!==""){d({},i.UnexpectedToken,"ILLEGAL")}return{type:u.StringLiteral,value:t,octal:o,lineNumber:h,lineStart:g,range:[c,e]}}function rt(){var t="",n,o,l,a,p,c,r,f;l=false;a=false;o=e;++e;while(e<y){n=s[e++];if(n==="`"){a=true;l=true;break}else if(n==="$"){if(s[e]==="{"){++e;l=true;break}t+=n}else if(n==="\\"){n=s[e++];if(!T(n.charCodeAt(0))){switch(n){case"n":t+="\n";break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":case"x":if(s[e]==="{"){++e;t+=zn()}else{p=e;c=cn(n);if(c){t+=c}else{e=p;t+=n}}break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="";break;default:if(U(n)){r="01234567".indexOf(n);if(r!==0){f=true}if(e<y&&U(s[e])){f=true;r=r*8+"01234567".indexOf(s[e++]);if("0123".indexOf(n)>=0&&e<y&&U(s[e])){r=r*8+"01234567".indexOf(s[e++])}}t+=String.fromCharCode(r)}else{t+=n}break}}else{++h;if(n==="\r"&&s[e]==="\n"){++e}g=e}}else if(T(n.charCodeAt(0))){++h;if(n==="\r"&&s[e]==="\n"){++e}g=e;t+="\n"}else{t+=n}}if(!l){d({},i.UnexpectedToken,"ILLEGAL")}return{type:u.Template,value:{cooked:t,raw:s.slice(o+1,e-(a?1:2))},tail:a,octal:f,lineNumber:h,lineStart:g,range:[o,e]}}function Xt(r){var n,t;c=null;O();n=r.head?"`":"}";if(s[e]!==n){d({},i.UnexpectedToken,"ILLEGAL")}t=rt();mn();return t}function N(){var t,n,v,l,r,a,m=false,o,x=false,f;c=null;O();v=e;n=s[e];G(n==="/","Regular expression literal must start with a slash");t=s[e++];while(e<y){n=s[e++];t+=n;if(m){if(n==="]"){m=false}}else{if(n==="\\"){n=s[e++];if(T(n.charCodeAt(0))){d({},i.UnterminatedRegExp)}t+=n}else if(n==="/"){x=true;break}else if(n==="["){m=true}else if(T(n.charCodeAt(0))){d({},i.UnterminatedRegExp)}}}if(!x){d({},i.UnterminatedRegExp)}l=t.substr(1,t.length-2);r="";while(e<y){n=s[e];if(!an(n.charCodeAt(0))){break}++e;if(n==="\\"&&e<y){n=s[e];if(n==="u"){++e;o=e;n=cn("u");if(n){r+=n;for(t+="\\u";o<e;++o){t+=s[o]}}else{e=o;r+="u";t+="\\u"}}else{t+="\\"}}else{r+=n;t+=n}}f=l;if(r.indexOf("u")>=0){f=f.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}try{a=new RegExp(f)}catch(b){d({},i.InvalidRegExp)}try{a=new RegExp(l,r)}catch(E){a=null}mn();if(p.tokenize){return{type:u.RegularExpression,value:a,regex:{pattern:l,flags:r},lineNumber:h,lineStart:g,range:[v,e]}}return{literal:t,value:a,regex:{pattern:l,flags:r},range:[v,e]}}function On(e){return e.type===u.Identifier||e.type===u.Keyword||e.type===u.BooleanLiteral||e.type===u.NullLiteral}function gr(){var n,e;n=p.tokens[p.tokens.length-1];if(!n){return N()}if(n.type==="Punctuator"){if(n.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 V()}if(n.value==="}"){if(p.tokens[p.openCurlyToken-3]&&p.tokens[p.openCurlyToken-3].type==="Keyword"){e=p.tokens[p.openCurlyToken-4];if(!e){return V()}}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 V()}if(Gn.indexOf(e.value)>=0){return V()}return N()}return N()}if(n.type==="Keyword"){return N()}return V()}function nn(){var n;if(!a.inXJSChild){O()}if(e>=y){return{type:u.EOF,lineNumber:h,lineStart:g,range:[e,e]}}if(a.inXJSChild){return Ar()}n=s.charCodeAt(e);if(n===40||n===41||n===58){return V()}if(n===39||n===34){if(a.inXJSTag){return Cr()}return St()}if(a.inXJSTag&&_r(n)){return kr()}if(n===96){return rt()}if(q(n)){return pr()}if(n===46){if(D(s.charCodeAt(e+1))){return Zn()}return V()}if(D(n)){return Zn()}if(p.tokenize&&n===47){return gr()}return V()}function m(){var n;n=c;e=n.range[1];h=n.lineNumber;g=n.lineStart;c=nn();e=n.range[1];h=n.lineNumber;g=n.lineStart;return n}function mn(){var n,t,r;n=e;t=h;r=g;c=nn();e=n;h=t;g=r}function P(){var n,t,r,l,a;n=typeof p.advance==="function"?p.advance:nn;t=e;r=h;l=g;if(c===null){c=n()}e=c.range[1];h=c.lineNumber;g=c.lineStart;a=n();e=t;h=r;g=l;return a}function fn(n){e=n.range[0];h=n.lineNumber;g=n.lineStart;c=n}function f(){if(!p.loc&&!p.range){return undefined}O();return{offset:e,line:h,col:e-g}}function Xn(){if(!p.loc&&!p.range){return undefined}return{offset:e,line:h,col:e-g}}function er(e){var t,r,a=p.bottomRightStack,n=a[a.length-1];if(e.type===l.Program){if(e.body.length>0){return}}if(p.trailingComments.length>0){if(p.trailingComments[0].range[0]>=e.range[1]){r=p.trailingComments;p.trailingComments=[]}else{p.trailingComments.length=0}}else{if(n&&n.trailingComments&&n.trailingComments[0].range[0]>=e.range[1]){r=n.trailingComments;delete n.trailingComments}}if(n){while(n&&n.range[0]>=e.range[0]){t=n;n=a.pop()}}if(t){if(t.leadingComments&&t.leadingComments[t.leadingComments.length-1].range[1]<=e.range[0]){e.leadingComments=t.leadingComments;delete t.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(r){e.trailingComments=r}a.push(e)}function n(r,n){if(p.range){n.range=[r.offset,e]}if(p.loc){n.loc={start:{line:r.line,column:r.col},end:{line:h,column:e-g}};n=t.postProcess(n)}if(p.attachComment){er(n)}return n}Fn={name:"SyntaxTree",postProcess:function(e){return e},createArrayExpression:function(e){return{type:l.ArrayExpression,elements:e}},createAssignmentExpression:function(e,n,t){return{type:l.AssignmentExpression,operator:e,left:n,right:t}},createBinaryExpression:function(e,n,t){var r=e==="||"||e==="&&"?l.LogicalExpression:l.BinaryExpression;return{type:r,operator:e,left:n,right:t}},createBlockStatement:function(e){return{type:l.BlockStatement,body:e}},createBreakStatement:function(e){return{type:l.BreakStatement,label:e}},createCallExpression:function(e,n){return{type:l.CallExpression,callee:e,arguments:n}},createCatchClause:function(e,n){return{type:l.CatchClause,param:e,body:n}},createConditionalExpression:function(e,n,t){return{type:l.ConditionalExpression,test:e,consequent:n,alternate:t}},createContinueStatement:function(e){return{type:l.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:l.DebuggerStatement}},createDoWhileStatement:function(e,n){return{type:l.DoWhileStatement,body:e,test:n}},createEmptyStatement:function(){return{type:l.EmptyStatement}},createExpressionStatement:function(e){return{type:l.ExpressionStatement,expression:e}},createForStatement:function(e,n,t,r){return{type:l.ForStatement,init:e,test:n,update:t,body:r}},createForInStatement:function(e,n,t){return{type:l.ForInStatement,left:e,right:n,body:t,each:false}},createForOfStatement:function(e,n,t){return{type:l.ForOfStatement,left:e,right:n,body:t}},createFunctionDeclaration:function(n,i,t,r,a,f,s,o,u,c){var e={type:l.FunctionDeclaration,id:n,params:i,defaults:t,body:r,rest:a,generator:f,expression:s,returnType:u,typeParameters:c};if(o){e.async=true}return e},createFunctionExpression:function(n,i,t,r,a,f,s,o,u,c){var e={type:l.FunctionExpression,id:n,params:i,defaults:t,body:r,rest:a,generator:f,expression:s,returnType:u,typeParameters:c};if(o){e.async=true}return e},createIdentifier:function(e){return{type:l.Identifier,name:e,typeAnnotation:undefined,optional:undefined}},createTypeAnnotation:function(e){return{type:l.TypeAnnotation,typeAnnotation:e}},createFunctionTypeAnnotation:function(e,n,t,r){return{type:l.FunctionTypeAnnotation,params:e,returnType:n,rest:t,typeParameters:r}},createFunctionTypeParam:function(e,n,t){return{type:l.FunctionTypeParam,name:e,typeAnnotation:n,optional:t}},createNullableTypeAnnotation:function(e){return{type:l.NullableTypeAnnotation,typeAnnotation:e}},createArrayTypeAnnotation:function(e){return{type:l.ArrayTypeAnnotation,elementType:e}},createGenericTypeAnnotation:function(e,n){return{type:l.GenericTypeAnnotation,id:e,typeParameters:n}},createQualifiedTypeIdentifier:function(e,n){return{type:l.QualifiedTypeIdentifier,qualification:e,id:n}},createTypeParameterDeclaration:function(e){return{type:l.TypeParameterDeclaration,params:e}},createTypeParameterInstantiation:function(e){return{type:l.TypeParameterInstantiation,params:e}},createAnyTypeAnnotation:function(){return{type:l.AnyTypeAnnotation}},createBooleanTypeAnnotation:function(){return{type:l.BooleanTypeAnnotation}},createNumberTypeAnnotation:function(){return{type:l.NumberTypeAnnotation}},createStringTypeAnnotation:function(){return{type:l.StringTypeAnnotation}},createStringLiteralTypeAnnotation:function(e){return{type:l.StringLiteralTypeAnnotation,value:e.value,raw:s.slice(e.range[0],e.range[1])}},createVoidTypeAnnotation:function(){return{type:l.VoidTypeAnnotation}},createTypeofTypeAnnotation:function(e){return{type:l.TypeofTypeAnnotation,argument:e}},createTupleTypeAnnotation:function(e){return{type:l.TupleTypeAnnotation,types:e}},createObjectTypeAnnotation:function(e,n,t){return{type:l.ObjectTypeAnnotation,properties:e,indexers:n,callProperties:t}},createObjectTypeIndexer:function(e,n,t,r){return{type:l.ObjectTypeIndexer,id:e,key:n,value:t,"static":r}},createObjectTypeCallProperty:function(e,n){return{type:l.ObjectTypeCallProperty,value:e,"static":n}},createObjectTypeProperty:function(e,n,t,r){return{type:l.ObjectTypeProperty,key:e,value:n,optional:t,"static":r}},createUnionTypeAnnotation:function(e){return{type:l.UnionTypeAnnotation,types:e}},createIntersectionTypeAnnotation:function(e){return{type:l.IntersectionTypeAnnotation,types:e}},createTypeAlias:function(e,n,t){return{type:l.TypeAlias,id:e,typeParameters:n,right:t}},createInterface:function(e,n,t,r){return{type:l.InterfaceDeclaration,id:e,typeParameters:n,body:t,"extends":r}},createInterfaceExtends:function(e,n){return{type:l.InterfaceExtends,id:e,typeParameters:n}},createDeclareFunction:function(e){return{type:l.DeclareFunction,id:e}},createDeclareVariable:function(e){return{type:l.DeclareVariable,id:e}},createDeclareModule:function(e,n){return{type:l.DeclareModule,id:e,body:n}},createXJSAttribute:function(e,n){return{type:l.XJSAttribute,name:e,value:n||null}},createXJSSpreadAttribute:function(e){return{type:l.XJSSpreadAttribute,argument:e}},createXJSIdentifier:function(e){return{type:l.XJSIdentifier,name:e}},createXJSNamespacedName:function(e,n){return{type:l.XJSNamespacedName,namespace:e,name:n}},createXJSMemberExpression:function(e,n){return{type:l.XJSMemberExpression,object:e,property:n}},createXJSElement:function(e,n,t){return{type:l.XJSElement,openingElement:e,closingElement:n,children:t}},createXJSEmptyExpression:function(){return{type:l.XJSEmptyExpression}},createXJSExpressionContainer:function(e){return{type:l.XJSExpressionContainer,expression:e}},createXJSOpeningElement:function(e,n,t){return{type:l.XJSOpeningElement,name:e,selfClosing:t,attributes:n}},createXJSClosingElement:function(e){return{type:l.XJSClosingElement,name:e}},createIfStatement:function(e,n,t){return{type:l.IfStatement,test:e,consequent:n,alternate:t}},createLabeledStatement:function(e,n){return{type:l.LabeledStatement,label:e,body:n}},createLiteral:function(e){var n={type:l.Literal,value:e.value,raw:s.slice(e.range[0],e.range[1])};if(e.regex){n.regex=e.regex}return n},createMemberExpression:function(e,n,t){return{type:l.MemberExpression,computed:e==="[",object:n,property:t}},createNewExpression:function(e,n){return{type:l.NewExpression,callee:e,arguments:n}},createObjectExpression:function(e){return{type:l.ObjectExpression,properties:e}},createPostfixExpression:function(e,n){return{type:l.UpdateExpression,operator:e,argument:n,prefix:false}},createProgram:function(e){return{type:l.Program,body:e}},createProperty:function(e,n,t,r,a,i){return{type:l.Property,key:n,value:t,kind:e,method:r,shorthand:a,computed:i}},createReturnStatement:function(e){return{type:l.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:l.SequenceExpression,expressions:e}},createSwitchCase:function(e,n){return{type:l.SwitchCase,test:e,consequent:n}},createSwitchStatement:function(e,n){return{type:l.SwitchStatement,discriminant:e,cases:n}},createThisExpression:function(){return{type:l.ThisExpression}},createThrowStatement:function(e){return{type:l.ThrowStatement,argument:e}},createTryStatement:function(e,n,t,r){return{type:l.TryStatement,block:e,guardedHandlers:n,handlers:t,finalizer:r}},createUnaryExpression:function(e,n){if(e==="++"||e==="--"){return{type:l.UpdateExpression,operator:e,argument:n,prefix:true}}return{type:l.UnaryExpression,operator:e,argument:n,prefix:true}},createVariableDeclaration:function(e,n){return{type:l.VariableDeclaration,declarations:e,kind:n}},createVariableDeclarator:function(e,n){return{type:l.VariableDeclarator,id:e,init:n}},createWhileStatement:function(e,n){return{type:l.WhileStatement,test:e,body:n}},createWithStatement:function(e,n){return{type:l.WithStatement,object:e,body:n}},createTemplateElement:function(e,n){return{type:l.TemplateElement,value:e,tail:n}},createTemplateLiteral:function(e,n){return{type:l.TemplateLiteral,quasis:e,expressions:n}},createSpreadElement:function(e){return{type:l.SpreadElement,argument:e}},createSpreadProperty:function(e){return{type:l.SpreadProperty,argument:e}},createTaggedTemplateExpression:function(e,n){return{type:l.TaggedTemplateExpression,tag:e,quasi:n}},createArrowFunctionExpression:function(n,t,r,a,i,s){var e={type:l.ArrowFunctionExpression,id:null,params:n,defaults:t,body:r,rest:a,generator:false,expression:i};if(s){e.async=true}return e},createMethodDefinition:function(e,n,t,r){return{type:l.MethodDefinition,key:t,value:r,kind:n,"static":e===$.static}},createClassProperty:function(e,n,t,r){return{type:l.ClassProperty,key:e,typeAnnotation:n,computed:t,"static":r}},createClassBody:function(e){return{type:l.ClassBody,body:e}},createClassImplements:function(e,n){return{type:l.ClassImplements,id:e,typeParameters:n}},createClassExpression:function(e,n,t,r,a,i){return{type:l.ClassExpression,id:e,superClass:n,body:t,typeParameters:r,superTypeParameters:a,"implements":i}},createClassDeclaration:function(e,n,t,r,a,i){return{type:l.ClassDeclaration,id:e,superClass:n,body:t,typeParameters:r,superTypeParameters:a,"implements":i}},createModuleSpecifier:function(e){return{type:l.ModuleSpecifier,value:e.value,raw:s.slice(e.range[0],e.range[1])}},createExportSpecifier:function(e,n){return{type:l.ExportSpecifier,id:e,name:n}},createExportBatchSpecifier:function(){return{type:l.ExportBatchSpecifier}},createImportDefaultSpecifier:function(e){return{type:l.ImportDefaultSpecifier,id:e}},createImportNamespaceSpecifier:function(e){return{type:l.ImportNamespaceSpecifier,id:e}},createExportDeclaration:function(e,n,t,r){return{type:l.ExportDeclaration,"default":!!e,declaration:n,specifiers:t,source:r}},createImportSpecifier:function(e,n){return{type:l.ImportSpecifier,id:e,name:n}},createImportDeclaration:function(e,n){return{type:l.ImportDeclaration,specifiers:e,source:n}},createYieldExpression:function(e,n){return{type:l.YieldExpression,argument:e,delegate:n}},createAwaitExpression:function(e){return{type:l.AwaitExpression,argument:e}},createComprehensionExpression:function(e,n,t){return{type:l.ComprehensionExpression,filter:e,blocks:n,body:t}}};function K(){var t,n,r,l;t=e;n=h;r=g;O();l=h!==n;e=t;h=n;g=r;return l}function d(t,a){var n,l=Array.prototype.slice.call(arguments,2),r=a.replace(/%(\d)/g,function(n,e){G(e<l.length,"Message reference must be in range");return l[e]});if(typeof t.lineNumber==="number"){n=new Error("Line "+t.lineNumber+": "+r);n.index=t.range[0];n.lineNumber=t.lineNumber;n.column=t.range[0]-g+1}else{n=new Error("Line "+h+": "+r);n.index=e;n.lineNumber=h;n.column=e-g+1}n.description=r;throw n}function E(){try{d.apply(null,arguments)}catch(e){if(p.errors){p.errors.push(e)}else{throw e}}}function I(e){if(e.type===u.EOF){d(e,i.UnexpectedEOS)}if(e.type===u.NumericLiteral){d(e,i.UnexpectedNumber)}if(e.type===u.StringLiteral||e.type===u.XJSText){d(e,i.UnexpectedString)}if(e.type===u.Identifier){d(e,i.UnexpectedIdentifier)}if(e.type===u.Keyword){if(Lr(e.value)){d(e,i.UnexpectedReserved)}else if(v&&un(e.value)){E(e,i.StrictReservedWord);return}d(e,i.UnexpectedToken,e.value)}if(e.type===u.Template){d(e,i.UnexpectedTemplate,e.value.raw)}d(e,i.UnexpectedToken,e.value)}function o(n){var e=m();if(e.type!==u.Punctuator||e.value!==n){I(e)}}function b(n,t){var e=m();if(e.type!==(t?u.Identifier:u.Keyword)||e.value!==n){I(e)}}function X(e){return b(e,true)}function r(e){return c.type===u.Punctuator&&c.value===e}function x(e,n){var t=n?u.Identifier:u.Keyword;return c.type===t&&c.value===e}function _(e){return x(e,true)}function tr(){var e;if(c.type!==u.Punctuator){return false}e=c.value;return e==="="||e==="*="||e==="/="||e==="%="||e==="+="||e==="-="||e==="<<="||e===">>="||e===">>>="||e==="&="||e==="^="||e==="|="}function lr(){return a.yieldAllowed&&x("yield",!v)}function ln(){var n=c,e=false;if(_("async")){m();e=!K();fn(n)}return e}function ir(){return a.awaitAllowed&&_("await")}function S(){var n,t=e,l=h,a=g,i=c;if(s.charCodeAt(e)===59){m();return}n=h;O();if(h!==n){e=t;h=l;g=a;c=i;return}if(r(";")){m();return}if(c.type!==u.EOF&&!r("}")){I(c)}}function vn(e){return e.type===l.Identifier||e.type===l.MemberExpression}function Tr(e){return vn(e)||e.type===l.ObjectPattern||e.type===l.ArrayPattern}function xn(){var a=[],s=[],h=null,e,p=true,y,g=f();o("[");while(!r("]")){if(c.value==="for"&&c.type===u.Keyword){if(!p){d({},i.ComprehensionError)}x("for");e=$n({ignoreBody:true});e.of=e.type===l.ForOfStatement;e.type=l.ComprehensionBlock;if(e.left.kind){d({},i.ComprehensionError)}s.push(e)}else if(c.value==="if"&&c.type===u.Keyword){if(!p){d({},i.ComprehensionError)}b("if");o("(");h=w();o(")")}else if(c.value===","&&c.type===u.Punctuator){p=false;m();a.push(null)}else{e=Ln();a.push(e);if(e&&e.type===l.SpreadElement){if(!r("]")){d({},i.ElementAfterSpreadElement)}}else if(!(r("]")||x("for")||x("if"))){o(",");p=false}}}o("]");if(h&&!s.length){d({},i.ComprehensionRequiresBlock)}if(s.length){if(a.length!==1){d({},i.ComprehensionError)}return n(g,t.createComprehensionExpression(h,s,a[0]))}return n(g,t.createArrayExpression(a))}function rn(e){var o,u,c,r,p,s,d=f();o=v;u=a.yieldAllowed;a.yieldAllowed=e.generator;c=a.awaitAllowed;a.awaitAllowed=e.async;r=e.params||[];p=e.defaults||[];s=Qn();if(e.name&&v&&L(r[0].name)){E(e.name,i.StrictParamName)}v=o;a.yieldAllowed=u;a.awaitAllowed=c;return n(d,t.createFunctionExpression(null,r,p,s,e.rest||null,e.generator,s.type!==l.BlockStatement,e.async,e.returnType,e.typeParameters))}function en(n){var t,e,r;t=v;v=true;e=hn();if(e.stricted){E(e.stricted,e.message)}r=rn({params:e.params,defaults:e.defaults,rest:e.rest,generator:n.generator,async:n.async,returnType:e.returnType,typeParameters:n.typeParameters});v=t;return r}function j(){var r=f(),e=m(),l,a;if(e.type===u.StringLiteral||e.type===u.NumericLiteral){if(v&&e.octal){E(e,i.StrictOctalLiteral)}return n(r,t.createLiteral(e))}if(e.type===u.Punctuator&&e.value==="["){r=f();l=R();a=n(r,l);o("]");return a}return n(r,t.createIdentifier(e.value))}function el(){var l,a,s,h,d,g,e,i=f(),p;l=c;e=l.value==="[";if(l.type===u.Identifier||e||ln()){s=j();if(r(":")){m();return n(i,t.createProperty("init",s,R(),false,false,e))}if(r("(")){return n(i,t.createProperty("init",s,en({generator:false,async:false}),true,false,e))}if(l.value==="get"){e=c.value==="[";a=j();o("(");o(")");if(r(":")){p=M()}return n(i,t.createProperty("get",a,rn({generator:false,async:false,returnType:p}),false,false,e))}if(l.value==="set"){e=c.value==="[";a=j();o("(");l=c;d=[tn()];o(")");if(r(":")){p=M()}return n(i,t.createProperty("set",a,rn({params:d,generator:false,async:false,name:l,returnType:p}),false,false,e))}if(l.value==="async"){e=c.value==="[";a=j();return n(i,t.createProperty("init",a,en({generator:false,async:true}),true,false,e))}if(e){I(c)}return n(i,t.createProperty("init",s,s,false,true,false))}if(l.type===u.EOF||l.type===u.Punctuator){if(!r("*")){I(l)}m();e=c.type===u.Punctuator&&c.value==="[";s=j();if(!r("(")){I(m())}return n(i,t.createProperty("init",s,en({generator:true}),true,false,e))}a=j();if(r(":")){m();return n(i,t.createProperty("init",a,R(),false,false,false))}if(r("(")){return n(i,t.createProperty("init",a,en({generator:false}),true,false,false))}I(m())}function nl(){var e=f();o("...");return n(e,t.createSpreadProperty(R()))}function dn(){var p=[],e,c,s,a,u={},d=String,m=f();o("{");while(!r("}")){if(r("...")){e=nl()}else{e=el();if(e.key.type===l.Identifier){c=e.key.name}else{c=d(e.key.value)}a=e.kind==="init"?J.Data:e.kind==="get"?J.Get:J.Set;s="$"+c;if(Object.prototype.hasOwnProperty.call(u,s)){if(u[s]===J.Data){if(v&&a===J.Data){E({},i.StrictDuplicateProperty)}else if(a!==J.Data){E({},i.AccessorDataProperty)}}else{if(a===J.Data){E({},i.AccessorDataProperty)}else if(u[s]&a){E({},i.AccessorGetSet)}}u[s]|=a}else{u[s]=a}}p.push(e);if(!r("}")){o(",")}}o("}");return n(m,t.createObjectExpression(p))}function _t(r){var l=f(),e=Xt(r);if(v&&e.octal){d(e,i.StrictOctalLiteral)}return n(l,t.createTemplateElement({raw:e.value.raw,cooked:e.value.cooked},e.tail))}function Sn(){var e,r,l,a=f();e=_t({head:true});r=[e];l=[];while(!e.tail){l.push(w());e=_t({head:false});r.push(e)}return n(a,t.createTemplateLiteral(r,l))}function Zt(){var e;o("(");++a.parenthesizedCount;e=w();o(")");return e}function et(){var e;if(ln()){e=P();if(e.type===u.Keyword&&e.value==="function"){return true}}return false}function nt(){var e,l,a,s;l=c.type;if(l===u.Identifier){e=f();return n(e,t.createIdentifier(m().value))}if(l===u.StringLiteral||l===u.NumericLiteral){if(v&&c.octal){E(c,i.StrictOctalLiteral)}e=f();return n(e,t.createLiteral(m()))}if(l===u.Keyword){if(x("this")){e=f();m();return n(e,t.createThisExpression())}if(x("function")){return Mn()}if(x("class")){return it()}if(x("super")){e=f();m();return n(e,t.createIdentifier("super"))}}if(l===u.BooleanLiteral){e=f();a=m();a.value=a.value==="true";return n(e,t.createLiteral(a))}if(l===u.NullLiteral){e=f();a=m();a.value=null;return n(e,t.createLiteral(a))}if(r("[")){return xn()}if(r("{")){return dn()}if(r("(")){return Zt()}if(r("/")||r("/=")){e=f();return n(e,t.createLiteral(N()))
}if(l===u.Template){return Sn()}if(r("<")){return Bn()}I(m())}function tt(){var t=[],n;o("(");if(!r(")")){while(e<y){n=Ln();t.push(n);if(r(")")){break}else if(n.type===l.SpreadElement){d({},i.ElementAfterSpreadElement)}o(",")}}o(")");return t}function Ln(){if(r("...")){var e=f();m();return n(e,t.createSpreadElement(R()))}return R()}function W(){var r=f(),e=m();if(!On(e)){I(e)}return n(r,t.createIdentifier(e.value))}function ut(){o(".");return W()}function gt(){var e;o("[");e=w();o("]");return e}function Un(){var e,l,a=f();b("new");e=jr();l=r("(")?tt():[];return n(a,t.createNewExpression(e,l))}function An(){var e,a,l=f();e=x("new")?Un():nt();while(r(".")||r("[")||r("(")||c.type===u.Template){if(r("(")){a=tt();e=n(l,t.createCallExpression(e,a))}else if(r("[")){e=n(l,t.createMemberExpression("[",e,gt()))}else if(r(".")){e=n(l,t.createMemberExpression(".",e,ut()))}else{e=n(l,t.createTaggedTemplateExpression(e,Sn()))}}return e}function jr(){var e,l=f();e=x("new")?Un():nt();while(r(".")||r("[")||c.type===u.Template){if(r("[")){e=n(l,t.createMemberExpression("[",e,gt()))}else if(r(".")){e=n(l,t.createMemberExpression(".",e,ut()))}else{e=n(l,t.createTaggedTemplateExpression(e,Sn()))}}return e}function Jn(){var s=f(),e=An(),a;if(c.type!==u.Punctuator){return e}if((r("++")||r("--"))&&!K()){if(v&&e.type===l.Identifier&&L(e.name)){E({},i.StrictLHSPostfix)}if(!vn(e)){d({},i.InvalidLHSInAssignment)}a=m();e=n(s,t.createPostfixExpression(a.value,e))}return e}function Z(){var a,s,e;if(c.type!==u.Punctuator&&c.type!==u.Keyword){return Jn()}if(r("++")||r("--")){a=f();s=m();e=Z();if(v&&e.type===l.Identifier&&L(e.name)){E({},i.StrictLHSPrefix)}if(!vn(e)){d({},i.InvalidLHSInAssignment)}return n(a,t.createUnaryExpression(s.value,e))}if(r("+")||r("-")||r("~")||r("!")){a=f();s=m();e=Z();return n(a,t.createUnaryExpression(s.value,e))}if(x("delete")||x("void")||x("typeof")){a=f();s=m();e=Z();e=n(a,t.createUnaryExpression(s.value,e));if(v&&e.operator==="delete"&&e.argument.type===l.Identifier){E({},i.StrictDelete)}return e}return Jn()}function Wn(n,t){var e=0;if(n.type!==u.Punctuator&&n.type!==u.Keyword){return 0}switch(n.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=t?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 $r(){var r,i,u,d,e,h,g,p,o,l,s;d=a.allowIn;a.allowIn=true;l=f();p=Z();i=c;u=Wn(i,d);if(u===0){return p}i.prec=u;m();s=[l,f()];h=Z();e=[p,i,h];while((u=Wn(c,d))>0){while(e.length>2&&u<=e[e.length-2].prec){h=e.pop();g=e.pop().value;p=e.pop();r=t.createBinaryExpression(g,p,h);s.pop();l=s.pop();n(l,r);e.push(r);s.push(l)}i=m();i.prec=u;e.push(i);s.push(f());r=Z();e.push(r)}a.allowIn=d;o=e.length-1;r=e[o];s.pop();while(o>1){r=t.createBinaryExpression(e[o-1].value,e[o-2],r);o-=2;l=s.pop();n(l,r)}return r}function Hn(){var e,l,i,s,u=f();e=$r();if(r("?")){m();l=a.allowIn;a.allowIn=true;i=R();a.allowIn=l;o(":");s=R();e=n(u,t.createConditionalExpression(e,i,s))}return e}function z(e){var n,t,r,a;if(e.type===l.ObjectExpression){e.type=l.ObjectPattern;for(n=0,t=e.properties.length;n<t;n+=1){r=e.properties[n];if(r.type===l.SpreadProperty){if(n<t-1){d({},i.PropertyAfterSpreadProperty)}z(r.argument)}else{if(r.kind!=="init"){d({},i.InvalidLHSInAssignment)}z(r.value)}}}else if(e.type===l.ArrayExpression){e.type=l.ArrayPattern;for(n=0,t=e.elements.length;n<t;n+=1){a=e.elements[n];if(a){z(a)}}}else if(e.type===l.Identifier){if(L(e.name)){d({},i.InvalidLHSInAssignment)}}else if(e.type===l.SpreadElement){z(e.argument);if(e.argument.type===l.ObjectPattern){d({},i.ObjectPatternAsSpread)}}else{if(e.type!==l.MemberExpression&&e.type!==l.CallExpression&&e.type!==l.NewExpression){d({},i.InvalidLHSInAssignment)}}}function Y(a,e){var n,t,r,s;if(e.type===l.ObjectExpression){e.type=l.ObjectPattern;for(n=0,t=e.properties.length;n<t;n+=1){r=e.properties[n];if(r.type===l.SpreadProperty){if(n<t-1){d({},i.PropertyAfterSpreadProperty)}Y(a,r.argument)}else{if(r.kind!=="init"){d({},i.InvalidLHSInFormalsList)}Y(a,r.value)}}}else if(e.type===l.ArrayExpression){e.type=l.ArrayPattern;for(n=0,t=e.elements.length;n<t;n+=1){s=e.elements[n];if(s){Y(a,s)}}}else if(e.type===l.Identifier){yn(a,e,e.name)}else{if(e.type!==l.MemberExpression){d({},i.InvalidLHSInFormalsList)}}}function Cn(c){var r,s,e,a,t,o,n,u;a=[];t=[];o=0;u=null;n={paramSet:{}};for(r=0,s=c.length;r<s;r+=1){e=c[r];if(e.type===l.Identifier){a.push(e);t.push(null);yn(n,e,e.name)}else if(e.type===l.ObjectExpression||e.type===l.ArrayExpression){Y(n,e);a.push(e);t.push(null)}else if(e.type===l.SpreadElement){G(r===s-1,"It is guaranteed that SpreadElement is last element by parseExpression");Y(n,e.argument);u=e.argument}else if(e.type===l.AssignmentExpression){a.push(e.left);t.push(e.right);++o;yn(n,e.left,e.left.name)}else{return null}}if(n.message===i.StrictParamDupe){d(v?n.stricted:n.firstRestricted,n.message)}if(o===0){t=[]}return{params:a,defaults:t,rest:u,stricted:n.stricted,firstRestricted:n.firstRestricted,message:n.message}}function In(e,c){var i,s,u,r;o("=>");i=v;s=a.yieldAllowed;a.yieldAllowed=false;u=a.awaitAllowed;a.awaitAllowed=!!e.async;r=Qn();if(v&&e.firstRestricted){d(e.firstRestricted,e.message)}if(v&&e.stricted){E(e.stricted,e.message)}v=i;a.yieldAllowed=s;a.awaitAllowed=u;return n(c,t.createArrowFunctionExpression(e.params,e.defaults,r,e.rest,r.type!==l.BlockStatement,!!e.async))}function R(){var h,e,o,s,g,y=c,p=false;if(lr()){return sr()}if(ir()){return or()}g=a.parenthesizedCount;h=f();if(et()){return Mn()}if(ln()){p=true;m()}if(r("(")){o=P();if(o.type===u.Punctuator&&o.value===")"||o.value==="..."){s=hn();if(!r("=>")){I(m())}s.async=p;return In(s,h)}}o=c;if(p&&!r("(")&&o.type!==u.Identifier){p=false;fn(y)}e=Hn();if(r("=>")&&(a.parenthesizedCount===g||a.parenthesizedCount===g+1)){if(e.type===l.Identifier){s=Cn([e])}else if(e.type===l.SequenceExpression){s=Cn(e.expressions)}if(s){s.async=p;return In(s,h)}}if(p){p=false;fn(y);e=Hn()}if(tr()){if(v&&e.type===l.Identifier&&L(e.name)){E(o,i.StrictLHSAssignment)}if(r("=")&&(e.type===l.ObjectExpression||e.type===l.ArrayExpression)){z(e)}else if(!vn(e)){d({},i.InvalidLHSInAssignment)}e=n(h,t.createAssignmentExpression(m().value,e,R()))}return e}function w(){var u,s,o,h,c,g,p;p=a.parenthesizedCount;u=f();s=R();o=[s];if(r(",")){while(e<y){if(!r(",")){break}m();s=Ln();o.push(s);if(s.type===l.SpreadElement){g=true;if(!r(")")){d({},i.ElementAfterSpreadElement)}break}}h=n(u,t.createSequenceExpression(o))}if(r("=>")){if(a.parenthesizedCount===p||a.parenthesizedCount===p+1){s=s.type===l.SequenceExpression?s.expressions:o;c=Cn(s);if(c){return In(c,u)}}I(m())}if(g&&P().value!=="=>"){d({},i.IllegalSpread)}return h||s}function nr(){var t=[],n;while(e<y){if(r("}")){break}n=H();if(typeof n==="undefined"){break}t.push(n)}return t}function gn(){var e,r=f();o("{");e=nr();o("}");return n(r,t.createBlockStatement(e))}function F(){var l=f(),e=[];o("<");while(!r(">")){e.push(k());if(!r(">")){o(",")}}o(">");return n(l,t.createTypeParameterDeclaration(e))}function sn(){var l=f(),i=a.inType,e=[];a.inType=true;o("<");while(!r(">")){e.push(A());if(!r(">")){o(",")}}o(">");a.inType=i;return n(l,t.createTypeParameterInstantiation(e))}function al(a,i){var e,r,l;o("[");e=j();o(":");r=A();o("]");o(":");l=A();return n(a,t.createObjectTypeIndexer(e,r,l,i))}function ct(s){var e=[],l=null,a,i=null;if(r("<")){i=F()}o("(");while(c.type===u.Identifier){e.push(bn());if(!r(")")){o(",")}}if(r("...")){m();l=bn()}o(")");o(":");a=A();return n(s,t.createFunctionTypeAnnotation(e,a,l,i))}function dr(e,l,a){var i=false,r;r=ct(e);return n(e,t.createObjectTypeProperty(a,r,i,l))}function mr(e,r){var l=f();return n(e,t.createObjectTypeCallProperty(ct(l),r))}function pt(y){var p=[],g=[],e,d=false,s=[],v,a,h,u,l;o("{");while(!r("}")){e=f();if(y&&_("static")){u=m();l=true}if(r("[")){g.push(al(e,l))}else if(r("(")||r("<")){p.push(mr(e,y))}else{if(l&&r(":")){a=n(e,t.createIdentifier(u));E(u,i.StrictReservedWord)}else{a=j()}if(r("<")||r("(")){s.push(dr(e,l,a))}else{if(r("?")){m();d=true}o(":");h=A();s.push(n(e,t.createObjectTypeProperty(a,h,d,l)))}}if(r(";")){m()}else if(!r("}")){I(c)}}o("}");return t.createObjectTypeAnnotation(s,g,p)}function yr(){var l=f(),i=null,a=null,e,s=f;e=k();while(r(".")){o(".");e=n(l,t.createQualifiedTypeIdentifier(e,k()))}if(r("<")){a=sn()}return n(l,t.createGenericTypeAnnotation(e,a))}function br(){var e=f();b("void");return n(e,t.createVoidTypeAnnotation())}function wr(){var e,r=f();b("typeof");e=Vn();return n(r,t.createTypeofTypeAnnotation(e))}function Rr(){var a=f(),l=[];o("[");while(e<y&&!r("]")){l.push(A());if(r("]")){break}o(",")}o("]");return n(a,t.createTupleTypeAnnotation(l))}function bn(){var i=f(),e,l=false,a;e=k();if(r("?")){m();l=true}o(":");a=A();return n(i,t.createFunctionTypeParam(e,a,l))}function Pn(){var e={params:[],rest:null};while(c.type===u.Identifier){e.params.push(bn());if(!r(")")){o(",")}}if(r("...")){m();e.rest=bn()}return e}function Vn(){var x=null,s=null,p=null,e=f(),h=null,a,y,l,v,g=false;switch(c.type){case u.Identifier:switch(c.value){case"any":m();return n(e,t.createAnyTypeAnnotation());case"bool":case"boolean":m();return n(e,t.createBooleanTypeAnnotation());case"number":m();return n(e,t.createNumberTypeAnnotation());case"string":m();return n(e,t.createStringTypeAnnotation())}return n(e,yr());case u.Punctuator:switch(c.value){case"{":return n(e,pt());case"[":return Rr();case"<":y=F();o("(");a=Pn();s=a.params;h=a.rest;o(")");o("=>");p=A();return n(e,t.createFunctionTypeAnnotation(s,p,h,y));case"(":m();if(!r(")")&&!r("...")){if(c.type===u.Identifier){l=P();g=l.value!=="?"&&l.value!==":"}else{g=true}}if(g){v=A();o(")");if(r("=>")){d({},i.ConfusedAboutFunctionType)}return v}a=Pn();s=a.params;h=a.rest;o(")");o("=>");p=A();return n(e,t.createFunctionTypeAnnotation(s,p,h,null))}break;case u.Keyword:switch(c.value){case"void":return n(e,br());case"typeof":return n(e,wr())}break;case u.StringLiteral:l=m();if(l.octal){d(l,i.StrictOctalLiteral)}return n(e,t.createStringLiteralTypeAnnotation(l))}I(c)}function Nr(){var l=f(),e=Vn();if(r("[")){o("[");o("]");return n(l,t.createArrayTypeAnnotation(e))}return e}function kn(){var e=f();if(r("?")){m();return n(e,t.createNullableTypeAnnotation(kn()))}return Nr()}function qn(){var a=f(),l,e;l=kn();e=[l];while(r("&")){m();e.push(kn())}return e.length===1?l:n(a,t.createIntersectionTypeAnnotation(e))}function zr(){var a=f(),l,e;l=qn();e=[l];while(r("|")){m();e.push(qn())}return e.length===1?l:n(a,t.createUnionTypeAnnotation(e))}function A(){var n=a.inType,e;a.inType=true;e=zr();a.inType=n;return e}function M(){var r=f(),e;o(":");e=A();return n(r,t.createTypeAnnotation(e))}function k(){var r=f(),e=m();if(e.type!==u.Identifier){I(e)}return n(r,t.createIdentifier(e.value))}function tn(a,i){var t=f(),e=k(),l=false;if(i&&r("?")){o("?");l=true}if(a||r(":")){e.typeAnnotation=M();e=n(t,e)}if(l){e.optional=true;e=n(t,e)}return e}function tl(u){var e,c=f(),l=null,s=f();if(r("{")){e=dn();z(e);if(r(":")){e.typeAnnotation=M();n(s,e)}}else if(r("[")){e=xn();z(e);if(r(":")){e.typeAnnotation=M();n(s,e)}}else{e=a.allowKeyword?W():tn();if(v&&L(e.name)){E({},i.StrictVarName)}}if(u==="const"){if(!r("=")){d({},i.NoUnintializedConst)}o("=");l=R()}else if(r("=")){m();l=R()}return n(c,t.createVariableDeclarator(e,l))}function Rn(t){var n=[];do{n.push(tl(t));if(!r(",")){break}m()}while(e<y);return n}function kt(){var e,r=f();b("var");e=Rn();S();return n(r,t.createVariableDeclaration(e,"var"))}function It(e){var r,l=f();b(e);r=Rn(e);S();return n(l,t.createVariableDeclaration(r,e))}function pn(){var r=f(),e;if(c.type!==u.StringLiteral){d({},i.InvalidModuleSpecifier)}e=t.createModuleSpecifier(c);m();return n(r,e)}function Ct(){var e=f();o("*");return n(e,t.createExportBatchSpecifier())}function At(){var e,r=null,l=f(),a;if(x("default")){m();e=n(l,t.createIdentifier("default"))}else{e=k()}if(_("as")){m();r=W()}return n(l,t.createExportSpecifier(e,r))}function Tt(){var p,g,y,l=null,h,s=null,a=[],e=f();b("export");if(x("default")){m();if(x("function")||x("class")){p=c;m();if(On(c)){g=W();fn(p);return n(e,t.createExportDeclaration(true,H(),[g],null))}fn(p);switch(c.value){case"class":return n(e,t.createExportDeclaration(true,it(),[],null));case"function":return n(e,t.createExportDeclaration(true,Mn(),[],null))}}if(_("from")){d({},i.UnexpectedToken,c.value)}if(r("{")){l=dn()}else if(r("[")){l=xn()}else{l=R()}S();return n(e,t.createExportDeclaration(true,l,[],null))}if(c.type===u.Keyword){switch(c.value){case"let":case"const":case"var":case"class":case"function":return n(e,t.createExportDeclaration(false,H(),a,null))}}if(r("*")){a.push(Ct());if(!_("from")){d({},c.value?i.UnexpectedToken:i.MissingFromClause,c.value)}m();s=pn();S();return n(e,t.createExportDeclaration(false,null,a,s))}o("{");do{h=h||x("default");a.push(At())}while(r(",")&&m());o("}");if(_("from")){m();s=pn();S()}else if(h){d({},c.value?i.UnexpectedToken:i.MissingFromClause,c.value)}else{S()}return n(e,t.createExportDeclaration(false,l,a,s))}function Lt(){var e,r=null,l=f();e=W();if(_("as")){m();r=k()}return n(l,t.createImportSpecifier(e,r))}function Pt(){var e=[];o("{");do{e.push(Lt())}while(r(",")&&m());o("}");return e}function jt(){var e,r=f();e=W();return n(r,t.createImportDefaultSpecifier(e))}function Mt(){var e,r=f();o("*");if(!_("as")){d({},i.NoAsAfterImportNamespace)}m();e=W();return n(r,t.createImportNamespaceSpecifier(e))}function Ot(){var e,l,a=f();b("import");e=[];if(c.type===u.StringLiteral){l=pn();S();return n(a,t.createImportDeclaration(e,l))}if(!x("default")&&On(c)){e.push(jt());if(r(",")){m()}}if(r("*")){e.push(Mt())}else if(r("{")){e=e.concat(Pt())}if(!_("from")){d({},c.value?i.UnexpectedToken:i.MissingFromClause,c.value)}m();l=pn();S();return n(a,t.createImportDeclaration(e,l))}function Dt(){var e=f();o(";");return n(e,t.createEmptyStatement())}function Nt(){var e=f(),r=w();S();return n(e,t.createExpressionStatement(r))}function Ft(){var r,l,e,a=f();b("if");o("(");r=w();o(")");l=B();if(x("else")){m();e=B()}else{e=null}return n(a,t.createIfStatement(r,l,e))}function Bt(){var e,l,i,s=f();b("do");i=a.inIteration;a.inIteration=true;e=B();a.inIteration=i;b("while");o("(");l=w();o(")");if(r(";")){m()}return n(s,t.createDoWhileStatement(e,l))}function Ut(){var e,r,l,i=f();b("while");o("(");e=w();o(")");l=a.inIteration;a.inIteration=true;r=B();a.inIteration=l;return n(i,t.createWhileStatement(e,r))}function Vt(){var e=f(),r=m(),l=Rn();return n(e,t.createVariableDeclaration(l,r.value))}function $n(v){var e,h,g,l,s,p,u,E,y=f();e=h=g=null;b("for");if(_("each")){d({},i.EachNotAllowed)}o("(");if(r(";")){m()}else{if(x("var")||x("let")||x("const")){a.allowIn=false;e=Vt();a.allowIn=true;if(e.declarations.length===1){if(x("in")||_("of")){u=c;if(!((u.value==="in"||e.kind!=="var")&&e.declarations[0].init)){m();l=e;s=w();e=null}}}}else{a.allowIn=false;e=w();a.allowIn=true;if(_("of")){u=m();l=e;s=w();e=null}else if(x("in")){if(!Tr(e)){d({},i.InvalidLHSInForIn)}u=m();l=e;s=w();e=null}}if(typeof l==="undefined"){o(";")}}if(typeof l==="undefined"){if(!r(";")){h=w()}o(";");if(!r(")")){g=w()}}o(")");E=a.inIteration;a.inIteration=true;if(!(v!==undefined&&v.ignoreBody)){p=B()}a.inIteration=E;if(typeof l==="undefined"){return n(y,t.createForStatement(e,h,g,p))}if(u.value==="in"){return n(y,t.createForInStatement(l,s,p))}return n(y,t.createForOfStatement(l,s,p))}function qt(){var r=null,o,l=f();b("continue");if(s.charCodeAt(e)===59){m();if(!a.inIteration){d({},i.IllegalContinue)}return n(l,t.createContinueStatement(null))}if(K()){if(!a.inIteration){d({},i.IllegalContinue)}return n(l,t.createContinueStatement(null))}if(c.type===u.Identifier){r=k();o="$"+r.name;if(!Object.prototype.hasOwnProperty.call(a.labelSet,o)){d({},i.UnknownLabel,r.name)}}S();if(r===null&&!a.inIteration){d({},i.IllegalContinue)}return n(l,t.createContinueStatement(r))}function Jt(){var r=null,o,l=f();b("break");if(s.charCodeAt(e)===59){m();if(!(a.inIteration||a.inSwitch)){d({},i.IllegalBreak)}return n(l,t.createBreakStatement(null))}if(K()){if(!(a.inIteration||a.inSwitch)){d({},i.IllegalBreak)}return n(l,t.createBreakStatement(null))}if(c.type===u.Identifier){r=k();o="$"+r.name;if(!Object.prototype.hasOwnProperty.call(a.labelSet,o)){d({},i.UnknownLabel,r.name)}}S();if(r===null&&!(a.inIteration||a.inSwitch)){d({},i.IllegalBreak)}return n(l,t.createBreakStatement(r))}function Gt(){var l=null,o=f();b("return");if(!a.inFunctionBody){E({},i.IllegalReturn)}if(s.charCodeAt(e)===32){if(q(s.charCodeAt(e+1))){l=w();S();return n(o,t.createReturnStatement(l))}}if(K()){return n(o,t.createReturnStatement(null))}if(!r(";")){if(!r("}")&&c.type!==u.EOF){l=w()}}S();return n(o,t.createReturnStatement(l))}function Wt(){var e,r,l=f();if(v){E({},i.StrictModeWith)}b("with");o("(");e=w();o(")");r=B();return n(l,t.createWithStatement(e,r))}function Ht(){var l,i=[],a,s=f();if(x("default")){m();l=null}else{b("case");l=w()}o(":");while(e<y){if(r("}")||x("default")||x("case")){break}a=H();if(typeof a==="undefined"){break}i.push(a)}return n(s,t.createSwitchCase(l,i))}function zt(){var s,l,u,p,c,h=f();b("switch");o("(");s=w();o(")");o("{");l=[];if(r("}")){m();return n(h,t.createSwitchStatement(s,l))}p=a.inSwitch;a.inSwitch=true;c=false;while(e<y){if(r("}")){break}u=Ht();if(u.test===null){if(c){d({},i.MultipleDefaultsInSwitch)}c=true}l.push(u)}a.inSwitch=p;o("}");return n(h,t.createSwitchStatement(s,l))}function Yt(){var e,r=f();b("throw");if(K()){d({},i.NewlineAfterThrow)}e=w();S();return n(r,t.createThrowStatement(e))}function $t(){var e,a,s=f();b("catch");o("(");if(r(")")){I(c)}e=w();if(v&&e.type===l.Identifier&&L(e.name)){E({},i.StrictCatchVariable)}o(")");a=gn();return n(s,t.createCatchClause(e,a))}function Kt(){var l,e=[],r=null,a=f();b("try");l=gn();if(x("catch")){e.push($t())}if(x("finally")){m();r=gn()}if(e.length===0&&!r){d({},i.NoCatchOrFinally)}return n(a,t.createTryStatement(l,[],e,r))}function Qt(){var e=f();b("debugger");S();return n(e,t.createDebuggerStatement())}function B(){var o=c.type,p,e,h,s;if(o===u.EOF){I(c)}if(o===u.Punctuator){switch(c.value){case";":return Dt();case"{":return gn();case"(":return Nt();default:break}}if(o===u.Keyword){switch(c.value){case"break":return Jt();case"continue":return qt();case"debugger":return Qt();case"do":return Bt();case"for":return $n();case"function":return jn();case"class":return hr();case"if":return Ft();case"return":return Gt();case"switch":return zt();case"throw":return Yt();case"try":return Kt();case"var":return kt();case"while":return Ut();case"with":return Wt();default:break}}if(et()){return jn()}p=f();e=w();if(e.type===l.Identifier&&r(":")){m();s="$"+e.name;if(Object.prototype.hasOwnProperty.call(a.labelSet,s)){d({},i.Redeclaration,"Label",e.name)}a.labelSet[s]=true;h=B();delete a.labelSet[s];return n(p,t.createLabeledStatement(e,h))}S();return n(p,t.createExpressionStatement(e))}function Qn(){if(r("{")){return Tn()}return R()}function Tn(){var p,h=[],d,x,m,g,b,w,_,S,k=f();o("{");while(e<y){if(c.type!==u.StringLiteral){break}d=c;p=H();h.push(p);if(p.expression.type!==l.Literal){break}x=s.slice(d.range[0]+1,d.range[1]-1);if(x==="use strict"){v=true;if(m){E(m,i.StrictOctalLiteral)}}else{if(!m&&d.octal){m=d}}}g=a.labelSet;b=a.inIteration;w=a.inSwitch;_=a.inFunctionBody;S=a.parenthesizedCount;a.labelSet={};a.inIteration=false;a.inSwitch=false;a.inFunctionBody=true;a.parenthesizedCount=0;while(e<y){if(r("}")){break}p=H();if(typeof p==="undefined"){break}h.push(p)}o("}");a.labelSet=g;a.inIteration=b;a.inSwitch=w;a.inFunctionBody=_;a.parenthesizedCount=S;return n(k,t.createBlockStatement(h))}function yn(e,n,t){var r="$"+t;if(v){if(L(t)){e.stricted=n;e.message=i.StrictParamName}if(Object.prototype.hasOwnProperty.call(e.paramSet,r)){e.stricted=n;e.message=i.StrictParamDupe}}else if(!e.firstRestricted){if(L(t)){e.firstRestricted=n;e.message=i.StrictParamName}else if(un(t)){e.firstRestricted=n;e.message=i.StrictReservedWord}else if(Object.prototype.hasOwnProperty.call(e.paramSet,r)){e.firstRestricted=n;e.message=i.StrictParamDupe}}e.paramSet[r]=true}function rr(t){var s,l,a,e,o;l=c;if(l.value==="..."){l=m();a=true}if(r("[")){s=f();e=xn();Y(t,e);if(r(":")){e.typeAnnotation=M();n(s,e)}}else if(r("{")){s=f();if(a){d({},i.ObjectPatternAsRestParameter)}e=dn();Y(t,e);if(r(":")){e.typeAnnotation=M();n(s,e)}}else{e=a?tn(false,false):tn(false,true);yn(t,l,l.value)}if(r("=")){if(a){E(c,i.DefaultRestParameter)}m();o=R();++t.defaultCount}if(a){if(!r(")")){d({},i.ParameterAfterRestParameter)}t.rest=e;return false}t.params.push(e);t.defaults.push(o);return!r(")")}function hn(l){var t,a=f();t={params:[],defaultCount:0,defaults:[],rest:null,firstRestricted:l};o("(");if(!r(")")){t.paramSet={};while(e<y){if(!rr(t)){break}o(",")}}o(")");if(t.defaultCount===0){t.defaults=[]}if(r(":")){t.returnType=M()}return n(a,t)}function jn(){var g,h,l,e,s,o,u,p,y,x,w,S=f(),_;p=false;if(ln()){m();p=true}b("function");u=false;if(r("*")){m();u=true}l=c;g=k();if(r("<")){_=F()}if(v){if(L(l.value)){E(l,i.StrictFunctionName)}}else{if(L(l.value)){s=l;o=i.StrictFunctionName}else if(un(l.value)){s=l;o=i.StrictReservedWord}}e=hn(s);s=e.firstRestricted;if(e.message){o=e.message}y=v;x=a.yieldAllowed;a.yieldAllowed=u;w=a.awaitAllowed;a.awaitAllowed=p;h=Tn();if(v&&s){d(s,o)}if(v&&e.stricted){E(e.stricted,o)}v=y;a.yieldAllowed=x;a.awaitAllowed=w;return n(S,t.createFunctionDeclaration(g,e.params,e.defaults,h,e.rest,u,false,p,e.returnType,_))}function Mn(){var l,h=null,s,o,e,g,u,p,y,x,w,S=f(),_;p=false;if(ln()){m();p=true}b("function");u=false;if(r("*")){m();u=true}if(!r("(")){if(!r("<")){l=c;h=k();if(v){if(L(l.value)){E(l,i.StrictFunctionName)}}else{if(L(l.value)){s=l;o=i.StrictFunctionName}else if(un(l.value)){s=l;o=i.StrictReservedWord}}}if(r("<")){_=F()}}e=hn(s);s=e.firstRestricted;if(e.message){o=e.message}y=v;x=a.yieldAllowed;a.yieldAllowed=u;w=a.awaitAllowed;a.awaitAllowed=p;g=Tn();if(v&&s){d(s,o)}if(v&&e.stricted){E(e.stricted,o)}v=y;a.yieldAllowed=x;a.awaitAllowed=w;return n(S,t.createFunctionExpression(h,e.params,e.defaults,g,e.rest,u,false,p,e.returnType,_))}function sr(){var e,l,a=f();b("yield",!v);e=false;if(r("*")){m();e=true}l=R();return n(a,t.createYieldExpression(l,e))}function or(){var e,r=f();X("await");e=R();return n(r,t.createAwaitExpression(e))}function ur(l,e,y,g,v){var p,m,n,a=false,f,h,u,s,x;n=y?$.static:$.prototype;if(g){return t.createMethodDefinition(n,"",e,en({generator:true}))}u=e.type==="Identifier"&&e.name;if(u==="get"&&!r("(")){e=j();if(l[n].hasOwnProperty(e.name)){a=l[n][e.name].get===undefined&&l[n][e.name].data===undefined&&l[n][e.name].set!==undefined;if(!a){d(e,i.IllegalDuplicateClassProperty)}}else{l[n][e.name]={}}l[n][e.name].get=true;o("(");o(")");if(r(":")){s=M()}return t.createMethodDefinition(n,"get",e,rn({generator:false,returnType:s}))}if(u==="set"&&!r("(")){e=j();if(l[n].hasOwnProperty(e.name)){a=l[n][e.name].set===undefined&&l[n][e.name].data===undefined&&l[n][e.name].get!==undefined;if(!a){d(e,i.IllegalDuplicateClassProperty)}}else{l[n][e.name]={}}l[n][e.name].set=true;o("(");p=c;m=[tn()];o(")");if(r(":")){s=M()}return t.createMethodDefinition(n,"set",e,rn({params:m,generator:false,name:p,returnType:s}))}if(r("<")){h=F()}f=u==="async"&&!r("(");if(f){e=j()}if(l[n].hasOwnProperty(e.name)){d(e,i.IllegalDuplicateClassProperty)}else{l[n][e.name]={}}l[n][e.name].data=true;return t.createMethodDefinition(n,"",e,en({generator:false,async:f,typeParameters:h}))}function cr(a,n,r,l){var e;e=M();o(";");return t.createClassProperty(n,e,r,l)}function fr(i){var e,t=false,l,s=f(),a=false;if(r(";")){m();return}if(c.value==="static"){m();a=true}if(r("*")){m();t=true}e=c.value==="[";l=j();if(!t&&c.value===":"){return n(s,cr(i,l,e,a))}return n(s,ur(i,l,a,t,e))}function lt(){var l,i=[],a={},s=f();a[$.static]={};a[$.prototype]={};o("{");while(e<y){if(r("}")){break}l=fr(a);if(typeof l!=="undefined"){i.push(l)}}o("}");return n(s,t.createClassBody(i))}function at(){var a,i=[],s,l;X("implements");while(e<y){s=f();a=k();if(r("<")){l=sn()}else{l=null}i.push(n(s,t.createClassImplements(a,l)));if(!r(",")){break}o(",")}return i}function it(){var e,l,i,s=null,o,c=f(),u;b("class");if(!x("extends")&&!_("implements")&&!r("{")){e=k()}if(r("<")){u=F()}if(x("extends")){b("extends");i=a.yieldAllowed;a.yieldAllowed=false;s=An();if(r("<")){o=sn()}a.yieldAllowed=i}if(_("implements")){l=at()}return n(c,t.createClassExpression(e,s,lt(),u,o,l))}function hr(){var e,l,i,s=null,o,c=f(),u;b("class");e=k();if(r("<")){u=F()}if(x("extends")){b("extends");i=a.yieldAllowed;a.yieldAllowed=false;s=An();if(r("<")){o=sn()}a.yieldAllowed=i}if(_("implements")){l=at()}return n(c,t.createClassDeclaration(e,s,lt(),u,o,l))}function H(){var e;if(c.type===u.Keyword){switch(c.value){case"const":case"let":return It(c.value);case"function":return jn();default:return B()}}if(_("type")&&P().type===u.Identifier){return Jr()}if(_("interface")&&P().type===u.Identifier){return Hr()}if(_("declare")){e=P();if(e.type===u.Keyword){switch(e.value){case"class":return vt();case"function":return xt();case"var":return bt()}}else if(e.type===u.Identifier&&e.value==="module"){return Kr()}}if(c.type!==u.EOF){return B()}}function ot(){if(c.type===u.Keyword){switch(c.value){case"export":return Tt();case"import":return Ot()}}return H()}function vr(){var n,a=[],t,o,r;while(e<y){t=c;if(t.type!==u.StringLiteral){break}n=ot();a.push(n);if(n.expression.type!==l.Literal){break}o=s.slice(t.range[0]+1,t.range[1]-1);if(o==="use strict"){v=true;if(r){E(r,i.StrictOctalLiteral)}}else{if(!r&&t.octal){r=t}}}while(e<y){n=ot();if(typeof n==="undefined"){break}a.push(n)}return a}function xr(){var e,r=f();v=false;mn();e=vr();return n(r,t.createProgram(e))}function wn(t,r,n,l,i){var e;G(typeof n==="number","Comment must have valid position");if(a.lastCommentStart>=n){return}a.lastCommentStart=n;e={type:t,value:r};if(p.range){e.range=[n,l]}if(p.loc){e.loc=i}p.comments.push(e);if(p.attachComment){p.leadingComments.push(e);p.trailingComments.push(e)}}function Er(){var t,n,r,l,o,a;t="";o=false;a=false;while(e<y){n=s[e];if(a){n=s[e++];if(T(n.charCodeAt(0))){r.end={line:h,column:e-g-1};a=false;wn("Line",t,l,e-1,r);if(n==="\r"&&s[e]==="\n"){++e}++h;g=e;t=""}else if(e>=y){a=false;t+=n;r.end={line:h,column:y-g};wn("Line",t,l,y,r)}else{t+=n}}else if(o){if(T(n.charCodeAt(0))){if(n==="\r"){++e;t+="\r"}if(n!=="\r"||s[e]==="\n"){t+=s[e];++h;++e;g=e;if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}}else{n=s[e++];if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}t+=n;if(n==="*"){n=s[e];if(n==="/"){t=t.substr(0,t.length-1);o=false;++e;r.end={line:h,column:e-g};wn("Block",t,l,e,r);t=""}}}}else if(n==="/"){n=s[e+1];if(n==="/"){r={start:{line:h,column:e-g}};l=e;e+=2;a=true;if(e>=y){r.end={line:h,column:e-g};a=false;wn("Line",t,l,e,r)}}else if(n==="*"){l=e;e+=2;o=true;r={start:{line:h,column:e-g-2}};if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}else{break}}else if(st(n.charCodeAt(0))){++e}else if(T(n.charCodeAt(0))){++e;if(n==="\r"&&s[e]==="\n"){++e}++h;g=e}else{break}}}Nn={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 on(e){if(e.type===l.XJSIdentifier){return e.name}if(e.type===l.XJSNamespacedName){return e.namespace.name+":"+e.name.name}if(e.type===l.XJSMemberExpression){return on(e.object)+"."+on(e.property)}}function _r(e){return e!==92&&q(e)}function Sr(e){return e!==92&&(e===45||an(e))}function kr(){var n,t,r="";t=e;while(e<y){n=s.charCodeAt(e);if(!Sr(n)){break}r+=s[e++]}return{type:u.XJSIdentifier,value:r,lineNumber:h,lineStart:g,range:[t,e]}}function Ir(){var t,n="",l=e,a=0,r;t=s[e];G(t==="&","Entity must start with an ampersand");e++;while(e<y&&a++<10){t=s[e++];if(t===";"){break}n+=t}if(t===";"){if(n[0]==="#"){if(n[1]==="x"){r=+("0"+n.substr(1))}else{r=+n.substr(1).replace(_n.LeadingZeros,"")}if(!isNaN(r)){return String.fromCharCode(r)}}else if(Nn[n]){return Nn[n]}}e=l+1;return"&"}function ft(l){var n,t="",r;r=e;while(e<y){n=s[e];if(l.indexOf(n)!==-1){break}if(n==="&"){t+=Ir()}else{e++;if(n==="\r"&&s[e]==="\n"){t+=n;n=s[e];e++}if(T(n.charCodeAt(0))){++h;g=e}t+=n}}return{type:u.XJSText,value:t,lineNumber:h,lineStart:g,range:[r,e]}}function Cr(){var t,n,r;n=s[e];G(n==="'"||n==='"',"String literal must starts with a quote");r=e;++e;t=ft([n]);if(n!==s[e]){d({},i.UnexpectedToken,"ILLEGAL")}++e;t.range=[r,e];return t}function Ar(){var n=s.charCodeAt(e);if(n!==123&&n!==60){return ft(["<","{"])}return V()}function Q(){var e,r=f();if(c.type!==u.XJSIdentifier){I(c)}e=m();return n(r,t.createXJSIdentifier(e.value))}function dt(){var e,r,l=f();e=Q();o(":");r=Q();return n(l,t.createXJSNamespacedName(e,r))}function Pr(){var l=f(),e=Q();while(r(".")){m();e=n(l,t.createXJSMemberExpression(e,Q()))}return e}function mt(){if(P().value===":"){return dt()}if(P().value==="."){return Pr()}return Q()}function Mr(){if(P().value===":"){return dt()}return Q()}function Or(){var e,a;if(r("{")){e=ht();if(e.expression.type===l.XJSEmptyExpression){d(e,"XJS attributes must only be assigned a non-empty "+"expression")}}else if(r("<")){e=Bn()}else if(c.type===u.XJSText){a=f();e=n(a,t.createLiteral(m()))}else{d({},i.InvalidXJSAttributeValue)}return e}function Dr(){var r=Xn();while(s.charAt(e)!=="}"){e++}return n(r,t.createXJSEmptyExpression())}function ht(){var e,l,i,s=f();l=a.inXJSChild;i=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=false;o("{");if(r("}")){e=Dr()}else{e=w()}a.inXJSChild=l;a.inXJSTag=i;o("}");return n(s,t.createXJSExpressionContainer(e))}function Fr(){var e,r,l,i=f();r=a.inXJSChild;l=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=false;
o("{");o("...");e=R();a.inXJSChild=r;a.inXJSTag=l;o("}");return n(i,t.createXJSSpreadAttribute(e))}function Br(){var e,l;if(r("{")){return Fr()}l=f();e=Mr();if(r("=")){m();return n(l,t.createXJSAttribute(e,Or()))}return n(l,t.createXJSAttribute(e))}function Ur(){var e,l;if(r("{")){e=ht()}else if(c.type===u.XJSText){l=Xn();e=n(l,t.createLiteral(m()))}else{e=Bn()}return e}function Vr(){var e,r,l,i=f();r=a.inXJSChild;l=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=true;o("<");o("/");e=mt();a.inXJSChild=r;a.inXJSTag=l;o(">");return n(i,t.createXJSClosingElement(e))}function Xr(){var r,d,l=[],i=false,s,u,p=f();s=a.inXJSChild;u=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=true;o("<");r=mt();while(e<y&&c.value!=="/"&&c.value!==">"){l.push(Br())}a.inXJSTag=u;if(c.value==="/"){o("/");a.inXJSChild=s;o(">");i=true}else{a.inXJSChild=true;o(">")}return n(p,t.createXJSOpeningElement(r,l,i))}function Bn(){var l,s=null,u=[],o,p,m=f();o=a.inXJSChild;p=a.inXJSTag;l=Xr();if(!l.selfClosing){while(e<y){a.inXJSChild=false;if(c.value==="<"&&P().value==="/"){break}a.inXJSChild=true;u.push(Ur())}a.inXJSChild=o;a.inXJSTag=p;s=Vr();if(on(s.name)!==on(l.name)){d({},i.ExpectedXJSClosingTag,on(l.name))}}if(!o&&r("<")){d(c,i.AdjacentXJSElements)}return n(m,t.createXJSElement(l,s,u))}function Jr(){var e,i=f(),l=null,a;X("type");e=k();if(r("<")){l=F()}o("=");a=A();S();return n(i,t.createTypeAlias(e,l,a))}function Gr(){var a=f(),e,l=null;e=k();if(r("<")){l=sn()}return n(a,t.createInterfaceExtends(e,l))}function yt(c,p){var l,a,i=[],s,u=null;s=k();if(r("<")){u=F()}if(x("extends")){b("extends");while(e<y){i.push(Gr());if(!r(",")){break}o(",")}}a=f();l=n(a,pt(p));return n(c,t.createInterface(s,u,l,i))}function Hr(){var n,t,r=[],l,e=f(),a=null;X("interface");return yt(e,false)}function vt(){var n=f(),e;X("declare");b("class");e=yt(n,true);e.type=l.DeclareClass;return e}function xt(){var e,i,m=f(),s,u,c,l,p=null,d,a;X("declare");b("function");i=f();e=k();a=f();if(r("<")){p=F()}o("(");l=Pn();s=l.params;c=l.rest;o(")");o(":");u=A();d=n(a,t.createFunctionTypeAnnotation(s,u,c,p));e.typeAnnotation=n(a,t.createTypeAnnotation(d));n(i,e);S();return n(m,t.createDeclareFunction(e))}function bt(){var e,r=f();X("declare");b("var");e=tn();S();return n(r,t.createDeclareVariable(e))}function Kr(){var l=[],s,a,p,h=f(),d;X("declare");X("module");if(c.type===u.StringLiteral){if(v&&c.octal){E(c,i.StrictOctalLiteral)}p=f();a=n(p,t.createLiteral(m()))}else{a=k()}s=f();o("{");while(e<y&&!r("}")){d=P();switch(d.value){case"class":l.push(vt());break;case"function":l.push(xt());break;case"var":l.push(bt());break;default:I(c)}}o("}");return n(h,t.createDeclareModule(a,n(s,t.createBlockStatement(l))))}function Qr(){var o,t,n,l,i,r;if(!a.inXJSChild){O()}o=e;t={start:{line:h,column:e-g}};n=p.advance();t.end={line:h,column:e-g};if(n.type!==u.EOF){l=[n.range[0],n.range[1]];i=s.slice(n.range[0],n.range[1]);r={type:C[n.type],value:i,range:l,loc:t};if(n.regex){r.regex={pattern:n.regex.pattern,flags:n.regex.flags}}p.tokens.push(r)}return n}function Zr(){var r,l,t,n;O();r=e;l={start:{line:h,column:e-g}};t=p.scanRegExp();l.end={line:h,column:e-g};if(!p.tokenize){if(p.tokens.length>0){n=p.tokens[p.tokens.length-1];if(n.range[0]===r&&n.type==="Punctuator"){if(n.value==="/"||n.value==="/="){p.tokens.pop()}}}p.tokens.push({type:"RegularExpression",value:t.literal,regex:t.regex,range:[r,e],loc:l})}return t}function Et(){var t,e,n,r=[];for(t=0;t<p.tokens.length;++t){e=p.tokens[t];n={type:e.type,value:e.value};if(e.regex){n.regex={pattern:e.regex.pattern,flags:e.regex.flags}}if(p.range){n.range=e.range}if(p.loc){n.loc=e.loc}r.push(n)}p.tokens=r}function wt(){if(p.comments){p.skipComment=O;O=Er}if(typeof p.tokens!=="undefined"){p.advance=nn;p.scanRegExp=N;nn=Qr;N=Zr}}function Kn(){if(typeof p.skipComment==="function"){O=p.skipComment}if(typeof p.scanRegExp==="function"){nn=p.advance;N=p.scanRegExp}}function rl(n,t){var e,r={};for(e in n){if(n.hasOwnProperty(e)){r[e]=n[e]}}for(e in t){if(t.hasOwnProperty(e)){r[e]=t[e]}}return r}function ll(r,n){var o,i,l;o=String;if(typeof r!=="string"&&!(r instanceof String)){r=o(r)}t=Fn;s=r;e=0;h=s.length>0?1:0;g=0;y=s.length;c=null;a={allowKeyword:true,allowIn:true,labelSet:{},inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1};p={};n=n||{};n.tokens=true;p.tokens=[];p.tokenize=true;p.openParenToken=-1;p.openCurlyToken=-1;p.range=typeof n.range==="boolean"&&n.range;p.loc=typeof n.loc==="boolean"&&n.loc;if(typeof n.comment==="boolean"&&n.comment){p.comments=[]}if(typeof n.tolerant==="boolean"&&n.tolerant){p.errors=[]}if(y>0){if(typeof s[0]==="undefined"){if(r instanceof String){s=r.valueOf()}}}wt();try{mn();if(c.type===u.EOF){return p.tokens}i=m();while(c.type!==u.EOF){try{i=m()}catch(f){i=c;if(p.errors){p.errors.push(f);break}else{throw f}}}Et();l=p.tokens;if(typeof p.comments!=="undefined"){l.comments=p.comments}if(typeof p.errors!=="undefined"){l.errors=p.errors}}catch(d){throw d}finally{Kn();p={}}return l}function Rt(r,n){var l,i;i=String;if(typeof r!=="string"&&!(r instanceof String)){r=i(r)}t=Fn;s=r;e=0;h=s.length>0?1:0;g=0;y=s.length;c=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 n!=="undefined"){p.range=typeof n.range==="boolean"&&n.range;p.loc=typeof n.loc==="boolean"&&n.loc;p.attachComment=typeof n.attachComment==="boolean"&&n.attachComment;if(p.loc&&n.source!==null&&n.source!==undefined){t=rl(t,{postProcess:function(e){e.loc.source=i(n.source);return e}})}if(typeof n.tokens==="boolean"&&n.tokens){p.tokens=[]}if(typeof n.comment==="boolean"&&n.comment){p.comments=[]}if(typeof n.tolerant==="boolean"&&n.tolerant){p.errors=[]}if(p.attachComment){p.range=true;p.comments=[];p.bottomRightStack=[];p.trailingComments=[];p.leadingComments=[]}}if(y>0){if(typeof s[0]==="undefined"){if(r instanceof String){s=r.valueOf()}}}wt();try{l=xr();if(typeof p.comments!=="undefined"){l.comments=p.comments}if(typeof p.tokens!=="undefined"){Et();l.tokens=p.tokens}if(typeof p.errors!=="undefined"){l.errors=p.errors}}catch(o){throw o}finally{Kn();p={}}return l}En.version="8001.1001.0-dev-harmony-fb";En.tokenize=ll;En.parse=Rt;En.Syntax=function(){var e,n={};if(typeof Object.create==="function"){n=Object.create(null)}for(e in l){if(l.hasOwnProperty(e)){n[e]=l[e]}}if(typeof Object.freeze==="function"){Object.freeze(n)}return n}()})},{}],162:[function(t,e,r){var n=function(){"use strict";function e(n,t){var e=Array.prototype.slice.call(arguments,1);return n.replace(/\{(\d+)\}/g,function(t,n){return n in e?e[n]:t})}function n(n,e){return n.replace(/\{([_$a-zA-Z0-9][_$a-zA-Z0-9]*)\}/g,function(t,n){return n in e?e[n]:t})}function t(e,n){return new Array(n+1).join(e)}e.fmt=e;e.obj=n;e.repeat=t;return e}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=n}},{}],163:[function(t,e,r){var n=function(){"use strict";var e=Object.prototype.hasOwnProperty;var n=Object.prototype.toString;var t=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 n=typeof e;return e===null||e===t||n==="boolean"||n==="number"||n==="string"},array:Array.isArray||function(e){return n.call(e)==="[object Array]"},finitenumber:function(e){return typeof e==="number"&&isFinite(e)},someof:function(e,n){return n.indexOf(e)>=0},noneof:function(e,n){return n.indexOf(e)===-1},own:function(n,t){return e.call(n,t)}}}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=n}},{}],164:[function(t,e,r){var n=function(){"use strict";var n=Object.prototype.hasOwnProperty;var t=function(){function r(e){for(var t in e){if(n.call(e,t)){return true}}return false}function l(e){return n.call(e,"__count__")||n.call(e,"__parent__")}var e=false;if(typeof Object.create==="function"){if(!r(Object.create(null))){e=true}}if(e===false){if(r({})){throw new Error("StringMap environment error 0, please file a bug at https://github.com/olov/stringmap/issues")}}var t=e?Object.create(null):{};var a=false;if(l(t)){t.__proto__=null;if(r(t)||l(t)){throw new Error("StringMap environment error 1, please file a bug at https://github.com/olov/stringmap/issues")}a=true}return function(){var n=e?Object.create(null):{};if(a){n.__proto__=null}return n}}();function e(n){if(!(this instanceof e)){return new e(n)}this.obj=t();this.hasProto=false;this.proto=undefined;if(n){this.setMany(n)}}e.prototype.has=function(e){if(typeof e!=="string"){throw new Error("StringMap expected string key")}return e==="__proto__"?this.hasProto:n.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:n.call(this.obj,e)?this.obj[e]:undefined};e.prototype.set=function(e,n){if(typeof e!=="string"){throw new Error("StringMap expected string key")}if(e==="__proto__"){this.hasProto=true;this.proto=n}else{this.obj[e]=n}};e.prototype.remove=function(e){if(typeof e!=="string"){throw new Error("StringMap expected string key")}var n=this.has(e);if(e==="__proto__"){this.hasProto=false;this.proto=undefined}else{delete this.obj[e]}return n};e.prototype["delete"]=e.prototype.remove;e.prototype.isEmpty=function(){for(var e in this.obj){if(n.call(this.obj,e)){return false}}return!this.hasProto};e.prototype.size=function(){var e=0;for(var t in this.obj){if(n.call(this.obj,t)){++e}}return this.hasProto?e+1:e};e.prototype.keys=function(){var e=[];for(var t in this.obj){if(n.call(this.obj,t)){e.push(t)}}if(this.hasProto){e.push("__proto__")}return e};e.prototype.values=function(){var e=[];for(var t in this.obj){if(n.call(this.obj,t)){e.push(this.obj[t])}}if(this.hasProto){e.push(this.proto)}return e};e.prototype.items=function(){var e=[];for(var t in this.obj){if(n.call(this.obj,t)){e.push([t,this.obj[t]])}}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 t in e){if(n.call(e,t)){this.set(t,e[t])}}return this};e.prototype.merge=function(n){var t=n.keys();for(var e=0;e<t.length;e++){var r=t[e];this.set(r,n.get(r))}return this};e.prototype.map=function(r){var e=this.keys();for(var n=0;n<e.length;n++){var t=e[n];e[n]=r(this.get(t),t)}return e};e.prototype.forEach=function(r){var n=this.keys();for(var e=0;e<n.length;e++){var t=n[e];r(this.get(t),t)}};e.prototype.clone=function(){var n=e();return n.merge(this)};e.prototype.toString=function(){var e=this;return"{"+this.keys().map(function(n){return JSON.stringify(n)+":"+JSON.stringify(e.get(n))}).join(",")+"}"};return e}();if(typeof e!=="undefined"&&typeof e.exports!=="undefined"){e.exports=n}},{}],165:[function(t,e,r){var n=function(){"use strict";var n=Object.prototype.hasOwnProperty;var t=function(){function r(e){for(var t in e){if(n.call(e,t)){return true}}return false}function l(e){return n.call(e,"__count__")||n.call(e,"__parent__")}var e=false;if(typeof Object.create==="function"){if(!r(Object.create(null))){e=true}}if(e===false){if(r({})){throw new Error("StringSet environment error 0, please file a bug at https://github.com/olov/stringset/issues")}}var t=e?Object.create(null):{};var a=false;if(l(t)){t.__proto__=null;if(r(t)||l(t)){throw new Error("StringSet environment error 1, please file a bug at https://github.com/olov/stringset/issues")}a=true}return function(){var n=e?Object.create(null):{};if(a){n.__proto__=null}return n}}();function e(n){if(!(this instanceof e)){return new e(n)}this.obj=t();this.hasProto=false;if(n){this.addMany(n)}}e.prototype.has=function(e){if(typeof e!=="string"){throw new Error("StringSet expected string item")}return e==="__proto__"?this.hasProto:n.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 n=this.has(e);if(e==="__proto__"){this.hasProto=false}else{delete this.obj[e]}return n};e.prototype["delete"]=e.prototype.remove;e.prototype.isEmpty=function(){for(var e in this.obj){if(n.call(this.obj,e)){return false}}return!this.hasProto};e.prototype.size=function(){var e=0;for(var t in this.obj){if(n.call(this.obj,t)){++e}}return this.hasProto?e+1:e};e.prototype.items=function(){var e=[];for(var t in this.obj){if(n.call(this.obj,t)){e.push(t)}}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 n=0;n<e.length;n++){this.add(e[n])}return this};e.prototype.merge=function(e){this.addMany(e.items());return this};e.prototype.clone=function(){var n=e();return n.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=n}},{}],166:[function(n,t,e){(function(t,n){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],n)}else if(typeof e!=="undefined"){n(e)}else{n(t.esprima={})}})(this,function(En){"use strict";var o,A,bt,r,G,i,wn,kn,Rn,tn,s,v,e,h,g,y,l,c,a,f;o={BooleanLiteral:1,EOF:2,Identifier:3,Keyword:4,NullLiteral:5,NumericLiteral:6,Punctuator:7,StringLiteral:8,RegularExpression:9,Template:10,XJSIdentifier:11,XJSText:12};A={};A[o.BooleanLiteral]="Boolean";A[o.EOF]="<end>";A[o.Identifier]="Identifier";A[o.Keyword]="Keyword";A[o.NullLiteral]="Null";A[o.NumericLiteral]="Numeric";A[o.Punctuator]="Punctuator";A[o.StringLiteral]="String";A[o.XJSIdentifier]="XJSIdentifier";A[o.XJSText]="XJSText";A[o.RegularExpression]="RegularExpression";bt=["(","{","[","in","typeof","instanceof","new","return","case","delete","throw","void","=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","&=","|=","^=",",","+","-","*","/","%","++","--","<<",">>",">>>","&","|","^","!","~","&&","||","?",":","===","==",">=","<=","<",">","!=","!=="];r={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};tn={"static":"static",prototype:"prototype"};i={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",IllegalImportDeclaration:"Illegal import declaration",IllegalExportDeclaration:"Illegal export declaration",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"};wn={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,n){if(!e){throw new Error("ASSERT: "+n)}}function O(){this.$data={}}O.prototype.get=function(e){e="$"+e;return this.$data[e]};O.prototype.set=function(e,n){e="$"+e;this.$data[e]=n;return this};O.prototype.has=function(e){e="$"+e;return Object.prototype.hasOwnProperty.call(this.$data,e)};O.prototype["delete"]=function(e){e="$"+e;return delete this.$data[e]};function B(e){return e>=48&&e<=57}function Un(e){return"0123456789abcdefABCDEF".indexOf(e)>=0}function X(e){return"01234567".indexOf(e)>=0}function gt(e){return e===32||e===9||e===11||e===12||e===160||e>=5760&&" ".indexOf(String.fromCharCode(e))>0}function T(e){return e===10||e===13||e===8232||e===8233}function W(e){return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e===92||e>=128&&wn.NonAsciiIdentifierStart.test(String.fromCharCode(e))}function an(e){return e===36||e===95||e>=65&&e<=90||e>=97&&e<=122||e>=48&&e<=57||e===92||e>=128&&wn.NonAsciiIdentifierPart.test(String.fromCharCode(e))}function jr(e){switch(e){case"class":case"enum":case"export":case"extends":case"import":case"super":return true;default:return false}}function ln(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 L(e){return e==="eval"||e==="arguments"}function Kr(e){if(v&&ln(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 N(){var n,t,r;t=false;r=false;while(e<y){n=s.charCodeAt(e);if(r){++e;if(T(n)){r=false;if(n===13&&s.charCodeAt(e)===10){++e}++h;g=e}}else if(t){if(T(n)){if(n===13){++e}if(n!==13||s.charCodeAt(e)===10){++h;++e;g=e;if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}}else{n=s.charCodeAt(e++);if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}if(n===42){n=s.charCodeAt(e);if(n===47){++e;t=false}}}}else if(n===47){n=s.charCodeAt(e+1);if(n===47){e+=2;r=true}else if(n===42){e+=2;t=true;if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}else{break}}else if(gt(n)){++e}else if(T(n)){++e;if(n===13&&s.charCodeAt(e)===10){++e}++h;g=e}else{break}}}function pn(a){var n,r,l,t=0;r=a==="u"?4:2;for(n=0;n<r;++n){if(e<y&&Un(s[e])){l=s[e++];t=t*16+"0123456789abcdef".indexOf(l.toLowerCase())}else{return""}}return String.fromCharCode(t)}function mt(){var t,n,r,l;t=s[e];n=0;if(t==="}"){d({},i.UnexpectedToken,"ILLEGAL")}while(e<y){t=s[e++];if(!Un(t)){break}n=n*16+"0123456789abcdef".indexOf(t.toLowerCase())}if(n>1114111||t!=="}"){d({},i.UnexpectedToken,"ILLEGAL")}if(n<=65535){return String.fromCharCode(n)}r=(n-65536>>10)+55296;l=(n-65536&1023)+56320;return String.fromCharCode(r,l)}function dt(){var n,t;n=s.charCodeAt(e++);t=String.fromCharCode(n);if(n===92){if(s.charCodeAt(e)!==117){d({},i.UnexpectedToken,"ILLEGAL")}++e;n=pn("u");if(!n||n==="\\"||!W(n.charCodeAt(0))){d({},i.UnexpectedToken,"ILLEGAL")}t=n}while(e<y){n=s.charCodeAt(e);if(!an(n)){break}++e;t+=String.fromCharCode(n);if(n===92){t=t.substr(0,t.length-1);if(s.charCodeAt(e)!==117){d({},i.UnexpectedToken,"ILLEGAL")}++e;n=pn("u");if(!n||n==="\\"||!an(n.charCodeAt(0))){d({},i.UnexpectedToken,"ILLEGAL")}t+=n}}return t}function sr(){var n,t;n=e++;while(e<y){t=s.charCodeAt(e);if(t===92){e=n;return dt()}if(an(t)){++e}else{break}}return s.slice(n,e)}function gr(){var r,n,t;r=e;n=s.charCodeAt(e)===92?dt():sr();if(n.length===1){t=o.Identifier}else if(Kr(n)){t=o.Keyword}else if(n==="null"){t=o.NullLiteral}else if(n==="true"||n==="false"){t=o.BooleanLiteral}else{t=o.Identifier}return{type:t,value:n,lineNumber:h,lineStart:g,range:[r,e]}}function U(){var n=e,l=s.charCodeAt(e),c,t=s[e],r,u,p;switch(l){case 40:case 41:case 59:case 44:case 123:case 125:case 91:case 93:case 58:case 63:case 126:++e;if(f.tokenize){if(l===40){f.openParenToken=f.tokens.length}else if(l===123){f.openCurlyToken=f.tokens.length}}return{type:o.Punctuator,value:String.fromCharCode(l),lineNumber:h,lineStart:g,range:[n,e]};default:c=s.charCodeAt(e+1);if(c===61){switch(l){case 37:case 38:case 42:case 43:case 45:case 47:case 60:case 62:case 94:case 124:e+=2;return{type:o.Punctuator,value:String.fromCharCode(l)+String.fromCharCode(c),lineNumber:h,lineStart:g,range:[n,e]};case 33:case 61:e+=2;if(s.charCodeAt(e)===61){++e}return{type:o.Punctuator,value:s.slice(n,e),lineNumber:h,lineStart:g,range:[n,e]};default:break}}break}r=s[e+1];u=s[e+2];p=s[e+3];if(t===">"&&r===">"&&u===">"){if(p==="="){e+=4;return{type:o.Punctuator,value:">>>=",lineNumber:h,lineStart:g,range:[n,e]}}}if(t===">"&&r===">"&&u===">"){e+=3;return{type:o.Punctuator,value:">>>",lineNumber:h,lineStart:g,range:[n,e]}}if(t==="<"&&r==="<"&&u==="="){e+=3;return{type:o.Punctuator,value:"<<=",lineNumber:h,lineStart:g,range:[n,e]}}if(t===">"&&r===">"&&u==="="){e+=3;return{type:o.Punctuator,value:">>=",lineNumber:h,lineStart:g,range:[n,e]}}if(t==="."&&r==="."&&u==="."){e+=3;return{type:o.Punctuator,value:"...",lineNumber:h,lineStart:g,range:[n,e]}}if(t===r&&"+-<>&|".indexOf(t)>=0&&!a.inType){e+=2;return{type:o.Punctuator,value:t+r,lineNumber:h,lineStart:g,range:[n,e]}}if(t==="="&&r===">"){e+=2;return{type:o.Punctuator,value:"=>",lineNumber:h,lineStart:g,range:[n,e]}}if("<>=!+-*%&|^/".indexOf(t)>=0){++e;return{type:o.Punctuator,value:t,lineNumber:h,lineStart:g,range:[n,e]}}if(t==="."){++e;return{type:o.Punctuator,value:t,lineNumber:h,lineStart:g,range:[n,e]}}d({},i.UnexpectedToken,"ILLEGAL")}function Ur(t){var n="";while(e<y){if(!Un(s[e])){break}n+=s[e++]}if(n.length===0){d({},i.UnexpectedToken,"ILLEGAL")}if(W(s.charCodeAt(e))){d({},i.UnexpectedToken,"ILLEGAL")}return{type:o.NumericLiteral,value:parseInt("0x"+n,16),lineNumber:h,lineStart:g,range:[t,e]}}function Yr(r,l){var n,t;if(X(r)){t=true;n="0"+s[e++]}else{t=false;++e;n=""}while(e<y){if(!X(s[e])){break}n+=s[e++]}if(!t&&n.length===0){d({},i.UnexpectedToken,"ILLEGAL")}if(W(s.charCodeAt(e))||B(s.charCodeAt(e))){d({},i.UnexpectedToken,"ILLEGAL")}return{type:o.NumericLiteral,value:parseInt(n,8),octal:t,lineNumber:h,lineStart:g,range:[l,e]}}function ft(){var t,r,n,l;n=s[e];J(B(n.charCodeAt(0))||n===".","Numeric literal must start with a decimal digit or a decimal point");r=e;t="";if(n!=="."){t=s[e++];n=s[e];if(t==="0"){if(n==="x"||n==="X"){++e;return Ur(r)}if(n==="b"||n==="B"){++e;t="";while(e<y){n=s[e];if(n!=="0"&&n!=="1"){break}t+=s[e++]}if(t.length===0){d({},i.UnexpectedToken,"ILLEGAL")}if(e<y){n=s.charCodeAt(e);if(W(n)||B(n)){d({},i.UnexpectedToken,"ILLEGAL")}}return{type:o.NumericLiteral,value:parseInt(t,2),lineNumber:h,lineStart:g,range:[r,e]}}if(n==="o"||n==="O"||X(n)){return Yr(n,r)}if(n&&B(n.charCodeAt(0))){d({},i.UnexpectedToken,"ILLEGAL")}}while(B(s.charCodeAt(e))){t+=s[e++]}n=s[e]}if(n==="."){t+=s[e++];while(B(s.charCodeAt(e))){t+=s[e++]}n=s[e]}if(n==="e"||n==="E"){t+=s[e++];n=s[e];if(n==="+"||n==="-"){t+=s[e++]}if(B(s.charCodeAt(e))){while(B(s.charCodeAt(e))){t+=s[e++]}}else{d({},i.UnexpectedToken,"ILLEGAL")}}if(W(s.charCodeAt(e))){d({},i.UnexpectedToken,"ILLEGAL")}return{type:o.NumericLiteral,value:parseFloat(t),lineNumber:h,lineStart:g,range:[r,e]}}function Pt(){var t="",l,c,n,r,a,f,u=false;l=s[e];J(l==="'"||l==='"',"String literal must starts with a quote");c=e;++e;while(e<y){n=s[e++];if(n===l){l="";break}else if(n==="\\"){n=s[e++];if(!n||!T(n.charCodeAt(0))){switch(n){case"n":t+="\n";
break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":case"x":if(s[e]==="{"){++e;t+=mt()}else{f=e;a=pn(n);if(a){t+=a}else{e=f;t+=n}}break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="";break;default:if(X(n)){r="01234567".indexOf(n);if(r!==0){u=true}if(e<y&&X(s[e])){u=true;r=r*8+"01234567".indexOf(s[e++]);if("0123".indexOf(n)>=0&&e<y&&X(s[e])){r=r*8+"01234567".indexOf(s[e++])}}t+=String.fromCharCode(r)}else{t+=n}break}}else{++h;if(n==="\r"&&s[e]==="\n"){++e}g=e}}else if(T(n.charCodeAt(0))){break}else{t+=n}}if(l!==""){d({},i.UnexpectedToken,"ILLEGAL")}return{type:o.StringLiteral,value:t,octal:u,lineNumber:h,lineStart:g,range:[c,e]}}function st(){var t="",n,u,l,a,p,c,r,f;l=false;a=false;u=e;++e;while(e<y){n=s[e++];if(n==="`"){a=true;l=true;break}else if(n==="$"){if(s[e]==="{"){++e;l=true;break}t+=n}else if(n==="\\"){n=s[e++];if(!T(n.charCodeAt(0))){switch(n){case"n":t+="\n";break;case"r":t+="\r";break;case"t":t+=" ";break;case"u":case"x":if(s[e]==="{"){++e;t+=mt()}else{p=e;c=pn(n);if(c){t+=c}else{e=p;t+=n}}break;case"b":t+="\b";break;case"f":t+="\f";break;case"v":t+="";break;default:if(X(n)){r="01234567".indexOf(n);if(r!==0){f=true}if(e<y&&X(s[e])){f=true;r=r*8+"01234567".indexOf(s[e++]);if("0123".indexOf(n)>=0&&e<y&&X(s[e])){r=r*8+"01234567".indexOf(s[e++])}}t+=String.fromCharCode(r)}else{t+=n}break}}else{++h;if(n==="\r"&&s[e]==="\n"){++e}g=e}}else if(T(n.charCodeAt(0))){++h;if(n==="\r"&&s[e]==="\n"){++e}g=e;t+="\n"}else{t+=n}}if(!l){d({},i.UnexpectedToken,"ILLEGAL")}return{type:o.Template,value:{cooked:t,raw:s.slice(u+1,e-(a?1:2))},tail:a,octal:f,lineNumber:h,lineStart:g,range:[u,e]}}function Jt(r){var n,t;c=null;N();n=r.head?"`":"}";if(s[e]!==n){d({},i.UnexpectedToken,"ILLEGAL")}t=st();mn();return t}function F(){var t,n,v,l,r,a,m=false,u,x=false,p;c=null;N();v=e;n=s[e];J(n==="/","Regular expression literal must start with a slash");t=s[e++];while(e<y){n=s[e++];t+=n;if(m){if(n==="]"){m=false}}else{if(n==="\\"){n=s[e++];if(T(n.charCodeAt(0))){d({},i.UnterminatedRegExp)}t+=n}else if(n==="/"){x=true;break}else if(n==="["){m=true}else if(T(n.charCodeAt(0))){d({},i.UnterminatedRegExp)}}}if(!x){d({},i.UnterminatedRegExp)}l=t.substr(1,t.length-2);r="";while(e<y){n=s[e];if(!an(n.charCodeAt(0))){break}++e;if(n==="\\"&&e<y){n=s[e];if(n==="u"){++e;u=e;n=pn("u");if(n){r+=n;for(t+="\\u";u<e;++u){t+=s[u]}}else{e=u;r+="u";t+="\\u"}E({},i.UnexpectedToken,"ILLEGAL")}else{t+="\\"}}else{r+=n;t+=n}}p=l;if(r.indexOf("u")>=0){p=p.replace(/\\u\{([0-9a-fA-F]+)\}/g,function(n,e){if(parseInt(e,16)<=1114111){return"x"}d({},i.InvalidRegExp)}).replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}try{a=new RegExp(p)}catch(b){d({},i.InvalidRegExp)}try{a=new RegExp(l,r)}catch(w){a=null}if(f.tokenize){return{type:o.RegularExpression,value:a,regex:{pattern:l,flags:r},lineNumber:h,lineStart:g,range:[v,e]}}return{literal:t,value:a,regex:{pattern:l,flags:r},range:[v,e]}}function Dn(e){return e.type===o.Identifier||e.type===o.Keyword||e.type===o.BooleanLiteral||e.type===o.NullLiteral}function kr(){var n,e;n=f.tokens[f.tokens.length-1];if(!n){return F()}if(n.type==="Punctuator"){if(n.value===")"){e=f.tokens[f.openParenToken-1];if(e&&e.type==="Keyword"&&(e.value==="if"||e.value==="while"||e.value==="for"||e.value==="with")){return F()}return U()}if(n.value==="}"){if(f.tokens[f.openCurlyToken-3]&&f.tokens[f.openCurlyToken-3].type==="Keyword"){e=f.tokens[f.openCurlyToken-4];if(!e){return U()}}else if(f.tokens[f.openCurlyToken-4]&&f.tokens[f.openCurlyToken-4].type==="Keyword"){e=f.tokens[f.openCurlyToken-5];if(!e){return F()}}else{return U()}if(bt.indexOf(e.value)>=0){return U()}return F()}return F()}if(n.type==="Keyword"){return F()}return U()}function en(){var n;if(!a.inXJSChild){N()}if(e>=y){return{type:o.EOF,lineNumber:h,lineStart:g,range:[e,e]}}if(a.inXJSChild){return Pr()}n=s.charCodeAt(e);if(n===40||n===41||n===58){return U()}if(n===39||n===34){if(a.inXJSTag){return Lr()}return Pt()}if(a.inXJSTag&&Ir(n)){return Cr()}if(n===96){return st()}if(W(n)){return gr()}if(n===46){if(B(s.charCodeAt(e+1))){return ft()}return U()}if(B(n)){return ft()}if(f.tokenize&&n===47){return kr()}return U()}function m(){var n;n=c;e=n.range[1];h=n.lineNumber;g=n.lineStart;c=en();e=n.range[1];h=n.lineNumber;g=n.lineStart;return n}function mn(){var n,t,r;n=e;t=h;r=g;c=en();e=n;h=t;g=r}function P(){var n,t,r,l,a;n=typeof f.advance==="function"?f.advance:en;t=e;r=h;l=g;if(c===null){c=n()}e=c.range[1];h=c.lineNumber;g=c.lineStart;a=n();e=t;h=r;g=l;return a}function dn(n){e=n.range[0];h=n.lineNumber;g=n.lineStart;c=n}function p(){if(!f.loc&&!f.range){return undefined}N();return{offset:e,line:h,col:e-g}}function it(){if(!f.loc&&!f.range){return undefined}return{offset:e,line:h,col:e-g}}function rr(e){var t,l,a=f.bottomRightStack,n=a[a.length-1];if(e.type===r.Program){if(e.body.length>0){return}}if(f.trailingComments.length>0){if(f.trailingComments[0].range[0]>=e.range[1]){l=f.trailingComments;f.trailingComments=[]}else{f.trailingComments.length=0}}else{if(n&&n.trailingComments&&n.trailingComments[0].range[0]>=e.range[1]){l=n.trailingComments;delete n.trailingComments}}if(n){while(n&&n.range[0]>=e.range[0]){t=n;n=a.pop()}}if(t){if(t.leadingComments&&t.leadingComments[t.leadingComments.length-1].range[1]<=e.range[0]){e.leadingComments=t.leadingComments;delete t.leadingComments}}else if(f.leadingComments.length>0&&f.leadingComments[f.leadingComments.length-1].range[1]<=e.range[0]){e.leadingComments=f.leadingComments;f.leadingComments=[]}if(l){e.trailingComments=l}a.push(e)}function t(t,n){if(f.range){n.range=[t.offset,e]}if(f.loc){n.loc={start:{line:t.line,column:t.col},end:{line:h,column:e-g}};n=l.postProcess(n)}if(f.attachComment){rr(n)}return n}kn={name:"SyntaxTree",postProcess:function(e){return e},createArrayExpression:function(e){return{type:r.ArrayExpression,elements:e}},createAssignmentExpression:function(e,n,t){return{type:r.AssignmentExpression,operator:e,left:n,right:t}},createBinaryExpression:function(e,n,t){var l=e==="||"||e==="&&"?r.LogicalExpression:r.BinaryExpression;return{type:l,operator:e,left:n,right:t}},createBlockStatement:function(e){return{type:r.BlockStatement,body:e}},createBreakStatement:function(e){return{type:r.BreakStatement,label:e}},createCallExpression:function(e,n){return{type:r.CallExpression,callee:e,arguments:n}},createCatchClause:function(e,n){return{type:r.CatchClause,param:e,body:n}},createConditionalExpression:function(e,n,t){return{type:r.ConditionalExpression,test:e,consequent:n,alternate:t}},createContinueStatement:function(e){return{type:r.ContinueStatement,label:e}},createDebuggerStatement:function(){return{type:r.DebuggerStatement}},createDoWhileStatement:function(e,n){return{type:r.DoWhileStatement,body:e,test:n}},createEmptyStatement:function(){return{type:r.EmptyStatement}},createExpressionStatement:function(e){return{type:r.ExpressionStatement,expression:e}},createForStatement:function(e,n,t,l){return{type:r.ForStatement,init:e,test:n,update:t,body:l}},createForInStatement:function(e,n,t){return{type:r.ForInStatement,left:e,right:n,body:t,each:false}},createForOfStatement:function(e,n,t){return{type:r.ForOfStatement,left:e,right:n,body:t}},createFunctionDeclaration:function(n,i,t,l,a,f,s,o,u,c){var e={type:r.FunctionDeclaration,id:n,params:i,defaults:t,body:l,rest:a,generator:f,expression:s,returnType:u,typeParameters:c};if(o){e.async=true}return e},createFunctionExpression:function(n,i,t,l,a,f,s,o,u,c){var e={type:r.FunctionExpression,id:n,params:i,defaults:t,body:l,rest:a,generator:f,expression:s,returnType:u,typeParameters:c};if(o){e.async=true}return e},createIdentifier:function(e){return{type:r.Identifier,name:e,typeAnnotation:undefined,optional:undefined}},createTypeAnnotation:function(e){return{type:r.TypeAnnotation,typeAnnotation:e}},createFunctionTypeAnnotation:function(e,n,t,l){return{type:r.FunctionTypeAnnotation,params:e,returnType:n,rest:t,typeParameters:l}},createFunctionTypeParam:function(e,n,t){return{type:r.FunctionTypeParam,name:e,typeAnnotation:n,optional:t}},createNullableTypeAnnotation:function(e){return{type:r.NullableTypeAnnotation,typeAnnotation:e}},createArrayTypeAnnotation:function(e){return{type:r.ArrayTypeAnnotation,elementType:e}},createGenericTypeAnnotation:function(e,n){return{type:r.GenericTypeAnnotation,id:e,typeParameters:n}},createQualifiedTypeIdentifier:function(e,n){return{type:r.QualifiedTypeIdentifier,qualification:e,id:n}},createTypeParameterDeclaration:function(e){return{type:r.TypeParameterDeclaration,params:e}},createTypeParameterInstantiation:function(e){return{type:r.TypeParameterInstantiation,params:e}},createAnyTypeAnnotation:function(){return{type:r.AnyTypeAnnotation}},createBooleanTypeAnnotation:function(){return{type:r.BooleanTypeAnnotation}},createNumberTypeAnnotation:function(){return{type:r.NumberTypeAnnotation}},createStringTypeAnnotation:function(){return{type:r.StringTypeAnnotation}},createStringLiteralTypeAnnotation:function(e){return{type:r.StringLiteralTypeAnnotation,value:e.value,raw:s.slice(e.range[0],e.range[1])}},createVoidTypeAnnotation:function(){return{type:r.VoidTypeAnnotation}},createTypeofTypeAnnotation:function(e){return{type:r.TypeofTypeAnnotation,argument:e}},createTupleTypeAnnotation:function(e){return{type:r.TupleTypeAnnotation,types:e}},createObjectTypeAnnotation:function(e,n,t){return{type:r.ObjectTypeAnnotation,properties:e,indexers:n,callProperties:t}},createObjectTypeIndexer:function(e,n,t,l){return{type:r.ObjectTypeIndexer,id:e,key:n,value:t,"static":l}},createObjectTypeCallProperty:function(e,n){return{type:r.ObjectTypeCallProperty,value:e,"static":n}},createObjectTypeProperty:function(e,n,t,l){return{type:r.ObjectTypeProperty,key:e,value:n,optional:t,"static":l}},createUnionTypeAnnotation:function(e){return{type:r.UnionTypeAnnotation,types:e}},createIntersectionTypeAnnotation:function(e){return{type:r.IntersectionTypeAnnotation,types:e}},createTypeAlias:function(e,n,t){return{type:r.TypeAlias,id:e,typeParameters:n,right:t}},createInterface:function(e,n,t,l){return{type:r.InterfaceDeclaration,id:e,typeParameters:n,body:t,"extends":l}},createInterfaceExtends:function(e,n){return{type:r.InterfaceExtends,id:e,typeParameters:n}},createDeclareFunction:function(e){return{type:r.DeclareFunction,id:e}},createDeclareVariable:function(e){return{type:r.DeclareVariable,id:e}},createDeclareModule:function(e,n){return{type:r.DeclareModule,id:e,body:n}},createXJSAttribute:function(e,n){return{type:r.XJSAttribute,name:e,value:n||null}},createXJSSpreadAttribute:function(e){return{type:r.XJSSpreadAttribute,argument:e}},createXJSIdentifier:function(e){return{type:r.XJSIdentifier,name:e}},createXJSNamespacedName:function(e,n){return{type:r.XJSNamespacedName,namespace:e,name:n}},createXJSMemberExpression:function(e,n){return{type:r.XJSMemberExpression,object:e,property:n}},createXJSElement:function(e,n,t){return{type:r.XJSElement,openingElement:e,closingElement:n,children:t}},createXJSEmptyExpression:function(){return{type:r.XJSEmptyExpression}},createXJSExpressionContainer:function(e){return{type:r.XJSExpressionContainer,expression:e}},createXJSOpeningElement:function(e,n,t){return{type:r.XJSOpeningElement,name:e,selfClosing:t,attributes:n}},createXJSClosingElement:function(e){return{type:r.XJSClosingElement,name:e}},createIfStatement:function(e,n,t){return{type:r.IfStatement,test:e,consequent:n,alternate:t}},createLabeledStatement:function(e,n){return{type:r.LabeledStatement,label:e,body:n}},createLiteral:function(e){var n={type:r.Literal,value:e.value,raw:s.slice(e.range[0],e.range[1])};if(e.regex){n.regex=e.regex}return n},createMemberExpression:function(e,n,t){return{type:r.MemberExpression,computed:e==="[",object:n,property:t}},createNewExpression:function(e,n){return{type:r.NewExpression,callee:e,arguments:n}},createObjectExpression:function(e){return{type:r.ObjectExpression,properties:e}},createPostfixExpression:function(e,n){return{type:r.UpdateExpression,operator:e,argument:n,prefix:false}},createProgram:function(e){return{type:r.Program,body:e}},createProperty:function(e,n,t,l,a,i){return{type:r.Property,key:n,value:t,kind:e,method:l,shorthand:a,computed:i}},createReturnStatement:function(e){return{type:r.ReturnStatement,argument:e}},createSequenceExpression:function(e){return{type:r.SequenceExpression,expressions:e}},createSwitchCase:function(e,n){return{type:r.SwitchCase,test:e,consequent:n}},createSwitchStatement:function(e,n){return{type:r.SwitchStatement,discriminant:e,cases:n}},createThisExpression:function(){return{type:r.ThisExpression}},createThrowStatement:function(e){return{type:r.ThrowStatement,argument:e}},createTryStatement:function(e,n,t,l){return{type:r.TryStatement,block:e,guardedHandlers:n,handlers:t,finalizer:l}},createUnaryExpression:function(e,n){if(e==="++"||e==="--"){return{type:r.UpdateExpression,operator:e,argument:n,prefix:true}}return{type:r.UnaryExpression,operator:e,argument:n,prefix:true}},createVariableDeclaration:function(e,n){return{type:r.VariableDeclaration,declarations:e,kind:n}},createVariableDeclarator:function(e,n){return{type:r.VariableDeclarator,id:e,init:n}},createWhileStatement:function(e,n){return{type:r.WhileStatement,test:e,body:n}},createWithStatement:function(e,n){return{type:r.WithStatement,object:e,body:n}},createTemplateElement:function(e,n){return{type:r.TemplateElement,value:e,tail:n}},createTemplateLiteral:function(e,n){return{type:r.TemplateLiteral,quasis:e,expressions:n}},createSpreadElement:function(e){return{type:r.SpreadElement,argument:e}},createSpreadProperty:function(e){return{type:r.SpreadProperty,argument:e}},createTaggedTemplateExpression:function(e,n){return{type:r.TaggedTemplateExpression,tag:e,quasi:n}},createArrowFunctionExpression:function(n,t,l,a,i,s){var e={type:r.ArrowFunctionExpression,id:null,params:n,defaults:t,body:l,rest:a,generator:false,expression:i};if(s){e.async=true}return e},createMethodDefinition:function(e,n,t,l,a){return{type:r.MethodDefinition,key:t,value:l,kind:n,"static":e===tn.static,computed:a}},createClassProperty:function(e,n,t,l){return{type:r.ClassProperty,key:e,typeAnnotation:n,computed:t,"static":l}},createClassBody:function(e){return{type:r.ClassBody,body:e}},createClassImplements:function(e,n){return{type:r.ClassImplements,id:e,typeParameters:n}},createClassExpression:function(e,n,t,l,a,i){return{type:r.ClassExpression,id:e,superClass:n,body:t,typeParameters:l,superTypeParameters:a,"implements":i}},createClassDeclaration:function(e,n,t,l,a,i){return{type:r.ClassDeclaration,id:e,superClass:n,body:t,typeParameters:l,superTypeParameters:a,"implements":i}},createModuleSpecifier:function(e){return{type:r.ModuleSpecifier,value:e.value,raw:s.slice(e.range[0],e.range[1])}},createExportSpecifier:function(e,n){return{type:r.ExportSpecifier,id:e,name:n}},createExportBatchSpecifier:function(){return{type:r.ExportBatchSpecifier}},createImportDefaultSpecifier:function(e){return{type:r.ImportDefaultSpecifier,id:e}},createImportNamespaceSpecifier:function(e){return{type:r.ImportNamespaceSpecifier,id:e}},createExportDeclaration:function(e,n,t,l){return{type:r.ExportDeclaration,"default":!!e,declaration:n,specifiers:t,source:l}},createImportSpecifier:function(e,n){return{type:r.ImportSpecifier,id:e,name:n}},createImportDeclaration:function(e,n){return{type:r.ImportDeclaration,specifiers:e,source:n}},createYieldExpression:function(e,n){return{type:r.YieldExpression,argument:e,delegate:n}},createAwaitExpression:function(e){return{type:r.AwaitExpression,argument:e}},createComprehensionExpression:function(e,n,t){return{type:r.ComprehensionExpression,filter:e,blocks:n,body:t}}};function rn(){var t,n,r,l;t=e;n=h;r=g;N();l=h!==n;e=t;h=n;g=r;return l}function d(t,a){var n,l=Array.prototype.slice.call(arguments,2),r=a.replace(/%(\d)/g,function(n,e){J(e<l.length,"Message reference must be in range");return l[e]});if(typeof t.lineNumber==="number"){n=new Error("Line "+t.lineNumber+": "+r);n.index=t.range[0];n.lineNumber=t.lineNumber;n.column=t.range[0]-g+1}else{n=new Error("Line "+h+": "+r);n.index=e;n.lineNumber=h;n.column=e-g+1}n.description=r;throw n}function E(){try{d.apply(null,arguments)}catch(e){if(f.errors){f.errors.push(e)}else{throw e}}}function S(e){if(e.type===o.EOF){d(e,i.UnexpectedEOS)}if(e.type===o.NumericLiteral){d(e,i.UnexpectedNumber)}if(e.type===o.StringLiteral||e.type===o.XJSText){d(e,i.UnexpectedString)}if(e.type===o.Identifier){d(e,i.UnexpectedIdentifier)}if(e.type===o.Keyword){if(jr(e.value)){d(e,i.UnexpectedReserved)}else if(v&&ln(e.value)){E(e,i.StrictReservedWord);return}d(e,i.UnexpectedToken,e.value)}if(e.type===o.Template){d(e,i.UnexpectedTemplate,e.value.raw)}d(e,i.UnexpectedToken,e.value)}function u(n){var e=m();if(e.type!==o.Punctuator||e.value!==n){S(e)}}function x(n,t){var e=m();if(e.type!==(t?o.Identifier:o.Keyword)||e.value!==n){S(e)}}function V(e){return x(e,true)}function n(e){return c.type===o.Punctuator&&c.value===e}function b(e,n){var t=n?o.Identifier:o.Keyword;return c.type===t&&c.value===e}function _(e){return b(e,true)}function lr(){var e;if(c.type!==o.Punctuator){return false}e=c.value;return e==="="||e==="*="||e==="/="||e==="%="||e==="+="||e==="-="||e==="<<="||e===">>="||e===">>>="||e==="&="||e==="^="||e==="|="}function ir(){return a.yieldAllowed&&b("yield",!v)}function un(){var n=c,e=false;if(_("async")){m();e=!rn();dn(n)}return e}function or(){return a.awaitAllowed&&_("await")}function k(){var t,r=e,l=h,a=g,i=c;if(s.charCodeAt(e)===59){m();return}t=h;N();if(h!==t){e=r;h=l;g=a;c=i;return}if(n(";")){m();return}if(c.type!==o.EOF&&!n("}")){S(c)}}function gn(e){return e.type===r.Identifier||e.type===r.MemberExpression}function Tr(e){return gn(e)||e.type===r.ObjectPattern||e.type===r.ArrayPattern}function yn(){var a=[],s=[],h=null,e,f=true,y,g=p();u("[");while(!n("]")){if(c.value==="for"&&c.type===o.Keyword){if(!f){d({},i.ComprehensionError)}b("for");e=Zn({ignoreBody:true});e.of=e.type===r.ForOfStatement;e.type=r.ComprehensionBlock;if(e.left.kind){d({},i.ComprehensionError)}s.push(e)}else if(c.value==="if"&&c.type===o.Keyword){if(!f){d({},i.ComprehensionError)}x("if");u("(");h=w();u(")")}else if(c.value===","&&c.type===o.Punctuator){f=false;m();a.push(null)}else{e=jn();a.push(e);if(e&&e.type===r.SpreadElement){if(!n("]")){d({},i.ElementAfterSpreadElement)}}else if(!(n("]")||b("for")||b("if"))){u(",");f=false}}}u("]");if(h&&!s.length){d({},i.ComprehensionRequiresBlock)}if(s.length){if(a.length!==1){d({},i.ComprehensionError)}return t(g,l.createComprehensionExpression(h,s,a[0]))}return t(g,l.createArrayExpression(a))}function cn(e){var o,u,c,n,f,s,d=p();o=v;u=a.yieldAllowed;a.yieldAllowed=e.generator;c=a.awaitAllowed;a.awaitAllowed=e.async;n=e.params||[];f=e.defaults||[];s=nt();if(e.name&&v&&L(n[0].name)){E(e.name,i.StrictParamName)}v=o;a.yieldAllowed=u;a.awaitAllowed=c;return t(d,l.createFunctionExpression(null,n,f,s,e.rest||null,e.generator,s.type!==r.BlockStatement,e.async,e.returnType,e.typeParameters))}function Z(n){var t,e,r;t=v;v=true;e=hn();if(e.stricted){E(e.stricted,e.message)}r=cn({params:e.params,defaults:e.defaults,rest:e.rest,generator:n.generator,async:n.async,returnType:e.returnType,typeParameters:n.typeParameters});v=t;return r}function M(){var n=p(),e=m(),r,a;if(e.type===o.StringLiteral||e.type===o.NumericLiteral){if(v&&e.octal){E(e,i.StrictOctalLiteral)}return t(n,l.createLiteral(e))}if(e.type===o.Punctuator&&e.value==="["){n=p();r=R();a=t(n,r);u("]");return a}return t(n,l.createIdentifier(e.value))}function Zr(){var r,a,f,g,h,y,e,i=p(),d,s;r=c;e=r.value==="["&&r.type===o.Punctuator;if(r.type===o.Identifier||e||un()){f=M();if(n(":")){m();return t(i,l.createProperty("init",f,R(),false,false,e))}if(n("(")||n("<")){if(n("<")){s=C()}return t(i,l.createProperty("init",f,Z({generator:false,async:false,typeParameters:s}),true,false,e))}if(r.value==="get"){e=c.value==="[";a=M();u("(");u(")");if(n(":")){d=D()}return t(i,l.createProperty("get",a,cn({generator:false,async:false,returnType:d}),false,false,e))}if(r.value==="set"){e=c.value==="[";a=M();u("(");r=c;h=[Q()];u(")");if(n(":")){d=D()}return t(i,l.createProperty("set",a,cn({params:h,generator:false,async:false,name:r,returnType:d}),false,false,e))}if(r.value==="async"){e=c.value==="[";a=M();if(n("<")){s=C()}return t(i,l.createProperty("init",a,Z({generator:false,async:true,typeParameters:s}),true,false,e))}if(e){S(c)}return t(i,l.createProperty("init",f,f,false,true,false))}if(r.type===o.EOF||r.type===o.Punctuator){if(!n("*")){S(r)}m();e=c.type===o.Punctuator&&c.value==="[";f=M();if(n("<")){s=C()}if(!n("(")){S(m())}return t(i,l.createProperty("init",f,Z({generator:true,typeParameters:s}),true,false,e))}a=M();if(n(":")){m();return t(i,l.createProperty("init",a,R(),false,false,false))}if(n("(")||n("<")){if(n("<")){s=C()}return t(i,l.createProperty("init",a,Z({generator:false,typeParameters:s}),true,false,false))}S(m())}function ll(){var e=p();u("...");return t(e,l.createSpreadProperty(R()))}function At(e){var n=String;if(e.type===r.Identifier){return e.name}return n(e.value)}function _n(){var f=[],e,s,a,o,c=new O,d=p(),m=String;u("{");while(!n("}")){if(n("...")){e=ll()}else{e=Zr();if(e.key.type===r.Identifier){s=e.key.name}else{s=m(e.key.value)}a=e.kind==="init"?G.Data:e.kind==="get"?G.Get:G.Set;if(c.has(s)){o=c.get(s);if(o===G.Data){if(v&&a===G.Data){E({},i.StrictDuplicateProperty)}else if(a!==G.Data){E({},i.AccessorDataProperty)}}else{if(a===G.Data){E({},i.AccessorDataProperty)}else if(o&a){E({},i.AccessorGetSet)}}c.set(s,o|a)}else{c.set(s,a)}}f.push(e);if(!n("}")){u(",")}}u("}");return t(d,l.createObjectExpression(f))}function at(n){var r=p(),e=Jt(n);if(v&&e.octal){d(e,i.StrictOctalLiteral)}return t(r,l.createTemplateElement({raw:e.value.raw,cooked:e.value.cooked},e.tail))}function Cn(){var e,n,r,a=p();e=at({head:true});n=[e];r=[];while(!e.tail){r.push(w());e=at({head:false});n.push(e)}return t(a,l.createTemplateLiteral(n,r))}function nr(){var e;u("(");++a.parenthesizedCount;e=w();u(")");return e}function lt(){var e;if(un()){e=P();if(e.type===o.Keyword&&e.value==="function"){return true}}return false}function rt(){var e,r,a,s;r=c.type;if(r===o.Identifier){e=p();return t(e,l.createIdentifier(m().value))}if(r===o.StringLiteral||r===o.NumericLiteral){if(v&&c.octal){E(c,i.StrictOctalLiteral)}e=p();return t(e,l.createLiteral(m()))}if(r===o.Keyword){if(b("this")){e=p();m();return t(e,l.createThisExpression())}if(b("function")){return On()}if(b("class")){return ct()}if(b("super")){e=p();m();return t(e,l.createIdentifier("super"))}}if(r===o.BooleanLiteral){e=p();a=m();a.value=a.value==="true";return t(e,l.createLiteral(a))}if(r===o.NullLiteral){e=p();a=m();a.value=null;return t(e,l.createLiteral(a))}if(n("[")){return yn()}if(n("{")){return _n()}if(n("(")){return nr()}if(n("/")||n("/=")){e=p();s=l.createLiteral(F());mn();return t(e,s)}if(r===o.Template){return Cn()}if(n("<")){return Mn()}S(m())}function tt(){var l=[],t;u("(");if(!n(")")){while(e<y){t=jn();l.push(t);if(n(")")){break}else if(t.type===r.SpreadElement){d({},i.ElementAfterSpreadElement)}u(",")}}u(")");return l}function jn(){if(n("...")){var e=p();m();return t(e,l.createSpreadElement(R()))}return R()}function H(){var n=p(),e=m();if(!Dn(e)){S(e)}return t(n,l.createIdentifier(e.value))}function et(){u(".");return H()}function $n(){var e;u("[");e=w();u("]");return e}function Yn(){var e,r,a=p();x("new");e=Dr();r=n("(")?tt():[];return t(a,l.createNewExpression(e,r))}function Fn(){var e,a,r=p();e=b("new")?Yn():rt();while(n(".")||n("[")||n("(")||c.type===o.Template){if(n("(")){a=tt();e=t(r,l.createCallExpression(e,a))}else if(n("[")){e=t(r,l.createMemberExpression("[",e,$n()))}else if(n(".")){e=t(r,l.createMemberExpression(".",e,et()))}else{e=t(r,l.createTaggedTemplateExpression(e,Cn()))}}return e}function Dr(){var e,r=p();e=b("new")?Yn():rt();while(n(".")||n("[")||c.type===o.Template){if(n("[")){e=t(r,l.createMemberExpression("[",e,$n()))}else if(n(".")){e=t(r,l.createMemberExpression(".",e,et()))}else{e=t(r,l.createTaggedTemplateExpression(e,Cn()))}}return e}function zn(){var s=p(),e=Fn(),a;if(c.type!==o.Punctuator){return e}if((n("++")||n("--"))&&!rn()){if(v&&e.type===r.Identifier&&L(e.name)){E({},i.StrictLHSPostfix)}if(!gn(e)){d({},i.InvalidLHSInAssignment)}a=m();e=t(s,l.createPostfixExpression(a.value,e))}return e}function K(){var a,s,e;if(c.type!==o.Punctuator&&c.type!==o.Keyword){return zn()}if(n("++")||n("--")){a=p();s=m();e=K();if(v&&e.type===r.Identifier&&L(e.name)){E({},i.StrictLHSPrefix)}if(!gn(e)){d({},i.InvalidLHSInAssignment)}return t(a,l.createUnaryExpression(s.value,e))}if(n("+")||n("-")||n("~")||n("!")){a=p();s=m();e=K();return t(a,l.createUnaryExpression(s.value,e))}if(b("delete")||b("void")||b("typeof")){a=p();s=m();e=K();e=t(a,l.createUnaryExpression(s.value,e));if(v&&e.operator==="delete"&&e.argument.type===r.Identifier){E({},i.StrictDelete)}return e}return zn()}function Hn(n,t){var e=0;if(n.type!==o.Punctuator&&n.type!==o.Keyword){return 0}switch(n.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=t?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 Qr(){var n,i,u,d,e,h,g,f,o,r,s;d=a.allowIn;a.allowIn=true;r=p();f=K();i=c;u=Hn(i,d);if(u===0){return f}i.prec=u;m();s=[r,p()];h=K();e=[f,i,h];while((u=Hn(c,d))>0){while(e.length>2&&u<=e[e.length-2].prec){h=e.pop();g=e.pop().value;f=e.pop();n=l.createBinaryExpression(g,f,h);s.pop();r=s.pop();t(r,n);e.push(n);s.push(r)}i=m();i.prec=u;e.push(i);s.push(p());n=K();e.push(n)}a.allowIn=d;o=e.length-1;n=e[o];s.pop();while(o>1){n=l.createBinaryExpression(e[o-1].value,e[o-2],n);o-=2;r=s.pop();t(r,n)}return n}function Wn(){var e,r,i,s,o=p();e=Qr();if(n("?")){m();r=a.allowIn;a.allowIn=true;i=R();a.allowIn=r;u(":");s=R();e=t(o,l.createConditionalExpression(e,i,s))}return e}function z(e){var n,t,l,a;if(e.type===r.ObjectExpression){e.type=r.ObjectPattern;for(n=0,t=e.properties.length;n<t;n+=1){l=e.properties[n];if(l.type===r.SpreadProperty){if(n<t-1){d({},i.PropertyAfterSpreadProperty)}z(l.argument)}else{if(l.kind!=="init"){d({},i.InvalidLHSInAssignment)}z(l.value)}}}else if(e.type===r.ArrayExpression){e.type=r.ArrayPattern;for(n=0,t=e.elements.length;n<t;n+=1){a=e.elements[n];if(a){z(a)}}}else if(e.type===r.Identifier){if(L(e.name)){d({},i.InvalidLHSInAssignment)}}else if(e.type===r.SpreadElement){z(e.argument);if(e.argument.type===r.ObjectPattern){d({},i.ObjectPatternAsSpread)}}else{if(e.type!==r.MemberExpression&&e.type!==r.CallExpression&&e.type!==r.NewExpression){d({},i.InvalidLHSInAssignment)}}}function Y(t,e){var n,l,a,s;if(e.type===r.ObjectExpression){e.type=r.ObjectPattern;for(n=0,l=e.properties.length;n<l;n+=1){a=e.properties[n];if(a.type===r.SpreadProperty){if(n<l-1){d({},i.PropertyAfterSpreadProperty)}Y(t,a.argument)}else{if(a.kind!=="init"){d({},i.InvalidLHSInFormalsList)}Y(t,a.value)}}}else if(e.type===r.ArrayExpression){e.type=r.ArrayPattern;for(n=0,l=e.elements.length;n<l;n+=1){s=e.elements[n];if(s){Y(t,s)}}}else if(e.type===r.Identifier){sn(t,e,e.name)}else if(e.type===r.SpreadElement){if(e.argument.type!==r.Identifier){d({},i.InvalidLHSInFormalsList)}sn(t,e.argument,e.argument.name)}else{d({},i.InvalidLHSInFormalsList)}}function Tn(c){var l,s,e,a,t,o,n,u;a=[];t=[];o=0;u=null;n={paramSet:new O};for(l=0,s=c.length;l<s;l+=1){e=c[l];if(e.type===r.Identifier){a.push(e);t.push(null);sn(n,e,e.name)}else if(e.type===r.ObjectExpression||e.type===r.ArrayExpression){Y(n,e);a.push(e);t.push(null)}else if(e.type===r.SpreadElement){J(l===s-1,"It is guaranteed that SpreadElement is last element by parseExpression");if(e.argument.type!==r.Identifier){d({},i.InvalidLHSInFormalsList)}Y(n,e.argument);u=e.argument}else if(e.type===r.AssignmentExpression){a.push(e.left);t.push(e.right);++o;sn(n,e.left,e.left.name)}else{return null}}if(n.message===i.StrictParamDupe){d(v?n.stricted:n.firstRestricted,n.message)}if(o===0){t=[]}return{params:a,defaults:t,rest:u,stricted:n.stricted,firstRestricted:n.firstRestricted,message:n.message}}function Ln(e,c){var i,s,o,n;u("=>");i=v;s=a.yieldAllowed;a.yieldAllowed=false;o=a.awaitAllowed;a.awaitAllowed=!!e.async;n=nt();if(v&&e.firstRestricted){d(e.firstRestricted,e.message)}if(v&&e.stricted){E(e.stricted,e.message)}v=i;a.yieldAllowed=s;a.awaitAllowed=o;return t(c,l.createArrowFunctionExpression(e.params,e.defaults,n,e.rest,n.type!==r.BlockStatement,!!e.async))}function R(){var h,e,u,s,g,y=c,f=false;if(ir()){return ur()}if(or()){return cr()}g=a.parenthesizedCount;h=p();if(lt()){return On()}if(un()){f=true;m()}if(n("(")){u=P();if(u.type===o.Punctuator&&u.value===")"||u.value==="..."){s=hn();if(!n("=>")){S(m())}s.async=f;return Ln(s,h)}}u=c;if(f&&!n("(")&&u.type!==o.Identifier){f=false;dn(y)}e=Wn();if(n("=>")&&(a.parenthesizedCount===g||a.parenthesizedCount===g+1)){if(e.type===r.Identifier){s=Tn([e])}else if(e.type===r.SequenceExpression){s=Tn(e.expressions)}if(s){s.async=f;return Ln(s,h)}}if(f){f=false;dn(y);e=Wn()}if(lr()){if(v&&e.type===r.Identifier&&L(e.name)){E(u,i.StrictLHSAssignment)}if(n("=")&&(e.type===r.ObjectExpression||e.type===r.ArrayExpression)){z(e)}else if(!gn(e)){d({},i.InvalidLHSInAssignment)}e=t(h,l.createAssignmentExpression(m().value,e,R()))}return e}function w(){var u,s,o,h,c,g,f;f=a.parenthesizedCount;u=p();s=R();o=[s];if(n(",")){while(e<y){if(!n(",")){break}m();s=jn();o.push(s);if(s.type===r.SpreadElement){g=true;if(!n(")")){d({},i.ElementAfterSpreadElement)}break}}h=t(u,l.createSequenceExpression(o))}if(n("=>")){if(a.parenthesizedCount===f||a.parenthesizedCount===f+1){s=s.type===r.SequenceExpression?s.expressions:o;c=Tn(s);if(c){return Ln(c,u)}}S(m())}if(g&&P().value!=="=>"){d({},i.IllegalSpread)}return h||s}function tr(){var r=[],t;while(e<y){if(n("}")){break}t=$();if(typeof t==="undefined"){break}r.push(t)}return r}function xn(){var e,n=p();u("{");e=tr();u("}");return t(n,l.createBlockStatement(e))}function C(){var r=p(),e=[];u("<");while(!n(">")){e.push(I());if(!n(">")){u(",")}}u(">");return t(r,l.createTypeParameterDeclaration(e))}function fn(){var r=p(),i=a.inType,e=[];a.inType=true;u("<");while(!n(">")){e.push(j());if(!n(">")){u(",")}}u(">");a.inType=i;return t(r,l.createTypeParameterInstantiation(e))}function ol(a,i){var e,n,r;u("[");e=M();u(":");n=j();u("]");u(":");r=j();return t(a,l.createObjectTypeIndexer(e,n,r,i))}function Gn(s){var e=[],r=null,a,i=null;if(n("<")){i=C()}u("(");while(c.type===o.Identifier){e.push(Sn());if(!n(")")){u(",")}}if(n("...")){m();r=Sn()}u(")");u(":");a=j();return t(s,l.createFunctionTypeAnnotation(e,a,r,i))}function fr(e,r,a){var i=false,n;n=Gn(e);return t(e,l.createObjectTypeProperty(a,n,i,r))}function hr(e,n){var r=p();return t(e,l.createObjectTypeCallProperty(Gn(r),n))}function ot(y){var f=[],g=[],e,d=false,s=[],v,a,h,o,r;u("{");while(!n("}")){e=p();if(y&&_("static")){o=m();r=true}if(n("[")){g.push(ol(e,r))}else if(n("(")||n("<")){f.push(hr(e,y))}else{if(r&&n(":")){a=t(e,l.createIdentifier(o));E(o,i.StrictReservedWord)}else{a=M()}if(n("<")||n("(")){s.push(fr(e,r,a))}else{if(n("?")){m();d=true}u(":");h=j();s.push(t(e,l.createObjectTypeProperty(a,h,d,r)))}}if(n(";")){m()}else if(!n("}")){S(c)}}u("}");return l.createObjectTypeAnnotation(s,g,f)}function yr(){var r=p(),i=null,a=null,e,s=p;e=I();while(n(".")){u(".");e=t(r,l.createQualifiedTypeIdentifier(e,I()))}if(n("<")){a=fn()}return t(r,l.createGenericTypeAnnotation(e,a))}function xr(){var e=p();x("void");return t(e,l.createVoidTypeAnnotation())}function br(){var e,n=p();x("typeof");e=qn();return t(n,l.createTypeofTypeAnnotation(e))}function _r(){var a=p(),r=[];u("[");while(e<y&&!n("]")){r.push(j());if(n("]")){break}u(",")}u("]");return t(a,l.createTupleTypeAnnotation(r))}function Sn(){var i=p(),e,r=false,a;e=I();if(n("?")){m();r=true}u(":");a=j();return t(i,l.createFunctionTypeParam(e,a,r))}function Vn(){var e={params:[],rest:null};while(c.type===o.Identifier){e.params.push(Sn());
if(!n(")")){u(",")}}if(n("...")){m();e.rest=Sn()}return e}function qn(){var x=null,s=null,f=null,e=p(),h=null,a,y,r,v,g=false;switch(c.type){case o.Identifier:switch(c.value){case"any":m();return t(e,l.createAnyTypeAnnotation());case"bool":case"boolean":m();return t(e,l.createBooleanTypeAnnotation());case"number":m();return t(e,l.createNumberTypeAnnotation());case"string":m();return t(e,l.createStringTypeAnnotation())}return t(e,yr());case o.Punctuator:switch(c.value){case"{":return t(e,ot());case"[":return _r();case"<":y=C();u("(");a=Vn();s=a.params;h=a.rest;u(")");u("=>");f=j();return t(e,l.createFunctionTypeAnnotation(s,f,h,y));case"(":m();if(!n(")")&&!n("...")){if(c.type===o.Identifier){r=P();g=r.value!=="?"&&r.value!==":"}else{g=true}}if(g){v=j();u(")");if(n("=>")){d({},i.ConfusedAboutFunctionType)}return v}a=Vn();s=a.params;h=a.rest;u(")");u("=>");f=j();return t(e,l.createFunctionTypeAnnotation(s,f,h,null))}break;case o.Keyword:switch(c.value){case"void":return t(e,xr());case"typeof":return t(e,br())}break;case o.StringLiteral:r=m();if(r.octal){d(r,i.StrictOctalLiteral)}return t(e,l.createStringLiteralTypeAnnotation(r))}S(c)}function Mr(){var r=p(),e=qn();if(n("[")){u("[");u("]");return t(r,l.createArrayTypeAnnotation(e))}return e}function Bn(){var e=p();if(n("?")){m();return t(e,l.createNullableTypeAnnotation(Bn()))}return Mr()}function Jn(){var a=p(),r,e;r=Bn();e=[r];while(n("&")){m();e.push(Bn())}return e.length===1?r:t(a,l.createIntersectionTypeAnnotation(e))}function Wr(){var a=p(),r,e;r=Jn();e=[r];while(n("|")){m();e.push(Jn())}return e.length===1?r:t(a,l.createUnionTypeAnnotation(e))}function j(){var n=a.inType,e;a.inType=true;e=Wr();a.inType=n;return e}function D(){var n=p(),e;u(":");e=j();return t(n,l.createTypeAnnotation(e))}function I(){var n=p(),e=m();if(e.type!==o.Identifier){S(e)}return t(n,l.createIdentifier(e.value))}function Q(a,i){var r=p(),e=I(),l=false;if(i&&n("?")){u("?");l=true}if(a||n(":")){e.typeAnnotation=D();e=t(r,e)}if(l){e.optional=true;e=t(r,e)}return e}function rl(o){var e,c=p(),r=null,s=p();if(n("{")){e=_n();z(e);if(n(":")){e.typeAnnotation=D();t(s,e)}}else if(n("[")){e=yn();z(e);if(n(":")){e.typeAnnotation=D();t(s,e)}}else{e=a.allowKeyword?H():Q();if(v&&L(e.name)){E({},i.StrictVarName)}}if(o==="const"){if(!n("=")){d({},i.NoUnintializedConst)}u("=");r=R()}else if(n("=")){m();r=R()}return t(c,l.createVariableDeclarator(e,r))}function Nn(r){var t=[];do{t.push(rl(r));if(!n(",")){break}m()}while(e<y);return t}function al(){var e,n=p();x("var");e=Nn();k();return t(n,l.createVariableDeclaration(e,"var"))}function Ct(e){var n,r=p();x(e);n=Nn(e);k();return t(r,l.createVariableDeclaration(n,e))}function bn(){var n=p(),e;if(c.type!==o.StringLiteral){d({},i.InvalidModuleSpecifier)}e=l.createModuleSpecifier(c);m();return t(n,e)}function Tt(){var e=p();u("*");return t(e,l.createExportBatchSpecifier())}function Lt(){var e,n=null,r=p(),a;if(b("default")){m();e=t(r,l.createIdentifier("default"))}else{e=I()}if(_("as")){m();n=H()}return t(r,l.createExportSpecifier(e,n))}function Kn(){var f,g,y,r=null,h,s=null,a=[],e=p();x("export");if(b("default")){m();if(b("function")||b("class")){f=c;m();if(Dn(c)){g=H();dn(f);return t(e,l.createExportDeclaration(true,$(),[g],null))}dn(f);switch(c.value){case"class":return t(e,l.createExportDeclaration(true,ct(),[],null));case"function":return t(e,l.createExportDeclaration(true,On(),[],null))}}if(_("from")){d({},i.UnexpectedToken,c.value)}if(n("{")){r=_n()}else if(n("[")){r=yn()}else{r=R()}k();return t(e,l.createExportDeclaration(true,r,[],null))}if(c.type===o.Keyword){switch(c.value){case"let":case"const":case"var":case"class":case"function":return t(e,l.createExportDeclaration(false,$(),a,null))}}if(n("*")){a.push(Tt());if(!_("from")){d({},c.value?i.UnexpectedToken:i.MissingFromClause,c.value)}m();s=bn();k();return t(e,l.createExportDeclaration(false,null,a,s))}u("{");if(!n("}")){do{h=h||b("default");a.push(Lt())}while(n(",")&&m())}u("}");if(_("from")){m();s=bn();k()}else if(h){d({},c.value?i.UnexpectedToken:i.MissingFromClause,c.value)}else{k()}return t(e,l.createExportDeclaration(false,r,a,s))}function jt(){var e,n=null,r=p();e=H();if(_("as")){m();n=I()}return t(r,l.createImportSpecifier(e,n))}function Mt(){var e=[];u("{");if(!n("}")){do{e.push(jt())}while(n(",")&&m())}u("}");return e}function Ot(){var e,n=p();e=H();return t(n,l.createImportDefaultSpecifier(e))}function Dt(){var e,n=p();u("*");if(!_("as")){d({},i.NoAsAfterImportNamespace)}m();e=H();return t(n,l.createImportNamespaceSpecifier(e))}function Qn(){var e,r,a=p();x("import");e=[];if(c.type===o.StringLiteral){r=bn();k();return t(a,l.createImportDeclaration(e,r))}if(!b("default")&&Dn(c)){e.push(Ot());if(n(",")){m()}}if(n("*")){e.push(Dt())}else if(n("{")){e=e.concat(Mt())}if(!_("from")){d({},c.value?i.UnexpectedToken:i.MissingFromClause,c.value)}m();r=bn();k();return t(a,l.createImportDeclaration(e,r))}function Ft(){var e=p();u(";");return t(e,l.createEmptyStatement())}function Bt(){var e=p(),n=w();k();return t(e,l.createExpressionStatement(n))}function Ut(){var n,r,e,a=p();x("if");u("(");n=w();u(")");r=q();if(b("else")){m();e=q()}else{e=null}return t(a,l.createIfStatement(n,r,e))}function Vt(){var e,r,i,s=p();x("do");i=a.inIteration;a.inIteration=true;e=q();a.inIteration=i;x("while");u("(");r=w();u(")");if(n(";")){m()}return t(s,l.createDoWhileStatement(e,r))}function Xt(){var e,n,r,i=p();x("while");u("(");e=w();u(")");r=a.inIteration;a.inIteration=true;n=q();a.inIteration=r;return t(i,l.createWhileStatement(e,n))}function qt(){var e=p(),n=m(),r=Nn();return t(e,l.createVariableDeclaration(r,n.value))}function Zn(v){var e,h,g,r,s,f,o,E,y=p();e=h=g=null;x("for");if(_("each")){d({},i.EachNotAllowed)}u("(");if(n(";")){m()}else{if(b("var")||b("let")||b("const")){a.allowIn=false;e=qt();a.allowIn=true;if(e.declarations.length===1){if(b("in")||_("of")){o=c;if(!((o.value==="in"||e.kind!=="var")&&e.declarations[0].init)){m();r=e;s=w();e=null}}}}else{a.allowIn=false;e=w();a.allowIn=true;if(_("of")){o=m();r=e;s=w();e=null}else if(b("in")){if(!Tr(e)){d({},i.InvalidLHSInForIn)}o=m();r=e;s=w();e=null}}if(typeof r==="undefined"){u(";")}}if(typeof r==="undefined"){if(!n(";")){h=w()}u(";");if(!n(")")){g=w()}}u(")");E=a.inIteration;a.inIteration=true;if(!(v!==undefined&&v.ignoreBody)){f=q()}a.inIteration=E;if(typeof r==="undefined"){return t(y,l.createForStatement(e,h,g,f))}if(o.value==="in"){return t(y,l.createForInStatement(r,s,f))}return t(y,l.createForOfStatement(r,s,f))}function Gt(){var n=null,r=p();x("continue");if(s.charCodeAt(e)===59){m();if(!a.inIteration){d({},i.IllegalContinue)}return t(r,l.createContinueStatement(null))}if(rn()){if(!a.inIteration){d({},i.IllegalContinue)}return t(r,l.createContinueStatement(null))}if(c.type===o.Identifier){n=I();if(!a.labelSet.has(n.name)){d({},i.UnknownLabel,n.name)}}k();if(n===null&&!a.inIteration){d({},i.IllegalContinue)}return t(r,l.createContinueStatement(n))}function Wt(){var n=null,r=p();x("break");if(s.charCodeAt(e)===59){m();if(!(a.inIteration||a.inSwitch)){d({},i.IllegalBreak)}return t(r,l.createBreakStatement(null))}if(rn()){if(!(a.inIteration||a.inSwitch)){d({},i.IllegalBreak)}return t(r,l.createBreakStatement(null))}if(c.type===o.Identifier){n=I();if(!a.labelSet.has(n.name)){d({},i.UnknownLabel,n.name)}}k();if(n===null&&!(a.inIteration||a.inSwitch)){d({},i.IllegalBreak)}return t(r,l.createBreakStatement(n))}function Ht(){var r=null,u=p();x("return");if(!a.inFunctionBody){E({},i.IllegalReturn)}if(s.charCodeAt(e)===32){if(W(s.charCodeAt(e+1))){r=w();k();return t(u,l.createReturnStatement(r))}}if(rn()){return t(u,l.createReturnStatement(null))}if(!n(";")){if(!n("}")&&c.type!==o.EOF){r=w()}}k();return t(u,l.createReturnStatement(r))}function zt(){var e,n,r=p();if(v){E({},i.StrictModeWith)}x("with");u("(");e=w();u(")");n=q();return t(r,l.createWithStatement(e,n))}function Yt(){var r,i=[],a,s=p();if(b("default")){m();r=null}else{x("case");r=w()}u(":");while(e<y){if(n("}")||b("default")||b("case")){break}a=$();if(typeof a==="undefined"){break}i.push(a)}return t(s,l.createSwitchCase(r,i))}function $t(){var s,r,o,f,c,h=p();x("switch");u("(");s=w();u(")");u("{");r=[];if(n("}")){m();return t(h,l.createSwitchStatement(s,r))}f=a.inSwitch;a.inSwitch=true;c=false;while(e<y){if(n("}")){break}o=Yt();if(o.test===null){if(c){d({},i.MultipleDefaultsInSwitch)}c=true}r.push(o)}a.inSwitch=f;u("}");return t(h,l.createSwitchStatement(s,r))}function Kt(){var e,n=p();x("throw");if(rn()){d({},i.NewlineAfterThrow)}e=w();k();return t(n,l.createThrowStatement(e))}function Qt(){var e,a,s=p();x("catch");u("(");if(n(")")){S(c)}e=w();if(v&&e.type===r.Identifier&&L(e.name)){E({},i.StrictCatchVariable)}u(")");a=xn();return t(s,l.createCatchClause(e,a))}function Zt(){var r,e=[],n=null,a=p();x("try");r=xn();if(b("catch")){e.push(Qt())}if(b("finally")){m();n=xn()}if(e.length===0&&!n){d({},i.NoCatchOrFinally)}return t(a,l.createTryStatement(r,[],e,n))}function er(){var e=p();x("debugger");k();return t(e,l.createDebuggerStatement())}function q(){var s=c.type,u,e,f;if(s===o.EOF){S(c)}if(s===o.Punctuator){switch(c.value){case";":return Ft();case"{":return xn();case"(":return Bt();default:break}}if(s===o.Keyword){switch(c.value){case"break":return Wt();case"continue":return Gt();case"debugger":return er();case"do":return Vt();case"for":return Zn();case"function":return In();case"class":return vr();case"if":return Ut();case"return":return Ht();case"switch":return $t();case"throw":return Kt();case"try":return Zt();case"var":return al();case"while":return Xt();case"with":return zt();default:break}}if(lt()){return In()}u=p();e=w();if(e.type===r.Identifier&&n(":")){m();if(a.labelSet.has(e.name)){d({},i.Redeclaration,"Label",e.name)}a.labelSet.set(e.name,true);f=q();a.labelSet["delete"](e.name);return t(u,l.createLabeledStatement(e,f))}k();return t(u,l.createExpressionStatement(e))}function nt(){if(n("{")){return Pn()}return R()}function Pn(){var f,h=[],d,x,m,g,b,w,_,S,k=p();u("{");while(e<y){if(c.type!==o.StringLiteral){break}d=c;f=$();h.push(f);if(f.expression.type!==r.Literal){break}x=s.slice(d.range[0]+1,d.range[1]-1);if(x==="use strict"){v=true;if(m){E(m,i.StrictOctalLiteral)}}else{if(!m&&d.octal){m=d}}}g=a.labelSet;b=a.inIteration;w=a.inSwitch;_=a.inFunctionBody;S=a.parenthesizedCount;a.labelSet=new O;a.inIteration=false;a.inSwitch=false;a.inFunctionBody=true;a.parenthesizedCount=0;while(e<y){if(n("}")){break}f=$();if(typeof f==="undefined"){break}h.push(f)}u("}");a.labelSet=g;a.inIteration=b;a.inSwitch=w;a.inFunctionBody=_;a.parenthesizedCount=S;return t(k,l.createBlockStatement(h))}function sn(e,t,n){if(v){if(L(n)){e.stricted=t;e.message=i.StrictParamName}if(e.paramSet.has(n)){e.stricted=t;e.message=i.StrictParamDupe}}else if(!e.firstRestricted){if(L(n)){e.firstRestricted=t;e.message=i.StrictParamName}else if(ln(n)){e.firstRestricted=t;e.message=i.StrictReservedWord}else if(e.paramSet.has(n)){e.firstRestricted=t;e.message=i.StrictParamDupe}}e.paramSet.set(n,true)}function ar(r){var s,l,a,e,o;l=c;if(l.value==="..."){l=m();a=true}if(n("[")){s=p();e=yn();Y(r,e);if(n(":")){e.typeAnnotation=D();t(s,e)}}else if(n("{")){s=p();if(a){d({},i.ObjectPatternAsRestParameter)}e=_n();Y(r,e);if(n(":")){e.typeAnnotation=D();t(s,e)}}else{e=a?Q(false,false):Q(false,true);sn(r,l,l.value)}if(n("=")){if(a){E(c,i.DefaultRestParameter)}m();o=R();++r.defaultCount}if(a){if(!n(")")){d({},i.ParameterAfterRestParameter)}r.rest=e;return false}r.params.push(e);r.defaults.push(o);return!n(")")}function hn(l){var r,a=p();r={params:[],defaultCount:0,defaults:[],rest:null,firstRestricted:l};u("(");if(!n(")")){r.paramSet=new O;while(e<y){if(!ar(r)){break}u(",")}}u(")");if(r.defaultCount===0){r.defaults=[]}if(n(":")){r.returnType=D()}return t(a,r)}function In(){var g,h,r,e,s,o,u,f,y,b,w,S=p(),_;f=false;if(un()){m();f=true}x("function");u=false;if(n("*")){m();u=true}r=c;g=I();if(n("<")){_=C()}if(v){if(L(r.value)){E(r,i.StrictFunctionName)}}else{if(L(r.value)){s=r;o=i.StrictFunctionName}else if(ln(r.value)){s=r;o=i.StrictReservedWord}}e=hn(s);s=e.firstRestricted;if(e.message){o=e.message}y=v;b=a.yieldAllowed;a.yieldAllowed=u;w=a.awaitAllowed;a.awaitAllowed=f;h=Pn();if(v&&s){d(s,o)}if(v&&e.stricted){E(e.stricted,o)}v=y;a.yieldAllowed=b;a.awaitAllowed=w;return t(S,l.createFunctionDeclaration(g,e.params,e.defaults,h,e.rest,u,false,f,e.returnType,_))}function On(){var r,h=null,s,o,e,g,u,f,y,b,w,S=p(),_;f=false;if(un()){m();f=true}x("function");u=false;if(n("*")){m();u=true}if(!n("(")){if(!n("<")){r=c;h=I();if(v){if(L(r.value)){E(r,i.StrictFunctionName)}}else{if(L(r.value)){s=r;o=i.StrictFunctionName}else if(ln(r.value)){s=r;o=i.StrictReservedWord}}}if(n("<")){_=C()}}e=hn(s);s=e.firstRestricted;if(e.message){o=e.message}y=v;b=a.yieldAllowed;a.yieldAllowed=u;w=a.awaitAllowed;a.awaitAllowed=f;g=Pn();if(v&&s){d(s,o)}if(v&&e.stricted){E(e.stricted,o)}v=y;a.yieldAllowed=b;a.awaitAllowed=w;return t(S,l.createFunctionExpression(h,e.params,e.defaults,g,e.rest,u,false,f,e.returnType,_))}function ur(){var e,r,a=p();x("yield",!v);e=false;if(n("*")){m();e=true}r=R();return t(a,l.createYieldExpression(r,e))}function cr(){var e,n=p();V("await");e=R();return t(n,l.createAwaitExpression(e))}function An(r,s,n){var e,l,t,a;t=At(s);if(r.has(t)){e=r.get(t);if(n==="data"){a=false}else{if(n==="get"){l="set"}else{l="get"}a=e[n]===undefined&&e.data===undefined&&e[l]!==undefined}if(!a){d(s,i.IllegalDuplicateClassProperty)}}else{e={get:undefined,set:undefined,data:undefined};r.set(t,e)}e[n]=true}function pr(g,e,h,m,t){var p,f,r,y=false,o,d,a,s,v,i;r=h?tn.static:tn.prototype;i=g[r];if(m){return l.createMethodDefinition(r,"",e,Z({generator:true}),t)}a=e.type==="Identifier"&&e.name;if(a==="get"&&!n("(")){e=M();if(!t){An(i,e,"get")}u("(");u(")");if(n(":")){s=D()}return l.createMethodDefinition(r,"get",e,cn({generator:false,returnType:s}),t)}if(a==="set"&&!n("(")){e=M();if(!t){An(i,e,"set")}u("(");p=c;f=[Q()];u(")");if(n(":")){s=D()}return l.createMethodDefinition(r,"set",e,cn({params:f,generator:false,name:p,returnType:s}),t)}if(n("<")){d=C()}o=a==="async"&&!n("(");if(o){e=M()}if(!t){An(i,e,"data")}return l.createMethodDefinition(r,"",e,Z({generator:false,async:o,typeParameters:d}),t)}function dr(a,n,t,r){var e;e=D();u(";");return l.createClassProperty(n,e,t,r)}function mr(s){var r=false,l=false,a,u=p(),i=false,e;if(n(";")){m();return}if(c.value==="static"){m();i=true}if(n("*")){m();l=true}e=c;if(_("get")||_("set")){e=P()}if(e.type===o.Punctuator&&e.value==="["){r=true}a=M();if(!l&&c.value===":"){return t(u,dr(s,a,r,i))}return t(u,pr(s,a,i,l,r))}function Xn(){var r,i=[],a={},s=p();a[tn.static]=new O;a[tn.prototype]=new O;u("{");while(e<y){if(n("}")){break}r=mr(a);if(typeof r!=="undefined"){i.push(r)}}u("}");return t(s,l.createClassBody(i))}function ut(){var a,i=[],s,r;V("implements");while(e<y){s=p();a=I();if(n("<")){r=fn()}else{r=null}i.push(t(s,l.createClassImplements(a,r)));if(!n(",")){break}u(",")}return i}function ct(){var e,r,i,s=null,o,c=p(),u;x("class");if(!b("extends")&&!_("implements")&&!n("{")){e=I()}if(n("<")){u=C()}if(b("extends")){x("extends");i=a.yieldAllowed;a.yieldAllowed=false;s=Fn();if(n("<")){o=fn()}a.yieldAllowed=i}if(_("implements")){r=ut()}return t(c,l.createClassExpression(e,s,Xn(),u,o,r))}function vr(){var e,r,i,s=null,o,c=p(),u;x("class");e=I();if(n("<")){u=C()}if(b("extends")){x("extends");i=a.yieldAllowed;a.yieldAllowed=false;s=Fn();if(n("<")){o=fn()}a.yieldAllowed=i}if(_("implements")){r=ut()}return t(c,l.createClassDeclaration(e,s,Xn(),u,o,r))}function $(){var e;if(c.type===o.Keyword){switch(c.value){case"const":case"let":return Ct(c.value);case"function":return In();case"export":E({},i.IllegalExportDeclaration);return Kn();case"import":E({},i.IllegalImportDeclaration);return Qn();default:return q()}}if(_("type")&&P().type===o.Identifier){return Hr()}if(_("interface")&&P().type===o.Identifier){return $r()}if(_("declare")){e=P();if(e.type===o.Keyword){switch(e.value){case"class":return wt();case"function":return _t();case"var":return St()}}else if(e.type===o.Identifier&&e.value==="module"){return el()}}if(c.type!==o.EOF){return q()}}function pt(){if(f.isModule&&c.type===o.Keyword){switch(c.value){case"export":return Kn();case"import":return Qn()}}return $()}function Er(){var n,a=[],t,u,l;while(e<y){t=c;if(t.type!==o.StringLiteral){break}n=pt();a.push(n);if(n.expression.type!==r.Literal){break}u=s.slice(t.range[0]+1,t.range[1]-1);if(u==="use strict"){v=true;if(l){E(l,i.StrictOctalLiteral)}}else{if(!l&&t.octal){l=t}}}while(e<y){n=pt();if(typeof n==="undefined"){break}a.push(n)}return a}function wr(){var e,n=p();v=!!f.isModule;mn();e=Er();return t(n,l.createProgram(e))}function vn(t,r,n,l,i){var e;J(typeof n==="number","Comment must have valid position");if(a.lastCommentStart>=n){return}a.lastCommentStart=n;e={type:t,value:r};if(f.range){e.range=[n,l]}if(f.loc){e.loc=i}f.comments.push(e);if(f.attachComment){f.leadingComments.push(e);f.trailingComments.push(e)}}function Sr(){var t,n,r,l,o,a;t="";o=false;a=false;while(e<y){n=s[e];if(a){n=s[e++];if(T(n.charCodeAt(0))){r.end={line:h,column:e-g-1};a=false;vn("Line",t,l,e-1,r);if(n==="\r"&&s[e]==="\n"){++e}++h;g=e;t=""}else if(e>=y){a=false;t+=n;r.end={line:h,column:y-g};vn("Line",t,l,y,r)}else{t+=n}}else if(o){if(T(n.charCodeAt(0))){if(n==="\r"){++e;t+="\r"}if(n!=="\r"||s[e]==="\n"){t+=s[e];++h;++e;g=e;if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}}else{n=s[e++];if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}t+=n;if(n==="*"){n=s[e];if(n==="/"){t=t.substr(0,t.length-1);o=false;++e;r.end={line:h,column:e-g};vn("Block",t,l,e,r);t=""}}}}else if(n==="/"){n=s[e+1];if(n==="/"){r={start:{line:h,column:e-g}};l=e;e+=2;a=true;if(e>=y){r.end={line:h,column:e-g};a=false;vn("Line",t,l,e,r)}}else if(n==="*"){l=e;e+=2;o=true;r={start:{line:h,column:e-g-2}};if(e>=y){d({},i.UnexpectedToken,"ILLEGAL")}}else{break}}else if(gt(n.charCodeAt(0))){++e}else if(T(n.charCodeAt(0))){++e;if(n==="\r"&&s[e]==="\n"){++e}++h;g=e}else{break}}}Rn={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 on(e){if(e.type===r.XJSIdentifier){return e.name}if(e.type===r.XJSNamespacedName){return e.namespace.name+":"+e.name.name}if(e.type===r.XJSMemberExpression){return on(e.object)+"."+on(e.property)}S(e)}function Ir(e){return e!==92&&W(e)}function Rr(e){return e!==92&&(e===45||an(e))}function Cr(){var n,t,r="";t=e;while(e<y){n=s.charCodeAt(e);if(!Rr(n)){break}r+=s[e++]}return{type:o.XJSIdentifier,value:r,lineNumber:h,lineStart:g,range:[t,e]}}function Ar(){var t,n="",l=e,a=0,r;t=s[e];J(t==="&","Entity must start with an ampersand");e++;while(e<y&&a++<10){t=s[e++];if(t===";"){break}n+=t}if(t===";"){if(n[0]==="#"){if(n[1]==="x"){r=+("0"+n.substr(1))}else{r=+n.substr(1).replace(wn.LeadingZeros,"")}if(!isNaN(r)){return String.fromCharCode(r)}}else if(Rn[n]){return Rn[n]}}e=l+1;return"&"}function ht(l){var n,t="",r;r=e;while(e<y){n=s[e];if(l.indexOf(n)!==-1){break}if(n==="&"){t+=Ar()}else{e++;if(n==="\r"&&s[e]==="\n"){t+=n;n=s[e];e++}if(T(n.charCodeAt(0))){++h;g=e}t+=n}}return{type:o.XJSText,value:t,lineNumber:h,lineStart:g,range:[r,e]}}function Lr(){var t,n,r;n=s[e];J(n==="'"||n==='"',"String literal must starts with a quote");r=e;++e;t=ht([n]);if(n!==s[e]){d({},i.UnexpectedToken,"ILLEGAL")}++e;t.range=[r,e];return t}function Pr(){var n=s.charCodeAt(e);if(n!==123&&n!==60){return ht(["<","{"])}return U()}function nn(){var e,n=p();if(c.type!==o.XJSIdentifier){S(c)}e=m();return t(n,l.createXJSIdentifier(e.value))}function yt(){var e,n,r=p();e=nn();u(":");n=nn();return t(r,l.createXJSNamespacedName(e,n))}function Or(){var r=p(),e=nn();while(n(".")){m();e=t(r,l.createXJSMemberExpression(e,nn()))}return e}function vt(){if(P().value===":"){return yt()}if(P().value==="."){return Or()}return nn()}function Nr(){if(P().value===":"){return yt()}return nn()}function Fr(){var e,a;if(n("{")){e=xt();if(e.expression.type===r.XJSEmptyExpression){d(e,"XJS attributes must only be assigned a non-empty "+"expression")}}else if(n("<")){e=Mn()}else if(c.type===o.XJSText){a=p();e=t(a,l.createLiteral(m()))}else{d({},i.InvalidXJSAttributeValue)}return e}function Br(){var n=it();while(s.charAt(e)!=="}"){e++}return t(n,l.createXJSEmptyExpression())}function xt(){var e,r,i,s=p();r=a.inXJSChild;i=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=false;u("{");if(n("}")){e=Br()}else{e=w()}a.inXJSChild=r;a.inXJSTag=i;u("}");return t(s,l.createXJSExpressionContainer(e))}function Vr(){var e,n,r,i=p();n=a.inXJSChild;r=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=false;u("{");u("...");e=R();a.inXJSChild=n;a.inXJSTag=r;u("}");return t(i,l.createXJSSpreadAttribute(e))}function Xr(){var e,r;if(n("{")){return Vr()}r=p();e=Nr();if(n("=")){m();return t(r,l.createXJSAttribute(e,Fr()))}return t(r,l.createXJSAttribute(e))}function qr(){var e,r;if(n("{")){e=xt()}else if(c.type===o.XJSText){r=it();e=t(r,l.createLiteral(m()))}else{e=Mn()}return e}function Jr(){var e,n,r,i=p();n=a.inXJSChild;r=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=true;u("<");u("/");e=vt();a.inXJSChild=n;a.inXJSTag=r;u(">");return t(i,l.createXJSClosingElement(e))}function Gr(){var n,d,r=[],i=false,s,o,f=p();s=a.inXJSChild;o=a.inXJSTag;a.inXJSChild=false;a.inXJSTag=true;u("<");n=vt();while(e<y&&c.value!=="/"&&c.value!==">"){r.push(Xr())}a.inXJSTag=o;if(c.value==="/"){u("/");a.inXJSChild=s;u(">");i=true}else{a.inXJSChild=true;u(">")}return t(f,l.createXJSOpeningElement(n,r,i))}function Mn(){var r,s=null,u=[],o,f,m=p();o=a.inXJSChild;f=a.inXJSTag;r=Gr();if(!r.selfClosing){while(e<y){a.inXJSChild=false;if(c.value==="<"&&P().value==="/"){break}a.inXJSChild=true;u.push(qr())}a.inXJSChild=o;a.inXJSTag=f;s=Jr();if(on(s.name)!==on(r.name)){d({},i.ExpectedXJSClosingTag,on(r.name))}}if(!o&&n("<")){d(c,i.AdjacentXJSElements)}return t(m,l.createXJSElement(r,s,u))}function Hr(){var e,i=p(),r=null,a;V("type");e=I();if(n("<")){r=C()}u("=");a=j();k();return t(i,l.createTypeAlias(e,r,a))}function zr(){var a=p(),e,r=null;e=I();if(n("<")){r=fn()}return t(a,l.createInterfaceExtends(e,r))}function Et(c,f){var r,a,i=[],s,o=null;s=I();if(n("<")){o=C()}if(b("extends")){x("extends");while(e<y){i.push(zr());if(!n(",")){break}u(",")}}a=p();r=t(a,ot(f));return t(c,l.createInterface(s,o,r,i))}function $r(){var n,t,r=[],l,e=p(),a=null;V("interface");return Et(e,false)}function wt(){var n=p(),e;V("declare");x("class");e=Et(n,true);e.type=r.DeclareClass;return e}function _t(){var e,i,m=p(),s,o,c,r,f=null,d,a;V("declare");x("function");i=p();e=I();a=p();if(n("<")){f=C()}u("(");r=Vn();s=r.params;c=r.rest;u(")");u(":");o=j();d=t(a,l.createFunctionTypeAnnotation(s,o,c,f));e.typeAnnotation=t(a,l.createTypeAnnotation(d));t(i,e);k();return t(m,l.createDeclareFunction(e))}function St(){var e,n=p();V("declare");x("var");e=Q();k();return t(n,l.createDeclareVariable(e))}function el(){var r=[],s,a,f,h=p(),d;V("declare");V("module");if(c.type===o.StringLiteral){if(v&&c.octal){E(c,i.StrictOctalLiteral)}f=p();a=t(f,l.createLiteral(m()))}else{a=I()}s=p();u("{");while(e<y&&!n("}")){d=P();switch(d.value){case"class":r.push(wt());break;case"function":r.push(_t());break;case"var":r.push(St());break;default:S(c)}}u("}");return t(h,l.createDeclareModule(a,t(s,l.createBlockStatement(r))))}function nl(){var u,t,n,l,i,r;if(!a.inXJSChild){N()}u=e;t={start:{line:h,column:e-g}};n=f.advance();t.end={line:h,column:e-g};if(n.type!==o.EOF){l=[n.range[0],n.range[1]];i=s.slice(n.range[0],n.range[1]);r={type:A[n.type],value:i,range:l,loc:t};if(n.regex){r.regex={pattern:n.regex.pattern,flags:n.regex.flags}}f.tokens.push(r)}return n}function tl(){var r,l,t,n;N();r=e;l={start:{line:h,column:e-g}};t=f.scanRegExp();l.end={line:h,column:e-g};if(!f.tokenize){if(f.tokens.length>0){n=f.tokens[f.tokens.length-1];if(n.range[0]===r&&n.type==="Punctuator"){if(n.value==="/"||n.value==="/="){f.tokens.pop()}}}f.tokens.push({type:"RegularExpression",value:t.literal,regex:t.regex,range:[r,e],loc:l})}return t}function kt(){var t,e,n,r=[];for(t=0;t<f.tokens.length;++t){e=f.tokens[t];n={type:e.type,value:e.value};if(e.regex){n.regex={pattern:e.regex.pattern,flags:e.regex.flags}}if(f.range){n.range=e.range}if(f.loc){n.loc=e.loc}r.push(n)}f.tokens=r}function It(){if(f.comments){f.skipComment=N;N=Sr}if(typeof f.tokens!=="undefined"){f.advance=en;f.scanRegExp=F;en=nl;F=tl}}function Rt(){if(typeof f.skipComment==="function"){N=f.skipComment}if(typeof f.scanRegExp==="function"){en=f.advance;F=f.scanRegExp}}function il(n,t){var e,r={};for(e in n){if(n.hasOwnProperty(e)){r[e]=n[e]}}for(e in t){if(t.hasOwnProperty(e)){r[e]=t[e]}}return r}function sl(t,n){var u,i,r;u=String;if(typeof t!=="string"&&!(t instanceof String)){t=u(t)}l=kn;s=t;e=0;h=s.length>0?1:0;g=0;y=s.length;c=null;a={allowKeyword:true,allowIn:true,labelSet:new O,inFunctionBody:false,inIteration:false,inSwitch:false,lastCommentStart:-1};f={};n=n||{};n.tokens=true;f.tokens=[];f.tokenize=true;f.openParenToken=-1;f.openCurlyToken=-1;f.range=typeof n.range==="boolean"&&n.range;f.loc=typeof n.loc==="boolean"&&n.loc;if(typeof n.comment==="boolean"&&n.comment){f.comments=[]}if(typeof n.tolerant==="boolean"&&n.tolerant){f.errors=[]}It();try{mn();if(c.type===o.EOF){return f.tokens}i=m();while(c.type!==o.EOF){try{i=m()}catch(p){i=c;if(f.errors){f.errors.push(p);break}else{throw p}}}kt();r=f.tokens;if(typeof f.comments!=="undefined"){r.comments=f.comments}if(typeof f.errors!=="undefined"){r.errors=f.errors}}catch(d){throw d}finally{Rt();f={}}return r}function Nt(t,n){var r,i;i=String;if(typeof t!=="string"&&!(t instanceof String)){t=i(t)}l=kn;s=t;e=0;h=s.length>0?1:0;g=0;y=s.length;c=null;a={allowKeyword:false,allowIn:true,labelSet:new O,parenthesizedCount:0,inFunctionBody:false,inIteration:false,inSwitch:false,inXJSChild:false,inXJSTag:false,inType:false,lastCommentStart:-1,yieldAllowed:false,awaitAllowed:false};f={};if(typeof n!=="undefined"){f.range=typeof n.range==="boolean"&&n.range;f.loc=typeof n.loc==="boolean"&&n.loc;f.attachComment=typeof n.attachComment==="boolean"&&n.attachComment;if(f.loc&&n.source!==null&&n.source!==undefined){l=il(l,{postProcess:function(e){e.loc.source=i(n.source);return e}})}if(n.sourceType==="module"){f.isModule=true}if(typeof n.tokens==="boolean"&&n.tokens){f.tokens=[]}if(typeof n.comment==="boolean"&&n.comment){f.comments=[]}if(typeof n.tolerant==="boolean"&&n.tolerant){f.errors=[]}if(f.attachComment){f.range=true;f.comments=[];f.bottomRightStack=[];f.trailingComments=[];f.leadingComments=[]}}It();try{r=wr();if(typeof f.comments!=="undefined"){r.comments=f.comments}if(typeof f.tokens!=="undefined"){kt();r.tokens=f.tokens}if(typeof f.errors!=="undefined"){r.errors=f.errors}}catch(o){throw o}finally{Rt();f={}}return r}En.version="10001.1.0-dev-harmony-fb";En.tokenize=sl;En.parse=Nt;En.Syntax=function(){var e,n={};if(typeof Object.create==="function"){n=Object.create(null)}for(e in r){if(r.hasOwnProperty(e)){n[e]=r[e]}}if(typeof Object.freeze==="function"){Object.freeze(n)}return n}()})},{}],167:[function(t,b,g){var n=t("assert");var s=t("./types");var h=s.namedTypes;var m=s.builtInTypes.array;var y=s.builtInTypes.object;var o=t("./lines");var l=o.fromString;var u=o.Lines;var f=o.concat;var a=t("./util").comparePos;var c=t("private").makeUniqueKey();function p(e,n){if(!e){return}if(n){if(h.Node.check(e)&&h.SourceLocation.check(e.loc)){for(var t=n.length-1;t>=0;--t){if(a(n[t].loc.end,e.loc.start)<=0){break}}n.splice(t+1,0,e);return}}else if(e[c]){return e[c]}var r;if(m.check(e)){r=Object.keys(e)}else if(y.check(e)){r=s.getFieldNames(e)}else{return}if(!n){Object.defineProperty(e,c,{value:n=[],enumerable:false})}for(var t=0,l=r.length;t<l;++t){p(e[r[t]],n)}return n}function d(u,e){var i=p(u);var t=0,r=i.length;while(t<r){var l=t+r>>1;var n=i[l];if(a(n.loc.start,e.loc.start)<=0&&a(e.loc.end,n.loc.end)<=0){d(e.enclosingNode=n,e);return}if(a(n.loc.end,e.loc.start)<=0){var s=n;t=l+1;continue}if(a(e.loc.end,n.loc.start)<=0){var o=n;r=l;continue}throw new Error("Comment location overlaps with node location")}if(s){e.precedingNode=s}if(o){e.followingNode=o}}g.attach=function(a,i,l){if(!m.check(a)){return}var t=[];a.forEach(function(a){a.loc.lines=l;d(i,a);var s=a.precedingNode;var c=a.enclosingNode;var o=a.followingNode;if(s&&o){var f=t.length;if(f>0){var u=t[f-1];n.strictEqual(u.precedingNode===a.precedingNode,u.followingNode===a.followingNode);if(u.followingNode!==a.followingNode){r(t,l)}}t.push(a)}else if(s){r(t,l);e.forNode(s).addTrailing(a)}else if(o){r(t,l);e.forNode(o).addLeading(a)}else if(c){r(t,l);e.forNode(c).addDangling(a)}else{throw new Error("AST contains no nodes at all?")}});r(t,l)};function r(t,u){var i=t.length;if(i===0){return}var s=t[0].precedingNode;var a=t[0].followingNode;var o=a.loc.start;for(var r=i;r>0;--r){var l=t[r-1];n.strictEqual(l.precedingNode,s);n.strictEqual(l.followingNode,a);var c=u.sliceString(l.loc.end,o);if(/\S/.test(c)){break}o=l.loc.start}while(r<=i&&(l=t[r])&&l.type==="Line"&&l.loc.start.column>a.loc.start.column){++r}t.forEach(function(n,t){if(t<r){e.forNode(s).addTrailing(n)}else{e.forNode(a).addLeading(n)}});t.length=0}function e(){n.ok(this instanceof e);this.leading=[];this.dangling=[];this.trailing=[]}var i=e.prototype;e.forNode=function E(t){var n=t.comments;if(!n){Object.defineProperty(t,"comments",{value:n=new e,enumerable:false})}return n};i.forEach=function w(e,n){this.leading.forEach(e,n);this.trailing.forEach(e,n)};i.addLeading=function _(e){this.leading.push(e)};i.addDangling=function S(e){this.dangling.push(e)};i.addTrailing=function k(e){e.trailing=true;if(e.type==="Block"){this.trailing.push(e)}else{this.leading.push(e)}};function v(e,s){var r=e.loc;var a=r&&r.lines;var t=[];if(e.type==="Block"){t.push("/*",l(e.value,s),"*/")}else if(e.type==="Line"){t.push("//",l(e.value,s))
}else n.fail(e.type);if(e.trailing){t.push("\n")}else if(a instanceof u){var i=a.slice(r.end,a.skipSpaces(r.end));if(i.length===1){t.push(i)}else{t.push(new Array(i.length).join("\n"))}}else{t.push("\n")}return f(t).stripMargin(r?r.start.column:0)}function x(e,s){var t=e.loc;var a=t&&t.lines;var r=[];if(a instanceof u){var o=a.skipSpaces(t.start,true)||a.firstPos();var i=a.slice(o,t.start);if(i.length===1){r.push(i)}else{r.push(new Array(i.length).join("\n"))}}if(e.type==="Block"){r.push("/*",l(e.value,s),"*/")}else if(e.type==="Line"){r.push("//",l(e.value,s),"\n")}else n.fail(e.type);return f(r).stripMargin(t?t.start.column:0,true)}g.printComments=function(e,t,a){if(t){n.ok(t instanceof u)}else{t=l("")}if(!e||!(e.leading.length+e.trailing.length)){return t}var r=[];e.leading.forEach(function(e){r.push(v(e,a))});r.push(t);e.trailing.forEach(function(e){n.strictEqual(e.type,"Block");r.push(x(e,a))});return f(r)}},{"./lines":169,"./types":175,"./util":176,assert:110,"private":143}],168:[function(s,u,m){var t=s("assert");var l=s("./types");var e=l.namedTypes;var p=e.Node;var f=l.builtInTypes.array;var o=l.builtInTypes.number;function r(e){t.ok(this instanceof r);this.stack=[e]}var n=r.prototype;u.exports=r;r.from=function(e){if(e instanceof r){return e.copy()}if(e instanceof l.NodePath){var t=Object.create(r.prototype);var a=[e.value];for(var n;n=e.parentPath;e=n)a.push(e.name,n.value);t.stack=a.reverse();return t}return new r(e)};n.copy=function h(){var h=Object.create(r.prototype);h.stack=this.stack.slice(0);return h};n.getName=function g(){var e=this.stack;var n=e.length;if(n>1){return e[n-2]}return null};n.getValue=function y(){var e=this.stack;return e[e.length-1]};n.getNode=function v(){var t=this.stack;for(var n=t.length-1;n>=0;n-=2){var r=t[n];if(e.Node.check(r)){return r}}return null};n.getParentNode=function x(){var t=this.stack;var l=0;for(var n=t.length-1;n>=0;n-=2){var r=t[n];if(e.Node.check(r)&&l++>0){return r}}return null};n.getRootValue=function b(){var e=this.stack;if(e.length%2===0){return e[1]}return e[0]};n.call=function E(a){var e=this.stack;var r=e.length;var n=e[r-1];var i=arguments.length;for(var t=1;t<i;++t){var l=arguments[t];n=n[l];e.push(l,n)}var s=a(this);e.length=r;return s};n.each=function w(a){var n=this.stack;var r=n.length;var t=n[r-1];var i=arguments.length;for(var e=1;e<i;++e){var l=arguments[e];t=t[l];n.push(l,t)}for(var e=0;e<t.length;++e){if(e in t){n.push(e,t[e]);a(this);n.length-=2}}n.length=r};n.map=function _(i){var t=this.stack;var r=t.length;var n=t[r-1];var s=arguments.length;for(var e=1;e<s;++e){var l=arguments[e];n=n[l];t.push(l,n)}var a=new Array(n.length);for(var e=0;e<n.length;++e){if(e in n){t.push(e,n[e]);a[e]=i(this,e);t.length-=2}}t.length=r;return a};n.needsParens=function(c){var n=this.getParentNode();if(!n){return false}var l=this.getName();var r=this.getNode();if(!e.Expression.check(r)){return false}if(r.type==="Identifier"){return false}switch(r.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return n.type==="MemberExpression"&&l==="object"&&n.object===r;case"BinaryExpression":case"LogicalExpression":switch(n.type){case"CallExpression":return l==="callee"&&n.callee===r;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return l==="object"&&n.object===r;case"BinaryExpression":case"LogicalExpression":var f=n.operator;var s=i[f];var p=r.operator;var u=i[p];if(s>u){return true}if(s===u&&l==="right"){t.strictEqual(n.right,r);return true}default:return false}case"SequenceExpression":switch(n.type){case"ForStatement":return false;case"ExpressionStatement":return l!=="expression";default:return true}case"YieldExpression":switch(n.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 n.type==="MemberExpression"&&o.check(r.value)&&l==="object"&&n.object===r;case"AssignmentExpression":case"ConditionalExpression":switch(n.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return l==="callee"&&n.callee===r;case"ConditionalExpression":return l==="test"&&n.test===r;case"MemberExpression":return l==="object"&&n.object===r;default:return false}default:if(n.type==="NewExpression"&&l==="callee"&&n.callee===r){return a(r)}}if(c!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function c(n){return e.BinaryExpression.check(n)||e.LogicalExpression.check(n)}function d(n){return e.UnaryExpression.check(n)||e.SpreadElement&&e.SpreadElement.check(n)||e.SpreadProperty&&e.SpreadProperty.check(n)}var i={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(e,n){e.forEach(function(e){i[e]=n})});function a(n){if(e.CallExpression.check(n)){return true}if(f.check(n)){return n.some(a)}if(e.Node.check(n)){return l.someField(n,function(n,e){return a(e)})}return false}n.canBeFirstInStatement=function(){var n=this.getNode();return!e.FunctionExpression.check(n)&&!e.ObjectExpression.check(n)};n.firstInStatement=function(){var i=this.stack;var s,n;var l,r;for(var a=i.length-1;a>=0;a-=2){if(e.Node.check(i[a])){l=s;r=n;s=i[a-1];n=i[a]}if(!n||!r){continue}if(e.BlockStatement.check(n)&&s==="body"&&l===0){t.strictEqual(n.body[0],r);return true}if(e.ExpressionStatement.check(n)&&l==="expression"){t.strictEqual(n.expression,r);return true}if(e.SequenceExpression.check(n)&&s==="expressions"&&l===0){t.strictEqual(n.expressions[0],r);continue}if(e.CallExpression.check(n)&&l==="callee"){t.strictEqual(n.callee,r);continue}if(e.MemberExpression.check(n)&&l==="object"){t.strictEqual(n.object,r);continue}if(e.ConditionalExpression.check(n)&&l==="test"){t.strictEqual(n.test,r);continue}if(c(n)&&l==="left"){t.strictEqual(n.left,r);continue}if(e.UnaryExpression.check(n)&&!n.prefix&&l==="argument"){t.strictEqual(n.argument,r);continue}return false}return true}},{"./types":175,assert:110}],169:[function(l,_,p){var n=l("assert");var E=l("source-map");var h=l("./options").normalize;var y=l("private").makeUniqueKey();var w=l("./types");var m=w.builtInTypes.string;var g=l("./util").comparePos;var b=l("./mapping");function t(e){return e[y]}function r(l,e){n.ok(this instanceof r);n.ok(l.length>0);if(e){m.assert(e)}else{e=null}Object.defineProperty(this,y,{value:{infos:l,mappings:[],name:e,cachedSourceMap:null}});if(e){t(this).mappings.push(new b(this,{start:this.firstPos(),end:this.lastPos()}))}}p.Lines=r;var e=r.prototype;Object.defineProperties(e,{length:{get:function(){return t(this).infos.length}},name:{get:function(){return t(this).name}}});function o(e){return{line:e.line,indent:e.indent,sliceStart:e.sliceStart,sliceEnd:e.sliceEnd}}var f={};var c=f.hasOwnProperty;var v=10;function d(a,t){var e=0;var s=a.length;for(var l=0;l<s;++l){var r=a.charAt(l);if(r===" "){e+=1}else if(r===" "){n.strictEqual(typeof t,"number");n.ok(t>0);var i=Math.ceil(e/t)*t;if(i===e){e+=t}else{e=i}}else if(r==="\r"){}else{n.fail("unexpected whitespace character",r)}}return e}p.countSpaces=d;var x=/^\s*/;function u(e,t){if(e instanceof r)return e;e+="";var l=t&&t.tabWidth;var a=e.indexOf(" ")<0;var i=!t&&a&&e.length<=v;n.ok(l||a,"No tab width specified but encountered tabs in string\n"+e);if(i&&c.call(f,e))return f[e];var s=new r(e.split("\n").map(function(e){var n=x.exec(e)[0];return{line:e,indent:d(n,l),sliceStart:n.length,sliceEnd:e.length}}),h(t).sourceFileName);if(i)f[e]=s;return s}p.fromString=u;function s(e){return!/\S/.test(e)}e.toString=function(e){return this.sliceString(this.firstPos(),this.lastPos(),e)};e.getSourceMap=function(a,i){if(!a){return null}var e=this;function s(e){e=e||{};m.assert(a);e.file=a;if(i){m.assert(i);e.sourceRoot=i}return e}var r=t(e);if(r.cachedSourceMap){return s(r.cachedSourceMap.toJSON())}var l=new E.SourceMapGenerator(s());var o={};r.mappings.forEach(function(t){var r=t.sourceLines.skipSpaces(t.sourceLoc.start)||t.sourceLines.lastPos();var a=e.skipSpaces(t.targetLoc.start)||e.lastPos();while(g(r,t.sourceLoc.end)<0&&g(a,t.targetLoc.end)<0){var u=t.sourceLines.charAt(r);var f=e.charAt(a);n.strictEqual(u,f);var i=t.sourceLines.name;l.addMapping({source:i,original:{line:r.line,column:r.column},generated:{line:a.line,column:a.column}});if(!c.call(o,i)){var s=t.sourceLines.toString();l.setSourceContent(i,s);o[i]=s}e.nextPos(a,true);t.sourceLines.nextPos(r,true)}});r.cachedSourceMap=l;return l.toJSON()};e.bootstrapCharAt=function(e){n.strictEqual(typeof e,"object");n.strictEqual(typeof e.line,"number");n.strictEqual(typeof e.column,"number");var l=e.line,r=e.column,a=this.toString().split("\n"),t=a[l-1];if(typeof t==="undefined")return"";if(r===t.length&&l<a.length)return"\n";if(r>=t.length)return"";return t.charAt(r)};e.charAt=function(r){n.strictEqual(typeof r,"object");n.strictEqual(typeof r.line,"number");n.strictEqual(typeof r.column,"number");var a=r.line,s=r.column,o=t(this),u=o.infos,l=u[a-1],e=s;if(typeof l==="undefined"||e<0)return"";var i=this.getIndentAt(a);if(e<i)return" ";e+=l.sliceStart-i;if(e===l.sliceEnd&&a<this.length)return"\n";if(e>=l.sliceEnd)return"";return l.line.charAt(e)};e.stripMargin=function(e,l){if(e===0)return this;n.ok(e>0,"negative margin: "+e);if(l&&this.length===1)return this;var a=t(this);var i=new r(a.infos.map(function(n,t){if(n.line&&(t>0||!l)){n=o(n);n.indent=Math.max(0,n.indent-e)}return n}));if(a.mappings.length>0){var s=t(i).mappings;n.strictEqual(s.length,0);a.mappings.forEach(function(n){s.push(n.indent(e,l,true))})}return i};e.indent=function(e){if(e===0)return this;var l=t(this);var a=new r(l.infos.map(function(n){if(n.line){n=o(n);n.indent+=e}return n}));if(l.mappings.length>0){var i=t(a).mappings;n.strictEqual(i.length,0);l.mappings.forEach(function(n){i.push(n.indent(e))})}return a};e.indentTail=function(e){if(e===0)return this;if(this.length<2)return this;var l=t(this);var a=new r(l.infos.map(function(n,t){if(t>0&&n.line){n=o(n);n.indent+=e}return n}));if(l.mappings.length>0){var i=t(a).mappings;n.strictEqual(i.length,0);l.mappings.forEach(function(n){i.push(n.indent(e,true))})}return a};e.getIndentAt=function(e){n.ok(e>=1,"no line "+e+" (line numbers start from 1)");var r=t(this),l=r.infos[e-1];return Math.max(l.indent,0)};e.guessTabWidth=function(){var l=t(this);if(c.call(l,"cachedTabWidth")){return l.cachedTabWidth}var n=[];var i=0;for(var a=1,p=this.length;a<=p;++a){var r=l.infos[a-1];var d=r.line.slice(r.sliceStart,r.sliceEnd);if(s(d)){continue}var o=Math.abs(r.indent-i);n[o]=~~n[o]+1;i=r.indent}var u=-1;var f=2;for(var e=1;e<n.length;e+=1){if(c.call(n,e)&&n[e]>u){u=n[e];f=e}}return l.cachedTabWidth=f};e.isOnlyWhitespace=function(){return s(this.toString())};e.isPrecededOnlyByWhitespace=function(n){var a=t(this);var e=a.infos[n.line-1];var i=Math.max(e.indent,0);var r=n.column-i;if(r<=0){return true}var l=e.sliceStart;var o=Math.min(l+r,e.sliceEnd);var u=e.line.slice(l,o);return s(u)};e.getLineLength=function(e){var r=t(this),n=r.infos[e-1];return this.getIndentAt(e)+n.sliceEnd-n.sliceStart};e.nextPos=function(e,n){var t=Math.max(e.line,0),r=Math.max(e.column,0);if(r<this.getLineLength(t)){e.column+=1;return n?!!this.skipSpaces(e,false,true):true}if(t<this.length){e.line+=1;e.column=0;return n?!!this.skipSpaces(e,false,true):true}return false};e.prevPos=function(e,r){var n=e.line,t=e.column;if(t<1){n-=1;if(n<1)return false;t=this.getLineLength(n)}else{t=Math.min(t-1,this.getLineLength(n))}e.line=n;e.column=t;return r?!!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,n,t){if(e){e=t?e:{line:e.line,column:e.column}}else if(n){e=this.lastPos()}else{e=this.firstPos()}if(n){while(this.prevPos(e)){if(!s(this.charAt(e))&&this.nextPos(e)){return e}}return null}else{while(s(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 t=this.skipSpaces(this.lastPos(),true,true);n.notStrictEqual(t,null);return this.slice(e,t)};e.eachPos=function(r,n,t){var e=this.firstPos();if(n){e.line=n.line,e.column=n.column}if(t&&!this.skipSpaces(e,false,true)){return}do r.call(this,e);while(this.nextPos(e,t))};e.bootstrapSlice=function(n,t){var e=this.toString().split("\n").slice(n.line-1,t.line);e.push(e.pop().slice(0,t.column));e[0]=e[0].slice(n.column);return u(e.join("\n"))};e.slice=function(l,e){if(!e){if(!l){return this}e=this.lastPos()}var s=t(this);var a=s.infos.slice(l.line-1,e.line);if(l.line===e.line){a[0]=i(a[0],l.column,e.column)}else{n.ok(l.line<e.line);a[0]=i(a[0],l.column);a.push(i(a.pop(),0,e.column))}var o=new r(a);if(s.mappings.length>0){var u=t(o).mappings;n.strictEqual(u.length,0);s.mappings.forEach(function(t){var n=t.slice(this,l,e);if(n){u.push(n)}},this)}return o};function i(r,l,t){var a=r.sliceStart;var i=r.sliceEnd;var e=Math.max(r.indent,0);var s=e+i-a;if(typeof t==="undefined"){t=s}l=Math.max(l,0);t=Math.min(t,s);t=Math.max(t,l);if(t<e){e=t;i=a}else{i-=s-t}s=t;s-=l;if(l<e){e-=l}else{l-=e;e=0;a+=l}n.ok(e>=0);n.ok(a<=i);n.strictEqual(s,e+i-a);if(r.indent===e&&r.sliceStart===a&&r.sliceEnd===i){return r}return{line:r.line,indent:e,sliceStart:a,sliceEnd:i}}e.bootstrapSliceString=function(e,n,t){return this.slice(e,n).toString(t)};e.sliceString=function(a,n,l){if(!n){if(!a){return this}n=this.lastPos()}l=h(l);var y=t(this).infos;var c=[];var m=l.tabWidth;for(var r=a.line;r<=n.line;++r){var e=y[r-1];if(r===a.line){if(r===n.line){e=i(e,a.column,n.column)}else{e=i(e,a.column)}}else if(r===n.line){e=i(e,0,n.column)}var f=Math.max(e.indent,0);var g=e.line.slice(0,e.sliceStart);if(l.reuseWhitespace&&s(g)&&d(g,l.tabWidth)===f){c.push(e.line.slice(0,e.sliceEnd));continue}var o=0;var p=f;if(l.useTabs){o=Math.floor(f/m);p-=o*m}var u="";if(o>0){u+=new Array(o+1).join(" ")}if(p>0){u+=new Array(p+1).join(" ")}u+=e.line.slice(e.sliceStart,e.sliceEnd);c.push(u)}return c.join("\n")};e.isEmpty=function(){return this.length<2&&this.getLineLength(1)<1};e.join=function(f){var s=this;var p=t(s);var n=[];var l=[];var e;function i(t){if(t===null)return;if(e){var r=t.infos[0];var a=new Array(r.indent+1).join(" ");var i=n.length;var s=Math.max(e.indent,0)+e.sliceEnd-e.sliceStart;e.line=e.line.slice(0,e.sliceEnd)+a+r.line.slice(r.sliceStart,r.sliceEnd);e.sliceEnd=e.line.length;if(t.mappings.length>0){t.mappings.forEach(function(e){l.push(e.add(i,s))})}}else if(t.mappings.length>0){l.push.apply(l,t.mappings)}t.infos.forEach(function(t,r){if(!e||r>0){e=o(t);n.push(e)}})}function d(e,n){if(n>0)i(p);i(e)}f.map(function(n){var e=u(n);if(e.isEmpty())return null;return t(e)}).forEach(s.isEmpty()?i:d);if(n.length<1)return a;var c=new r(n);t(c).mappings=l;return c};p.concat=function(e){return a.join(e)};e.concat=function(r){var t=arguments,e=[this];e.push.apply(e,t);n.strictEqual(e.length,t.length+1);return a.join(e)};var a=u("")},{"./mapping":170,"./options":171,"./types":175,"./util":176,assert:110,"private":143,"source-map":186}],170:[function(s,f,h){var e=s("assert");var o=s("./types");var m=o.builtInTypes.string;var i=o.builtInTypes.number;var p=o.namedTypes.SourceLocation;var l=o.namedTypes.Position;var u=s("./lines");var t=s("./util").comparePos;function r(l,t,n){e.ok(this instanceof r);e.ok(l instanceof u.Lines);p.assert(t);if(n){e.ok(i.check(n.start.line)&&i.check(n.start.column)&&i.check(n.end.line)&&i.check(n.end.column))}else{n=t}Object.defineProperties(this,{sourceLines:{value:l},sourceLoc:{value:t},targetLoc:{value:n}})}var a=r.prototype;f.exports=r;a.slice=function(f,a,s){e.ok(f instanceof u.Lines);l.assert(a);if(s){l.assert(s)}else{s=f.lastPos()}var p=this.sourceLines;var o=this.sourceLoc;var i=this.targetLoc;function c(n){var r=o[n];var l=i[n];var t=a;if(n==="end"){t=s}else{e.strictEqual(n,"start")}return d(p,r,f,l,t)}if(t(a,i.start)<=0){if(t(i.end,s)<=0){i={start:n(i.start,a.line,a.column),end:n(i.end,a.line,a.column)}}else if(t(s,i.start)<=0){return null}else{o={start:o.start,end:c("end")};i={start:n(i.start,a.line,a.column),end:n(s,a.line,a.column)}}}else{if(t(i.end,a)<=0){return null}if(t(i.end,s)<=0){o={start:c("start"),end:o.end};i={start:{line:1,column:0},end:n(i.end,a.line,a.column)}}else{o={start:c("start"),end:c("end")};i={start:{line:1,column:0},end:n(s,a.line,a.column)}}}return new r(this.sourceLines,o,i)};a.add=function(e,n){return new r(this.sourceLines,this.sourceLoc,{start:c(this.targetLoc.start,e,n),end:c(this.targetLoc.end,e,n)})};function c(e,n,t){return{line:e.line+n-1,column:e.line===1?e.column+t:e.column}}a.subtract=function(e,t){return new r(this.sourceLines,this.sourceLoc,{start:n(this.targetLoc.start,e,t),end:n(this.targetLoc.end,e,t)})};function n(e,n,t){return{line:e.line-n+1,column:e.line===n?e.column-t:e.column}}a.indent=function(n,t,i){if(n===0){return this}var e=this.targetLoc;var l=e.start.line;var a=e.end.line;if(t&&l===1&&a===1){return this}e={start:e.start,end:e.end};if(!t||l>1){var s=e.start.column+n;e.start={line:l,column:i?Math.max(0,s):s}}if(!t||a>1){var o=e.end.column+n;e.end={line:a,column:i?Math.max(0,o):o}}return new r(this.sourceLines,this.sourceLoc,e)};function d(a,c,i,f,o){e.ok(a instanceof u.Lines);e.ok(i instanceof u.Lines);l.assert(c);l.assert(f);l.assert(o);var p=t(f,o);if(p===0){return c}if(p<0){var r=a.skipSpaces(c);var n=i.skipSpaces(f);var s=o.line-n.line;r.line+=s;n.line+=s;if(s>0){r.column=0;n.column=0}else{e.strictEqual(s,0)}while(t(n,o)<0&&i.nextPos(n,true)){e.ok(a.nextPos(r,true));e.strictEqual(a.charAt(r),i.charAt(n))}}else{var r=a.skipSpaces(c,true);var n=i.skipSpaces(f,true);var s=o.line-n.line;r.line+=s;n.line+=s;if(s<0){r.column=a.getLineLength(r.line);n.column=i.getLineLength(n.line)}else{e.strictEqual(s,0)}while(t(o,n)<0&&i.prevPos(n,true)){e.ok(a.prevPos(r,true));e.strictEqual(a.charAt(r),i.charAt(n))}}return r}},{"./lines":169,"./types":175,"./util":176,assert:110}],171:[function(n,l,t){var e={esprima:n("esprima-fb"),tabWidth:4,useTabs:false,reuseWhitespace:true,wrapColumn:74,sourceFileName:null,sourceMapName:null,sourceRoot:null,inputSourceMap:null,range:false,tolerant:true},r=e.hasOwnProperty;t.normalize=function(t){t=t||e;function n(n){return r.call(t,n)?t[n]:e[n]}return{tabWidth:+n("tabWidth"),useTabs:!!n("useTabs"),reuseWhitespace:!!n("reuseWhitespace"),wrapColumn:Math.max(n("wrapColumn"),0),sourceFileName:n("sourceFileName"),sourceMapName:n("sourceMapName"),sourceRoot:n("sourceRoot"),inputSourceMap:n("inputSourceMap"),esprima:n("esprima"),range:n("range"),tolerant:n("tolerant")}}},{"esprima-fb":166}],172:[function(e,h,a){var o=e("assert");var n=e("./types");var t=n.namedTypes;var i=n.builders;var s=n.builtInTypes.object;var p=n.builtInTypes.array;var m=n.builtInTypes.function;var d=e("./patcher").Patcher;var f=e("./options").normalize;var c=e("./lines").fromString;var u=e("./comments").attach;a.parse=function g(s,e){e=f(e);var n=c(s,e);var o=n.toString({tabWidth:e.tabWidth,reuseWhitespace:false,useTabs:false});var t=e.esprima.parse(o,{loc:true,range:e.range,comment:true,tolerant:e.tolerant,sourceType:"module"});var p=t.comments;delete t.comments;var l=i.file(t);l.loc={lines:n,indent:0,start:n.firstPos(),end:n.lastPos()};var a=new r(n).copy(l);u(p,a.program,n);return a};function r(e){o.ok(this instanceof r);this.lines=e;this.indent=0}var l=r.prototype;l.copy=function(e){if(p.check(e)){return e.map(this.copy,this)}if(!s.check(e)){return e}if(t.MethodDefinition&&t.MethodDefinition.check(e)||t.Property.check(e)&&(e.method||e.shorthand)){e.value.loc=null;if(t.FunctionExpression.check(e.value)){e.value.id=null}}var l=Object.create(Object.getPrototypeOf(e),{original:{value:e,configurable:false,enumerable:false,writable:true}});var n=e.loc;var i=this.indent;var o=i;if(n){if(n.start.line<1){n.start.line=1}if(n.end.line<1){n.end.line=1}if(this.lines.isPrecededOnlyByWhitespace(n.start)){o=this.indent=n.start.column}n.lines=this.lines;n.indent=o}var u=Object.keys(e);var c=u.length;for(var a=0;a<c;++a){var r=u[a];if(r==="loc"){l[r]=e[r]}else if(r==="comments"){}else{l[r]=this.copy(e[r])}}this.indent=i;if(e.comments){Object.defineProperty(l,"comments",{value:e.comments,enumerable:false})}return l}},{"./comments":167,"./lines":169,"./options":171,"./patcher":173,"./types":175,assert:110}],173:[function(a,S,h){var r=a("assert");var o=a("./lines");var e=a("./types");var k=e.getFieldValue;var l=e.namedTypes.Node;var g=e.namedTypes.Expression;var E=e.namedTypes.SourceLocation;var f=a("./util");var t=f.comparePos;var p=a("./fast-path");var n=e.builtInTypes.object;var u=e.builtInTypes.array;var v=e.builtInTypes.string;function i(e){r.ok(this instanceof i);r.ok(e instanceof o.Lines);var n=this,l=[];n.replace=function(n,e){if(v.check(e))e=o.fromString(e);l.push({lines:e,start:n.start,end:n.end})};n.get=function(n){n=n||{start:{line:1,column:0},end:{line:e.length,column:e.getLineLength(e.length)}};var a=n.start,i=[];function s(n,l){r.ok(t(n,l)<=0);i.push(e.slice(n,l))}l.sort(function(e,n){return t(e.start,n.start)}).forEach(function(e){if(t(a,e.start)>0){}else{s(a,e.start);i.push(e.lines);a=e.end}});s(a,n.end);return o.concat(i)}}h.Patcher=i;h.getReprinter=function(e){r.ok(e instanceof p);var a=e.getValue();if(!l.check(a))return;var n=a.original;var t=n&&n.loc;var s=t&&t.lines;var o=[];if(!s||!y(e,o))return;return function(r){var e=new i(s);o.forEach(function(t){var n=t.oldNode;E.assert(n.loc,true);e.replace(n.loc,r(t.newPath).indentTail(n.loc.indent))});return e.get(t).indentTail(-n.loc.indent)}};function y(a,e){var n=a.getValue();l.assert(n);var t=n.original;l.assert(t);r.deepEqual(e,[]);if(n.type!==t.type){return false}var o=new p(t);var i=s(a,o,e);if(!i){e.length=0}return i}function c(e,t,l){var r=e.getValue();var a=t.getValue();if(r===a)return true;if(u.check(r))return x(e,t,l);if(n.check(r))return b(e,t,l);return false}function x(n,t,i){var r=n.getValue();var l=t.getValue();u.assert(r);var a=r.length;if(!(u.check(l)&&l.length===a))return false;for(var e=0;e<a;++e){n.stack.push(e,r[e]);t.stack.push(e,l[e]);var s=c(n,t,i);n.stack.length-=2;t.stack.length-=2;if(!s){return false}}return true}function b(t,i,r){var a=t.getValue();n.assert(a);if(a.original===null){return false}var e=i.getValue();if(!n.check(e))return false;if(l.check(a)){if(!l.check(e)){return false}if(!e.loc){return false}if(a.type===e.type){var o=[];if(s(t,i,o)){r.push.apply(r,o)}else{r.push({oldNode:e,newPath:t.copy()})}return true}if(g.check(a)&&g.check(e)){r.push({oldNode:e,newPath:t.copy()});return true}return false}return s(t,i,r)}var m={line:1,column:0};function d(l){var i=l.getValue();var n=i.loc;var r=n&&n.lines;if(r){var e=m;e.line=n.start.line;e.column=n.start.column;while(r.prevPos(e)){var a=r.charAt(e);if(a==="("){return t(l.getRootValue().loc.start,e)<=0}if(a!==" "){return false}}}return false}function w(l){var i=l.getValue();var n=i.loc;var r=n&&n.lines;if(r){var e=m;e.line=n.end.line;e.column=n.end.column;do{var a=r.charAt(e);if(a===")"){return t(e,l.getRootValue().loc.end)<=0}if(a!==" "){return false}}while(r.nextPos(e))}return false}function _(e){return d(e)&&w(e)}function s(t,r,s){var a=t.getValue();var i=r.getValue();n.assert(a);n.assert(i);if(a.original===null){return false}if(!t.canBeFirstInStatement()&&t.firstInStatement()&&!d(r))return false;if(t.needsParens(true)&&!_(r)){return false}for(var l in f.getUnionOfKeys(a,i)){if(l==="loc")continue;t.stack.push(l,e.getFieldValue(a,l));r.stack.push(l,e.getFieldValue(i,l));var o=c(t,r,s);t.stack.length-=2;r.stack.length-=2;if(!o){return false}}return true}},{"./fast-path":168,"./lines":169,"./types":175,"./util":176,assert:110}],174:[function(l,D,j){var r=l("assert");var O=l("source-map");var L=l("./comments").printComments;var h=l("./lines");var n=h.fromString;var e=h.concat;var A=l("./options").normalize;var I=l("./patcher").getReprinter;var f=l("./types");var t=f.namedTypes;var E=f.builtInTypes.string;var P=f.builtInTypes.object;var s=l("./fast-path");var c=l("./util");function i(n,e){r.ok(this instanceof i);E.assert(n);this.code=n;if(e){P.assert(e);this.map=e}}var M=i.prototype;var g=false;M.toString=function(){if(!g){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.");g=true}return this.code};var y=new i("");function v(n){r.ok(this instanceof v);var u=n&&n.tabWidth;var e=A(n);r.notStrictEqual(e,n);e.sourceFileName=null;function l(n){r.ok(n instanceof s);return L(n.getNode().comments,a(n),e)}function a(n,i){if(i)return l(n);r.ok(n instanceof s);if(!u){var o=e.tabWidth;var a=n.getNode().loc;if(a&&a.lines&&a.lines.guessTabWidth){e.tabWidth=a.lines.guessTabWidth();var c=t(n);e.tabWidth=o;return c}}return t(n)}function t(e){var n=I(e);if(n)return x(e,n(t));return f(e)}function f(n){return b(n,e,l)}function o(n){return b(n,e,o)}this.print=function(n){if(!n){return y}var t=a(s.from(n),true);return new i(t.toString(e),c.composeSourceMaps(e.inputSourceMap,t.getSourceMap(e.sourceMapName,e.sourceRoot)))};this.printGenerically=function(n){if(!n){return y}var t=s.from(n);var r=e.reuseWhitespace;e.reuseWhitespace=false;var l=new i(o(t).toString(e));e.reuseWhitespace=r;return l}}j.Printer=v;function x(t,n){return t.needsParens()?e(["(",n,")"]):n}function b(e,n,t){r.ok(e instanceof s);return x(e,k(e,n,t))}function k(l,f,i){var c=l.getValue();if(!c){return n("")}if(typeof c==="string"){return n(c,f)}t.Node.assert(c);switch(c.type){case"File":return l.call(i,"program");case"Program":return u(l.call(function(e){return o(e,f,i)},"body"));case"EmptyStatement":return n("");case"ExpressionStatement":return e([l.call(i,"expression"),";"]);case"BinaryExpression":case"LogicalExpression":case"AssignmentExpression":return n(" ").join([l.call(i,"left"),c.operator,l.call(i,"right")]);case"MemberExpression":var s=[l.call(i,"object")];if(c.computed)s.push("[",l.call(i,"property"),"]");else s.push(".",l.call(i,"property"));return e(s);case"Path":return n(".").join(c.body);case"Identifier":return n(c.name,f);case"SpreadElement":case"SpreadElementPattern":case"SpreadProperty":case"SpreadPropertyPattern":return e(["...",l.call(i,"argument")]);case"FunctionDeclaration":case"FunctionExpression":var s=[];if(c.async)s.push("async ");s.push("function");if(c.generator)s.push("*");if(c.id)s.push(" ",l.call(i,"id"));s.push("(",m(l,f,i),") ",l.call(i,"body"));return e(s);case"ArrowFunctionExpression":var s=[];if(c.async)s.push("async ");if(c.params.length===1){s.push(l.call(i,"params",0))}else{s.push("(",m(l,f,i),")")}s.push(" => ",l.call(i,"body"));return e(s);case"MethodDefinition":var s=[];if(c.static){s.push("static ")}s.push(w(l,f,i));return e(s);case"YieldExpression":var s=["yield"];if(c.delegate)s.push("*");if(c.argument)s.push(" ",l.call(i,"argument"));return e(s);case"AwaitExpression":var s=["await"];if(c.all)s.push("*");if(c.argument)s.push(" ",l.call(i,"argument"));return e(s);case"ModuleDeclaration":var s=["module",l.call(i,"id")];if(c.source){r.ok(!c.body);s.push("from",l.call(i,"source"))}else{s.push(l.call(i,"body"))}return n(" ").join(s);case"ImportSpecifier":case"ExportSpecifier":var s=[l.call(i,"id")];if(c.name)s.push(" as ",l.call(i,"name"));return e(s);case"ExportBatchSpecifier":return n("*");case"ImportNamespaceSpecifier":return e(["* as ",l.call(i,"id")]);case"ImportDefaultSpecifier":return l.call(i,"id");case"ExportDeclaration":var s=["export"];if(c["default"]){s.push(" default")}else if(c.specifiers&&c.specifiers.length>0){if(c.specifiers.length===1&&c.specifiers[0].type==="ExportBatchSpecifier"){s.push(" *")}else{s.push(" { ",n(", ").join(l.map(i,"specifiers"))," }")}if(c.source)s.push(" from ",l.call(i,"source"));s.push(";");return e(s)}if(c.declaration){if(!t.Node.check(c.declaration)){console.log(JSON.stringify(c,null,2))}var D=l.call(i,"declaration");s.push(" ",D);if(d(D)!==";"){s.push(";")}}return e(s);case"ImportDeclaration":var s=["import "];if(c.specifiers&&c.specifiers.length>0){var y=false;l.each(function(e){var l=e.getName();if(l>0){s.push(", ")}var n=e.getValue();if(t.ImportDefaultSpecifier.check(n)||t.ImportNamespaceSpecifier.check(n)){r.strictEqual(y,false)}else{t.ImportSpecifier.assert(n);if(!y){y=true;s.push("{")}}s.push(i(e))},"specifiers");if(y){s.push("}")}s.push(" from ")}s.push(l.call(i,"source"),";");return e(s);case"BlockStatement":var O=l.call(function(e){return o(e,f,i)},"body");if(O.isEmpty()){return n("{}")}return e(["{\n",O.indent(f.tabWidth),"\n}"]);case"ReturnStatement":var s=["return"];if(c.argument){var E=l.call(i,"argument");if(E.length>1&&t.XJSElement&&t.XJSElement.check(c.argument)){s.push(" (\n",E.indent(f.tabWidth),"\n)")}else{s.push(" ",E)}}s.push(";");return e(s);case"CallExpression":return e([l.call(i,"callee"),_(l,f,i)]);case"ObjectExpression":case"ObjectPattern":var R=false,v=c.properties.length,s=[v>0?"{\n":"{"];l.map(function(e){var r=e.getName();var l=e.getValue();var t=i(e).indent(f.tabWidth);var n=t.length>1;if(n&&R){s.push("\n")}s.push(t);if(r<v-1){s.push(n?",\n\n":",\n");R=!n}},"properties");s.push(v>0?"\n}":"}");return e(s);case"PropertyPattern":return e([l.call(i,"key"),": ",l.call(i,"pattern")]);case"Property":if(c.method||c.kind==="get"||c.kind==="set"){return w(l,f,i)}if(c.shorthand){return l.call(i,"key")}return e([l.call(i,"key"),": ",l.call(i,"value")]);case"ArrayExpression":case"ArrayPattern":var X=c.elements,v=X.length,s=["["];l.each(function(e){var n=e.getName();var t=e.getValue();if(!t){s.push(",")}else{if(n>0)s.push(" ");s.push(i(e));if(n<v-1)s.push(",")}},"elements");s.push("]");return e(s);case"SequenceExpression":return n(", ").join(l.map(i,"expressions"));case"ThisExpression":return n("this");case"Literal":if(typeof c.value!=="string")return n(c.value,f);case"ModuleSpecifier":return n(T(c),f);case"UnaryExpression":var s=[c.operator];if(/[a-z]$/.test(c.operator))s.push(" ");s.push(l.call(i,"argument"));return e(s);case"UpdateExpression":var s=[l.call(i,"argument"),c.operator];if(c.prefix)s.reverse();return e(s);case"ConditionalExpression":return e(["(",l.call(i,"test")," ? ",l.call(i,"consequent")," : ",l.call(i,"alternate"),")"]);case"NewExpression":var s=["new ",l.call(i,"callee")];var N=c.arguments;if(N){s.push(_(l,f,i))}return e(s);case"VariableDeclaration":var s=[c.kind," "];var I=0;var x=l.map(function(n){var e=i(n);I=Math.max(e.length,I);return e},"declarations");if(I===1){s.push(n(", ").join(x))}else if(x.length>1){s.push(n(",\n").join(x).indentTail(c.kind.length+1))}else{s.push(x[0])}var b=l.getParentNode();if(!t.ForStatement.check(b)&&!t.ForInStatement.check(b)&&!(t.ForOfStatement&&t.ForOfStatement.check(b))){s.push(";")}return e(s);case"VariableDeclarator":return c.init?n(" = ").join([l.call(i,"id"),l.call(i,"init")]):l.call(i,"id");case"WithStatement":return e(["with (",l.call(i,"object"),") ",l.call(i,"body")]);case"IfStatement":var C=a(l.call(i,"consequent"),f),s=["if (",l.call(i,"test"),")",C];if(c.alternate)s.push(S(C)?" else":"\nelse",a(l.call(i,"alternate"),f));return e(s);case"ForStatement":var A=l.call(i,"init"),V=A.length>1?";\n":"; ",L="for (",F=n(V).join([A,l.call(i,"test"),l.call(i,"update")]).indentTail(L.length),P=e([L,F,")"]),k=a(l.call(i,"body"),f),s=[P];if(P.length>1){s.push("\n");k=k.trimLeft()}s.push(k);return e(s);case"WhileStatement":return e(["while (",l.call(i,"test"),")",a(l.call(i,"body"),f)]);case"ForInStatement":return e([c.each?"for each (":"for (",l.call(i,"left")," in ",l.call(i,"right"),")",a(l.call(i,"body"),f)]);case"ForOfStatement":return e(["for (",l.call(i,"left")," of ",l.call(i,"right"),")",a(l.call(i,"body"),f)]);
case"DoWhileStatement":var j=e(["do",a(l.call(i,"body"),f)]),s=[j];if(S(j))s.push(" while");else s.push("\nwhile");s.push(" (",l.call(i,"test"),");");return e(s);case"BreakStatement":var s=["break"];if(c.label)s.push(" ",l.call(i,"label"));s.push(";");return e(s);case"ContinueStatement":var s=["continue"];if(c.label)s.push(" ",l.call(i,"label"));s.push(";");return e(s);case"LabeledStatement":return e([l.call(i,"label"),":\n",l.call(i,"body")]);case"TryStatement":var s=["try ",l.call(i,"block")];l.each(function(e){s.push(" ",i(e))},"handlers");if(c.finalizer)s.push(" finally ",l.call(i,"finalizer"));return e(s);case"CatchClause":var s=["catch (",l.call(i,"param")];if(c.guard)s.push(" if ",l.call(i,"guard"));s.push(") ",l.call(i,"body"));return e(s);case"ThrowStatement":return e(["throw ",l.call(i,"argument"),";"]);case"SwitchStatement":return e(["switch (",l.call(i,"discriminant"),") {\n",n("\n").join(l.map(i,"cases")),"\n}"]);case"SwitchCase":var s=[];if(c.test)s.push("case ",l.call(i,"test"),":");else s.push("default:");if(c.consequent.length>0){s.push("\n",l.call(function(e){return o(e,f,i)},"consequent").indent(f.tabWidth))}return e(s);case"DebuggerStatement":return n("debugger;");case"XJSAttribute":var s=[l.call(i,"name")];if(c.value)s.push("=",l.call(i,"value"));return e(s);case"XJSIdentifier":return n(c.name,f);case"XJSNamespacedName":return n(":").join([l.call(i,"namespace"),l.call(i,"name")]);case"XJSMemberExpression":return n(".").join([l.call(i,"object"),l.call(i,"property")]);case"XJSSpreadAttribute":return e(["{...",l.call(i,"argument"),"}"]);case"XJSExpressionContainer":return e(["{",l.call(i,"expression"),"}"]);case"XJSElement":var M=l.call(i,"openingElement");if(c.openingElement.selfClosing){r.ok(!c.closingElement);return M}var B=e(l.map(function(n){var e=n.getValue();if(t.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 i(n)},"children")).indentTail(f.tabWidth);var U=l.call(i,"closingElement");return e([M,B,U]);case"XJSOpeningElement":var s=["<",l.call(i,"name")];var h=[];l.each(function(e){h.push(" ",i(e))},"attributes");var g=e(h);var q=g.length>1||g.getLineLength(1)>f.wrapColumn;if(q){h.forEach(function(n,e){if(n===" "){r.strictEqual(e%2,0);h[e]="\n"}});g=e(h).indentTail(f.tabWidth)}s.push(g,c.selfClosing?" />":">");return e(s);case"XJSClosingElement":return e(["</",l.call(i,"name"),">"]);case"XJSText":return n(c.value,f);case"XJSEmptyExpression":return n("");case"TypeAnnotatedIdentifier":return e([l.call(i,"annotation")," ",l.call(i,"identifier")]);case"ClassBody":if(c.body.length===0){return n("{}")}return e(["{\n",l.call(function(e){return o(e,f,i)},"body").indent(f.tabWidth),"\n}"]);case"ClassPropertyDefinition":var s=["static ",l.call(i,"definition")];if(!t.MethodDefinition.check(c.definition))s.push(";");return e(s);case"ClassProperty":return e([l.call(i,"id"),";"]);case"ClassDeclaration":case"ClassExpression":var s=["class"];if(c.id)s.push(" ",l.call(i,"id"));if(c.superClass)s.push(" extends ",l.call(i,"superClass"));s.push(" ",l.call(i,"body"));return e(s);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(c.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(c.type))}return p}function o(l,s,o){var a=t.ClassBody&&t.ClassBody.check(l.getParentNode());var n=[];l.each(function(r){var l=r.getName();var e=r.getValue();if(!e){return}if(e.type==="EmptyStatement"){return}if(!a){t.Statement.assert(e)}n.push({node:e,printed:o(r)})});var i=null;var c=n.length;var r=[];n.forEach(function(h,g){var o=h.printed;var f=h.node;var y=true;var v=o.length>1;var w=g>0;var m=g<c-1;var p;var e;if(a){if(t.MethodDefinition.check(f)||t.ClassPropertyDefinition.check(f)&&t.MethodDefinition.check(f.definition)){y=false}}if(y){o=u(o)}var n=s.reuseWhitespace&&R(f);var l=n&&n.lines;if(w){if(l){var x=l.skipSpaces(n.start,true);var b=x?x.line:1;var E=n.start.line-b;p=Array(E+1).join("\n")}else{p=v?"\n\n":"\n"}}else{p=""}if(m){if(l){var d=l.skipSpaces(n.end);var _=d?d.line:l.length;var S=_-n.end.line;e=Array(S+1).join("\n")}else{e=v?"\n\n":"\n"}}else{e=""}r.push(C(i,p),o);if(m){i=e}else if(e){r.push(e)}});return e(r)}function R(e){if(!e.loc){return null}if(!e.comments){return e.loc}var n=e.loc.start;var t=e.loc.end;e.comments.forEach(function(e){if(e.loc){if(c.comparePos(e.loc.start,n)<0){n=e.loc.start}if(c.comparePos(t,e.loc.end)<0){t=e.loc.end}}});return{lines:e.loc.lines,start:n,end:t}}function C(e,t){if(!e&&!t){return n("")}if(!e){return n(t)}if(!t){return n(e)}var r=n(e);var l=n(t);if(l.length>r.length){return l}return r}function w(a,o,s){var i=a.getNode();var n=i.kind;var l=[];t.FunctionExpression.assert(i.value);if(i.value.async){l.push("async ")}if(!n||n==="init"){if(i.value.generator){l.push("*")}}else{r.ok(n==="get"||n==="set");l.push(n," ")}l.push(a.call(s,"key"),"(",a.call(function(e){return m(e,o,s)},"value"),") ",a.call(s,"value","body"));return e(l)}function _(a,r,i){var l=a.map(i,"arguments");var t=n(", ").join(l);if(t.getLineLength(1)>r.wrapColumn){t=n(",\n").join(l);return e(["(\n",t.indent(r.tabWidth),"\n)"])}return e(["(",t,")"])}function m(a,o,i){var s=a.getValue();t.Function.assert(s);var r=a.map(i,"params");if(s.defaults){a.each(function(n){var t=n.getName();var l=r[t];if(l&&n.getValue()){r[t]=e([l,"=",i(n)])}},"defaults")}if(s.rest){r.push(e(["...",a.call(i,"rest")]))}var l=n(", ").join(r);if(l.length>1||l.getLineLength(1)>o.wrapColumn){l=n(",\n").join(r);return e(["\n",l.indent(o.tabWidth)])}return l}function a(n,t){if(n.length>1)return e([" ",n]);return e(["\n",u(n).indent(t.tabWidth)])}function d(e){var n=e.lastPos();do{var t=e.charAt(n);if(/\S/.test(t))return t}while(e.prevPos(n))}function S(e){return d(e)==="}"}function T(e){t.Literal.assert(e);E.assert(e.value);return JSON.stringify(e.value)}function u(n){var t=d(n);if(!t||"\n};".indexOf(t)<0)return e([n,";"]);return n}},{"./comments":167,"./fast-path":168,"./lines":169,"./options":171,"./patcher":173,"./types":175,"./util":176,assert:110,"source-map":186}],175:[function(t,r,l){var e=t("ast-types");var n=e.Type.def;n("File").bases("Node").build("program").field("program",n("Program"));e.finalize();r.exports=e},{"ast-types":108}],176:[function(e,u,n){var c=e("assert");var o=e("./types").getFieldValue;var t=e("source-map");var r=t.SourceMapConsumer;var l=t.SourceMapGenerator;var a=Object.prototype.hasOwnProperty;function i(){var t={};var l=arguments.length;for(var e=0;e<l;++e){var r=Object.keys(arguments[e]);var a=r.length;for(var n=0;n<a;++n){t[r[n]]=true}}return t}n.getUnionOfKeys=i;function s(e,n){return e.line-n.line||e.column-n.column}n.comparePos=s;n.composeSourceMaps=function(n,e){if(n){if(!e){return n}}else{return e||null}var i=new r(n);var o=new r(e);var t=new l({file:e.file,sourceRoot:e.sourceRoot});var s={};o.eachMapping(function(n){var r=i.originalPositionFor({line:n.originalLine,column:n.originalColumn});var e=r.source;if(e===null){return}t.addMapping({source:e,original:{line:r.line,column:r.column},generated:{line:n.generatedLine,column:n.generatedColumn},name:n.name});var l=i.sourceContentFor(e);if(l&&!a.call(s,e)){s[e]=l;t.setSourceContent(e,l)}});return t.toJSON()}},{"./types":175,assert:110,"source-map":186}],177:[function(e,t,n){(function(t){var r=e("./lib/types");var l=e("./lib/parser").parse;var a=e("./lib/printer").Printer;function i(e,n){return new a(n).print(e)}function s(e,n){return new a(n).printGenerically(e)}function o(e,n){return u(t.argv[2],e,n)}function u(n,t,r){e("fs").readFile(n,"utf-8",function(e,n){if(e){console.error(e);return}f(n,t,r)})}function c(e){t.stdout.write(e)}function f(n,t,e){var r=e&&e.writeback||c;t(l(n,e),function(n){r(i(n,e).code)})}Object.defineProperties(n,{parse:{enumerable:true,value:l},visit:{enumerable:true,value:r.visit},print:{enumerable:true,value:i},prettyPrint:{enumerable:false,value:s},types:{enumerable:false,value:r},run:{enumerable:false,value:o}})}).call(this,e("_process"))},{"./lib/parser":172,"./lib/printer":174,"./lib/types":175,_process:119,fs:109}],178:[function(e,n,t){(function(l){var a=e("stream");t=n.exports=r;r.through=r;function r(t,r,s){t=t||function(e){this.queue(e)};r=r||function(){this.queue(null)};var i=false,o=false,n=[],u=false;var e=new a;e.readable=e.writable=true;e.paused=false;e.autoDestroy=!(s&&s.autoDestroy===false);e.write=function(n){t.call(this,n);return!e.paused};function c(){while(n.length&&!e.paused){var t=n.shift();if(null===t)return e.emit("end");else e.emit("data",t)}}e.queue=e.push=function(t){if(u)return e;if(t==null)u=true;n.push(t);c();return e};e.on("end",function(){e.readable=false;if(!e.writable&&e.autoDestroy)l.nextTick(function(){e.destroy()})});function f(){e.writable=false;r.call(e);if(!e.readable&&e.autoDestroy)e.destroy()}e.end=function(n){if(i)return;i=true;if(arguments.length)e.write(n);f();return e};e.destroy=function(){if(o)return;o=true;i=true;n.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")}c();if(!e.paused)e.emit("drain");return e};return e}}).call(this,e("_process"))},{_process:119,stream:131}],179:[function(n,e,t){(function(n){!function(h){"use strict";var r=Object.prototype.hasOwnProperty;var t;var d=typeof Symbol==="function"&&Symbol.iterator||"@@iterator";var m=typeof e==="object";var n=h.regeneratorRuntime;if(n){if(m){e.exports=n}return}n=h.regeneratorRuntime=m?e.exports:{};function b(e,n,t,r){return new y(e,n,t||null,r||[])}n.wrap=b;function f(e,n,t){try{return{type:"normal",arg:e.call(n,t)}}catch(r){return{type:"throw",arg:r}}}var c="suspendedStart";var u="suspendedYield";var g="executing";var s="completed";var o={};function i(){}function a(){}var l=a.prototype=y.prototype;i.prototype=l.constructor=a;a.constructor=i;i.displayName="GeneratorFunction";n.isGeneratorFunction=function(n){var e=typeof n==="function"&&n.constructor;return e?e===i||(e.displayName||e.name)==="GeneratorFunction":false};n.mark=function(e){e.__proto__=a;e.prototype=Object.create(l);return e};n.async=function(e,n,t,r){return new Promise(function(s,o){var l=b(e,n,t,r);var a=i.bind(l.next);var u=i.bind(l["throw"]);function i(t){var e=f(this,null,t);if(e.type==="throw"){o(e.arg);return}var n=e.arg;if(n.done){s(n.value)}else{Promise.resolve(n.value).then(a,u)}}a()})};function y(i,a,d,m){var r=a?Object.create(a.prototype):this;var e=new p(m);var n=c;function l(l,r){if(n===g){throw new Error("Generator is already running")}if(n===s){return E()}while(true){var p=e.delegate;if(p){var a=f(p.iterator[l],p.iterator,r);if(a.type==="throw"){e.delegate=null;l="throw";r=a.arg;continue}l="next";r=t;var m=a.arg;if(m.done){e[p.resultName]=m.value;e.next=p.nextLoc}else{n=u;return m}e.delegate=null}if(l==="next"){if(n===c&&typeof r!=="undefined"){throw new TypeError("attempt to send "+JSON.stringify(r)+" to newborn generator")}if(n===u){e.sent=r}else{delete e.sent}}else if(l==="throw"){if(n===c){n=s;throw r}if(e.dispatchException(r)){l="next";r=t}}else if(l==="return"){e.abrupt("return",r)}n=g;var a=f(i,d,e);if(a.type==="normal"){n=e.done?s:u;var m={value:a.arg,done:e.done};if(a.arg===o){if(e.delegate&&l==="next"){r=t}}else{return m}}else if(a.type==="throw"){n=s;if(l==="next"){e.dispatchException(a.arg)}else{r=a.arg}}}}r.next=l.bind(r,"next");r["throw"]=l.bind(r,"throw");r["return"]=l.bind(r,"return");return r}l[d]=function(){return this};l.toString=function(){return"[object Generator]"};function w(e){var n={tryLoc:e[0]};if(1 in e){n.catchLoc=e[1]}if(2 in e){n.finallyLoc=e[2]}this.tryEntries.push(n)}function x(n,t){var e=n.completion||{};e.type=t===0?"normal":"return";delete e.arg;n.completion=e}function p(e){this.tryEntries=[{tryLoc:"root"}];e.forEach(w,this);this.reset()}n.keys=function(n){var e=[];for(var t in n){e.push(t)}e.reverse();return function r(){while(e.length){var t=e.pop();if(t in n){r.value=t;r.done=false;return r}}r.done=true;return r}};function v(e){if(e){var l=e[d];if(l){return l.call(e)}if(typeof e.next==="function"){return e}if(!isNaN(e.length)){var n=-1,a=function i(){while(++n<e.length){if(r.call(e,n)){i.value=e[n];i.done=false;return i}}i.value=t;i.done=true;return i};return a.next=a}}return{next:E}}n.values=v;function E(){return{value:t,done:true}}p.prototype={constructor:p,reset:function(){this.prev=0;this.next=0;this.sent=t;this.done=false;this.delegate=null;this.tryEntries.forEach(x);for(var e=0,n;r.call(this,n="t"+e)||e<20;++e){this[n]=null}},stop:function(){this.done=true;var n=this.tryEntries[0];var e=n.completion;if(e.type==="throw"){throw e.arg}return this.rval},dispatchException:function(l){if(this.done){throw l}var o=this;function n(e,n){a.type="throw";a.arg=l;o.next=e;return!!n}for(var t=this.tryEntries.length-1;t>=0;--t){var e=this.tryEntries[t];var a=e.completion;if(e.tryLoc==="root"){return n("end")}if(e.tryLoc<=this.prev){var i=r.call(e,"catchLoc");var s=r.call(e,"finallyLoc");if(i&&s){if(this.prev<e.catchLoc){return n(e.catchLoc,true)}else if(this.prev<e.finallyLoc){return n(e.finallyLoc)}}else if(i){if(this.prev<e.catchLoc){return n(e.catchLoc,true)}}else if(s){if(this.prev<e.finallyLoc){return n(e.finallyLoc)}}else{throw new Error("try statement without catch or finally")}}}},_findFinallyEntry:function(t){for(var n=this.tryEntries.length-1;n>=0;--n){var e=this.tryEntries[n];if(e.tryLoc<=this.prev&&r.call(e,"finallyLoc")&&(e.finallyLoc===t||this.prev<e.finallyLoc)){return e}}},abrupt:function(t,r){var e=this._findFinallyEntry();var n=e?e.completion:{};n.type=t;n.arg=r;if(e){this.next=e.finallyLoc}else{this.complete(n)}return o},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 o},finish:function(e){var n=this._findFinallyEntry(e);return this.complete(n.completion)},"catch":function(r){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===r){var t=n.completion;if(t.type==="throw"){var l=t.arg;x(n,e)}return l}}throw new Error("illegal catch attempt")},delegateYield:function(e,n,t){this.delegate={iterator:v(e),resultName:n,nextLoc:t};return o}}}(typeof n==="object"?n:typeof window==="object"?window:this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],180:[function(t,r,n){var e=t("regenerate");n.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)};n.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)};n.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:182}],181:[function(n,e,t){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}},{}],182:[function(t,e,n){(function(t){(function(_){var h=typeof n=="object"&&n;var S=typeof e=="object"&&e&&e.exports==h&&e;var c=typeof t=="object"&&t;if(c.global===c||c.window===c){_=c}var f={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 r=55296;var l=56319;var o=56320;var v=57343;var X=/\\x00([^0123456789]|$)/g;var R={};var U=R.hasOwnProperty;var F=function(t,n){var e;for(e in n){if(U.call(n,e)){t[e]=n[e]}}return t};var g=function(n,t){var e=-1;var r=n.length;while(++e<r){t(n[e],e)}};var j=R.toString;var T=function(e){return j.call(e)=="[object Array]"};var s=function(e){return typeof e=="number"||j.call(e)=="[object Number]"};var V="0000";var D=function(t,n){var e=String(t);return e.length<n?(V+e).slice(-n):e};var w=function(e){return Number(e).toString(16).toUpperCase()};var E=[].slice;var Y=function(a){var l=-1;var i=a.length;var s=i-1;var n=[];var r=true;var e;var t=0;while(++l<i){e=a[l];if(r){n.push(e);t=e;r=false}else{if(e==t+1){if(l!=s){t=e;continue}else{r=true;n.push(e+1)}}else{n.push(t+1,e);t=e}}}if(!r){n.push(e+1)}return n};var k=function(e,n){var t=0;var r;var l;var a=e.length;while(t<a){r=e[t];l=e[t+1];if(n>=r&&n<l){if(n==r){if(l==r+1){e.splice(t,2);return e}else{e[t]=n+1;return e}}else if(n==l-1){e[t+1]=n;return e}else{e.splice(t,2,r,n,n+1,l);return e}}t+=2}return e};var I=function(e,r,t){if(t<r){throw Error(f.rangeOrder)}var n=0;var l;var a;while(n<e.length){l=e[n];a=e[n+1]-1;if(l>t){return e}if(r<=l&&t>=a){e.splice(n,2);continue}if(r>=l&&t<a){if(r==l){e[n]=t+1;e[n+1]=a+1;return e}e.splice(n,2,l,r,t+1,a+1);return e}if(r>=l&&r<=a){e[n+1]=r}else if(t>=l&&t<=a){e[n]=t+1;return e}n+=2}return e};var p=function(e,n){var t=0;var r;var l;var a=null;var i=e.length;if(n<0||n>1114111){throw RangeError(f.codePointRange)}while(t<i){r=e[t];l=e[t+1];if(n>=r&&n<l){return e}if(n==r-1){e[t]=n;return e}if(r>n){e.splice(a!=null?a+2:0,0,n,n+1);return e}if(n==l){if(n+1==e[t+2]){e.splice(t,4,r,e[t+3]);return e}e[t+1]=n+1;return e}a=t;t+=2}e.push(n,n+1);return e};var C=function(a,r){var n=0;var t;var l;var e=a.slice();var i=r.length;while(n<i){t=r[n];l=r[n+1]-1;if(t==l){e=p(e,t)}else{e=d(e,t,l)}n+=2}return e};var B=function(a,r){var n=0;var t;var l;var e=a.slice();var i=r.length;while(n<i){t=r[n];l=r[n+1]-1;if(t==l){e=k(e,t)}else{e=I(e,t,l)}n+=2}return e};var d=function(e,n,t){if(t<n){throw Error(f.rangeOrder)}if(n<0||n>1114111||t<0||t>1114111){throw RangeError(f.codePointRange)}var r=0;var l;var a;var i=false;var s=e.length;while(r<s){l=e[r];a=e[r+1];if(i){if(l==t+1){e.splice(r-1,2);return e}if(l>t){return e}if(l>=n&&l<=t){if(a>n&&a-1<=t){e.splice(r,2);r-=2}else{e.splice(r-1,2);r-=2}}}else if(l==t+1){e[r]=n;return e}else if(l>t){e.splice(r,0,n,t+1);return e}else if(n>=l&&n<a&&t+1<=a){return e}else if(n>=l&&n<a||a==n){e[r+1]=t+1;i=true}else if(n<=l&&t+1>=a){e[r]=n;e[r+1]=t+1;i=true}r+=2}if(!i){e.push(n,t+1)}return e};var L=function(n,t){var e=0;var r;var l;var a=n.length;while(e<a){r=n[e];l=n[e+1];if(t>=r&&t<l){return true}e+=2}return false};var J=function(l,t){var e=0;var a=t.length;var n;var r=[];while(e<a){n=t[e];if(L(l,n)){r.push(n)}++e}return Y(r)};var y=function(e){return!e.length};var b=function(e){return e.length==2&&e[0]+1==e[1]};var O=function(t){var e=0;var n;var r;var l=[];var a=t.length;while(e<a){n=t[e];r=t[e+1];while(n<r){l.push(n);++n}e+=2}return l};var $=Math.floor;var M=function(e){return parseInt($((e-65536)/1024)+r,10)};var P=function(e){return parseInt((e-65536)%1024+o,10)};var A=String.fromCharCode;var u=function(e){var n;if(e==9){n="\\t"}else if(e==10){n="\\n"}else if(e==12){n="\\f"}else if(e==13){n="\\r"}else if(e==92){n="\\\\"}else if(e==36||e>=40&&e<=43||e==45||e==46||e==63||e>=91&&e<=94||e>=123&&e<=125){n="\\"+A(e)}else if(e>=32&&e<=126){n=A(e)}else if(e<=255){n="\\x"+D(w(e),2)}else{n="\\u"+D(w(e),4)}return n};var i=function(n){var a=n.length;var e=n.charCodeAt(0);var t;if(e>=r&&e<=l&&a>1){t=n.charCodeAt(1);return(e-r)*1024+t-o+65536}return e};var m=function(n){var r="";var l=0;var e;var t;var a=n.length;if(b(n)){return u(n[0])}while(l<a){e=n[l];t=n[l+1]-1;if(e==t){r+=u(e)}else if(e+1==t){r+=u(e)+u(t)}else{r+=u(e)+"-"+u(t)}l+=2}return"["+r+"]"};var q=function(s){var a=[];var t=[];var o=[];var i=0;var e;var n;var u=s.length;while(i<u){e=s[i];n=s[i+1]-1;if(e<=65535&&n<=65535){if(e>=r&&e<=l){if(n<=l){a.push(e,n+1)}else{a.push(e,l+1);t.push(l+1,n+1)}}else if(n>=r&&n<=l){t.push(e,r);a.push(r,n+1)}else if(e<r&&n>l){t.push(e,r,l+1,n+1);a.push(r,l+1)}else{t.push(e,n+1)}}else if(e<=65535&&n>65535){if(e>=r&&e<=l){a.push(e,l+1);t.push(l+1,65535+1)}else if(e<r){t.push(e,r,l+1,65535+1);a.push(r,l+1)}else{t.push(e,65535+1)}o.push(65535+1,n+1)}else{o.push(e,n+1)}i+=2}return{loneHighSurrogates:a,bmp:t,astral:o}};var N=function(i){var u=[];var t=[];var c=false;var n;var e;var a;var o;var s;var l;var r=-1;var f=i.length;while(++r<f){n=i[r];e=i[r+1];if(!e){u.push(n);continue}a=n[0];o=n[1];s=e[0];l=e[1];t=o;while(s&&a[0]==s[0]&&a[1]==s[1]){if(b(l)){t=p(t,l[0])}else{t=d(t,l[0],l[1]-1)}++r;n=i[r];a=n[0];o=n[1];e=i[r+1];s=e&&e[0];l=e&&e[1];c=true}u.push([a,c?t:o]);c=false}return G(u)};var G=function(e){if(e.length==1){return e}var l=-1;var n=-1;while(++l<e.length){var t=e[l];var a=t[1];var c=a[0];var o=a[1];n=l;while(++n<e.length){var r=e[n];var i=r[1];var u=i[0];var s=i[1];if(c==u&&o==s){if(b(r[0])){t[0]=p(t[0],r[0][0])}else{t[0]=d(t[0],r[0][0],r[0][1]-1)}e.splice(n,1);--n}}}return e};var W=function(l){if(!l.length){return[]}var s=0;var c;var u;var e;var a;var d=0;var p=0;var y=[];var n;var r;var t=[];var m=l.length;var g=[];while(s<m){c=l[s];u=l[s+1]-1;e=M(c);a=P(c);n=M(u);r=P(u);var h=a==o;var f=r==v;var i=false;if(e==n||h&&f){t.push([[e,n+1],[a,r+1]]);i=true}else{t.push([[e,e+1],[a,v+1]])}if(!i&&e+1<n){if(f){t.push([[e+1,n+1],[o,r+1]]);i=true}else{t.push([[e+1,n],[o,v+1]])}}if(!i){t.push([[n,n+1],[o,r+1]])}d=e;p=n;s+=2}return N(t)};var H=function(n){var e=[];g(n,function(n){var t=n[0];var r=n[1];e.push(m(t)+m(r))});return e.join("|")};var z=function(s){var e=[];var n=q(s);var r=n.loneHighSurrogates;var t=n.bmp;var o=n.astral;var l=!y(n.astral);var a=!y(r);var i=W(o);if(!l&&a){t=C(t,r)}if(!y(t)){e.push(m(t))}if(i.length){e.push(H(i))}if(l&&a){e.push(m(r))}return e.join("|")};var a=function(e){if(arguments.length>1){e=E.call(arguments)}if(this instanceof a){this.data=[];return e?this.add(e):this}return(new a).add(e)};a.version="1.0.1";var x=a.prototype;F(x,{add:function(e){var n=this;if(e==null){return n}if(e instanceof a){n.data=C(n.data,e.data);return n}if(arguments.length>1){e=E.call(arguments)}if(T(e)){g(e,function(e){n.add(e)});return n}n.data=p(n.data,s(e)?e:i(e));return n},remove:function(e){var n=this;if(e==null){return n}if(e instanceof a){n.data=B(n.data,e.data);return n}if(arguments.length>1){e=E.call(arguments)}if(T(e)){g(e,function(e){n.remove(e)});return n}n.data=k(n.data,s(e)?e:i(e));return n},addRange:function(e,n){var t=this;t.data=d(t.data,s(e)?e:i(e),s(n)?n:i(n));return t},removeRange:function(e,n){var t=this;var r=s(e)?e:i(e);var l=s(n)?n:i(n);t.data=I(t.data,r,l);return t},intersection:function(e){var n=this;var t=e instanceof a?O(e.data):e;n.data=J(n.data,t);return n},contains:function(e){return L(this.data,s(e)?e:i(e))},clone:function(){var e=new a;e.data=this.data.slice(0);return e},toString:function(){var e=z(this.data);return e.replace(X,"\\0$1")},toRegExp:function(e){return RegExp(this.toString(),e||"")},valueOf:function(){return O(this.data)}});x.toArray=x.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return a})}else if(h&&!h.nodeType){if(S){S.exports=a}else{h.regenerate=a}}else{_.regenerate=a}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],183:[function(t,e,n){(function(t){(function(){"use strict";var i={"function":true,object:true};var u=i[typeof window]&&window||this;var R=u;var s=i[typeof n]&&n;var p=i[typeof e]&&e&&!e.nodeType&&e;var a=s&&p&&typeof t=="object"&&t;if(a&&(a.global===a||a.window===a||a.self===a)){u=a}var b=String.fromCharCode;var d=Math.floor;function o(){var s=16384;var n=[];var l;var a;var t=-1;var r=arguments.length;if(!r){return""}var i="";while(++t<r){var e=Number(arguments[t]);if(!isFinite(e)||e<0||e>1114111||d(e)!=e){throw RangeError("Invalid code point: "+e)}if(e<=65535){n.push(e)}else{e-=65536;l=(e>>10)+55296;a=e%1024+56320;n.push(l,a)}if(t+1==r||n.length>s){i+=b.apply(null,n);n.length=0}}return i}function l(n,e){if(e.indexOf("|")==-1){if(n==e){return}throw Error("Invalid node type: "+n)}e=l.hasOwnProperty(e)?l[e]:l[e]=RegExp("^(?:"+e+")$");if(e.test(n)){return}throw Error("Invalid node type: "+n)}function r(n){var e=n.type;if(r.hasOwnProperty(e)&&typeof r[e]=="function"){return r[e](n)}throw Error("Invalid node type: "+e)}function m(n){l(n.type,"alternative");var e=n.body,t=e?e.length:0;if(t==1){return f(e[0])}else{var r=-1,a="";while(++r<t){a+=f(e[r])}return a}}function I(e){l(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 g(e){l(e.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return r(e)}function y(n){l(n.type,"characterClass");var t=n.body,a=t?t.length:0;var r=-1,e="[";if(n.negative){e+="^"}while(++r<a){e+=c(t[r])}e+="]";return e}function v(e){l(e.type,"characterClassEscape");return"\\"+e.value}function x(e){l(e.type,"characterClassRange");var n=e.min,t=e.max;if(n.type=="characterClassRange"||t.type=="characterClassRange"){throw Error("Invalid character class range")}return c(n)+"-"+c(t)}function c(e){l(e.type,"anchor|characterClassEscape|characterClassRange|dot|value");return r(e)}function E(i){l(i.type,"disjunction");var e=i.body,n=e?e.length:0;if(n==0){throw Error("No body")}else if(n==1){return r(e[0])}else{var t=-1,a="";while(++t<n){if(t!=0){a+="|"}a+=r(e[t])}return a}}function w(e){l(e.type,"dot");return"."}function _(n){l(n.type,"group");var e="(";switch(n.behavior){case"normal":break;case"ignore":e+="?:";break;case"lookahead":e+="?=";break;case"negativeLookahead":e+="?!";break;default:throw Error("Invalid behaviour: "+n.behaviour)}var t=n.body,a=t?t.length:0;if(a==1){e+=r(t[0])}else{var i=-1;while(++i<a){e+=r(t[i])}}e+=")";return e}function S(t){l(t.type,"quantifier");var e="",n=t.min,r=t.max;switch(r){case undefined:case null:switch(n){case 0:e="*";break;case 1:e="+";break;default:e="{"+n+",}";break}break;default:if(n==r){e="{"+n+"}"}else if(n==0&&r==1){e="?"}else{e="{"+n+","+r+"}"}break}if(!t.greedy){e+="?"}return g(t.body[0])+e}function k(e){l(e.type,"reference");return"\\"+e.matchIndex}function f(e){l(e.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return r(e)}function h(n){l(n.type,"value");var t=n.kind,e=n.codePoint;switch(t){case"controlLetter":return"\\c"+o(e+64);case"hexadecimalEscape":return"\\x"+("00"+e.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+o(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 o(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: "+t)}}r.alternative=m;r.anchor=I;r.characterClass=y;r.characterClassEscape=v;r.characterClassRange=x;r.disjunction=E;r.dot=w;r.group=_;r.quantifier=S;r.reference=k;r.value=h;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:r}})}else if(s&&p){s.generate=r}else{u.regjsgen={generate:r}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})
},{}],184:[function(n,e,t){(function(){function t(r,L){var m=(L||"").indexOf("u")!==-1;var e=0;var g=0;function l(e){e.raw=r.substring(e.range[0],e.range[1]);return e}function S(e,n){e.range[0]=n;return l(e)}function o(n,t){return l({type:"anchor",kind:n,range:[e-t,e]})}function p(e,n,t,r){return l({type:"value",kind:e,codePoint:n,range:[t,r]})}function a(t,r,l,n){n=n||0;return p(t,r,e-(l.length+n),e)}function u(l){var r=l[0];var n=r.charCodeAt(0);if(m){var t;if(r.length===1&&n>=55296&&n<=56319){t=T().charCodeAt(0);if(t>=56320&&t<=57343){e++;return p("symbol",(n-55296)*1024+t-56320+65536,e-2,e)}}}return p("symbol",n,e-1,e)}function z(e,n,t){return l({type:"disjunction",body:e,range:[n,t]})}function G(){return l({type:"dot",range:[e-1,e]})}function J(n){return l({type:"characterClassEscape",value:n,range:[e-2,e]})}function F(n){return l({type:"reference",matchIndex:parseInt(n,10),range:[e-1-n.length,e]})}function N(e,n,t,r){return l({type:"group",behavior:e,body:n,range:[t,r]})}function s(r,a,t,n){if(n==null){t=e-1;n=e}return l({type:"quantifier",min:r,max:a,greedy:true,body:null,range:[t,n]})}function D(e,n,t){return l({type:"alternative",body:e,range:[n,t]})}function v(e,n,t,r){return l({type:"characterClass",body:e,negative:n,range:[t,r]})}function x(e,n,t,r){if(e.codePoint>n.codePoint){throw SyntaxError("invalid range in character class")}return l({type:"characterClassRange",min:e,max:n,range:[t,r]})}function b(e){if(e.type==="alternative"){return e.body}else{return[e]}}function $(e){return e.type==="empty"}function f(n){n=n||1;var t=r.substring(e,e+n);e+=n||1;return t}function c(e){if(!n(e)){throw SyntaxError("character: "+e)}}function n(n){if(r.indexOf(n,e)===e){return f(n.length)}}function T(){return r[e]}function i(n){return r.indexOf(n,e)===e}function R(n){return r[e+1]===n}function t(t){var l=r.substring(e);var n=l.match(t);if(n){n.range=[];n.range[0]=e;f(n[0].length);n.range[1]=e}return n}function A(){var t=[],r=e;t.push(k());while(n("|")){t.push(k())}if(t.length===1){return t[0]}return z(t,r,e)}function k(){var n=[],r=e;var t;while(t=U()){n.push(t)}if(n.length===1){return n[0]}return D(n,r,e)}function U(){if(e>=r.length||i("|")||i(")")){return null}var l=j();if(l){return l}var n=O();if(!n){throw SyntaxError("Expected atom")}var t=M()||false;if(t){t.body=b(n);S(t,n.range[0]);return t}return n}function E(l,a,i,s){var t=null,o=e;if(n(l)){t=a}else if(n(i)){t=s}else{return false}var r=A();if(!r){throw SyntaxError("Expected disjunction")}c(")");var u=N(t,b(r),o,e);if(t=="normal"){g++}return u}function j(){var t,r=e;if(n("^")){return o("start",1)}else if(n("$")){return o("end",1)}else if(n("\\b")){return o("boundary",2)}else if(n("\\B")){return o("not-boundary",2)}else{return E("(?=","lookahead","(?!","negativeLookahead")}}function M(){var e;var r;var l,a;if(n("*")){r=s(0)}else if(n("+")){r=s(1)}else if(n("?")){r=s(0,1)}else if(e=t(/^\{([0-9]+)\}/)){l=parseInt(e[1],10);r=s(l,l,e.range[0],e.range[1])}else if(e=t(/^\{([0-9]+),\}/)){l=parseInt(e[1],10);r=s(l,undefined,e.range[0],e.range[1])}else if(e=t(/^\{([0-9]+),([0-9]+)\}/)){l=parseInt(e[1],10);a=parseInt(e[2],10);if(l>a){throw SyntaxError("numbers out of order in {} quantifier")}r=s(l,a,e.range[0],e.range[1])}if(r){if(n("?")){r.greedy=false;r.range[1]+=1}}return r}function O(){var e;if(e=t(/^[^^$\\.*+?(){[|]/)){return u(e)}else if(n(".")){return G()}else if(n("\\")){e=I();if(!e){throw SyntaxError("atomEscape")}return e}else if(e=q()){return e}else{return E("(?:","ignore","(","normal")}}function y(n){if(m){var t,r;if(n.kind=="unicodeEscape"&&(t=n.codePoint)>=55296&&t<=56319&&i("\\")&&R("u")){var s=e;e++;var a=C();if(a.kind=="unicodeEscape"&&(r=a.codePoint)>=56320&&r<=57343){n.range[1]=a.range[1];n.codePoint=(t-55296)*1024+r-56320+65536;n.type="value";n.kind="unicodeCodePointEscape";l(n)}else{e=s}}}return n}function C(){return I(true)}function I(t){var e;e=B();if(e){return e}if(t){if(n("b")){return a("singleEscape",8,"\\b")}else if(n("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}e=Y();return e}function B(){var e,n;if(e=t(/^(?!0)\d+/)){n=e[0];var r=parseInt(e[0],10);if(r<=g){return F(e[0])}else{f(-e[0].length);if(e=t(/^[0-7]{1,3}/)){return a("octal",parseInt(e[0],8),e[0],1)}else{e=u(t(/^[89]/));return S(e,e.range[0]-1)}}}else if(e=t(/^[0-7]{1,3}/)){n=e[0];if(/^0{1,3}$/.test(n)){return a("null",0,"0",n.length+1)}else{return a("octal",parseInt(n,8),n,1)}}else if(e=t(/^[dDsSwW]/)){return J(e[0])}return false}function Y(){var e;if(e=t(/^[fnrtv]/)){var n=0;switch(e[0]){case"t":n=9;break;case"n":n=10;break;case"v":n=11;break;case"f":n=12;break;case"r":n=13;break}return a("singleEscape",n,"\\"+e[0])}else if(e=t(/^c([a-zA-Z])/)){return a("controlLetter",e[1].charCodeAt(0)%32,e[1],2)}else if(e=t(/^x([0-9a-fA-F]{2})/)){return a("hexadecimalEscape",parseInt(e[1],16),e[1],2)}else if(e=t(/^u([0-9a-fA-F]{4})/)){return y(a("unicodeEscape",parseInt(e[1],16),e[1],2))}else if(m&&(e=t(/^u\{([0-9a-fA-F]{1,})\}/))){return a("unicodeCodePointEscape",parseInt(e[1],16),e[1],4)}else{return X()}}function V(e){var n=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&&n.test(String.fromCharCode(e))}function X(){var t="";var r="";var l;var e;if(!V(T())){e=f();return a("identifier",e.charCodeAt(0),e,1)}if(n(t)){return a("identifier",8204,t)}else if(n(r)){return a("identifier",8205,r)}return null}function q(){var r,l=e;if(r=t(/^\[\^/)){r=d();c("]");return v(r,true,l,e)}else if(n("[")){r=d();c("]");return v(r,false,l,e)}return null}function d(){var e;if(i("]")){return[]}else{e=W();if(!e){throw SyntaxError("nonEmptyClassRanges")}return e}}function _(t){var r,l,n;if(i("-")&&!R("]")){c("-");n=h();if(!n){throw SyntaxError("classAtom")}l=e;var a=d();if(!a){throw SyntaxError("classRanges")}r=t.range[0];if(a.type==="empty"){return[x(t,n,r,l)]}return[x(t,n,r,l)].concat(a)}n=H();if(!n){throw SyntaxError("nonEmptyClassRangesNoDash")}return[t].concat(n)}function W(){var e=h();if(!e){throw SyntaxError("classAtom")}if(i("]")){return[e]}return _(e)}function H(){var e=h();if(!e){throw SyntaxError("classAtom")}if(i("]")){return e}return _(e)}function h(){if(n("-")){return u("-")}else{return P()}}function P(){var e;if(e=t(/^[^\\\]-]/)){return u(e[0])}else if(n("\\")){e=C();if(!e){throw SyntaxError("classEscape")}return y(e)}}r=String(r);if(r===""){r="(?:)"}var w=A();if(w.range[1]!==r.length){throw SyntaxError("Could not parse entire input - got stuck: "+r)}return w}var n={parse:t};if(typeof e!=="undefined"&&e.exports){e.exports=n}else{window.regjsparser=n}})()},{}],185:[function(n,h,_){var E=n("regjsgen").generate;var s=n("regjsparser").parse;var r=n("regenerate");var c=n("./data/iu-mappings.json");var a=n("./data/character-class-escape-sets.js");function o(n){if(e){if(t){return a.UNICODE_IGNORE_CASE[n]}return a.UNICODE[n]}return a.REGULAR[n]}var b={};var v=b.hasOwnProperty;function y(e,n){return v.call(e,n)}var m=r().addRange(0,1114111);var d=r().addRange(0,65535);var p=m.clone().remove(10,13,8232,8233);var g=p.clone().intersection(d);r.prototype.iuAddRange=function(e,r){var n=this;do{var t=i(e);if(t){n.add(t)}}while(++e<=r);return n};function f(t,e){for(var n in e){t[n]=e[n]}}function l(t,n){var e=s(n,"");switch(e.type){case"characterClass":case"group":case"value":break;default:e=x(e,n)}f(t,e)}function x(e,n){return{type:"group",behavior:"ignore",body:[e],raw:"(?:"+n+")"}}function i(e){return y(c,e)?c[e]:false}var t=false;var e=false;function w(a){var n=r();var s=a.body.forEach(function(r){switch(r.type){case"value":n.add(r.codePoint);if(t&&e){var l=i(r.codePoint);if(l){n.add(l)}}break;case"characterClassRange":var a=r.min.codePoint;var s=r.max.codePoint;n.addRange(a,s);if(t&&e){n.iuAddRange(a,s)}break;case"characterClassEscape":n.add(o(r.value));break;default:throw Error("Unknown term type: "+r.type)}});if(a.negative){n=(e?m:d).clone().remove(n)}l(a,n.toString());return a}function u(n){switch(n.type){case"dot":l(n,(e?p:g).toString());break;case"characterClass":n=w(n);break;case"characterClassEscape":l(n,o(n.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":n.body=n.body.map(u);break;case"value":var a=n.codePoint;var s=r(a);if(t&&e){var c=i(a);if(c){s.add(c)}}l(n,s.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+n.type)}return n}h.exports=function(l,n){var r=s(l,n);t=n?n.indexOf("i")>-1:false;e=n?n.indexOf("u")>-1:false;f(r,u(r));return E(r)}},{"./data/character-class-escape-sets.js":180,"./data/iu-mappings.json":181,regenerate:182,regjsgen:183,regjsparser:184}],186:[function(e,t,n){n.SourceMapGenerator=e("./source-map/source-map-generator").SourceMapGenerator;n.SourceMapConsumer=e("./source-map/source-map-consumer").SourceMapConsumer;n.SourceNode=e("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":192,"./source-map/source-map-generator":193,"./source-map/source-node":194}],187:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(t,r,l){var n=t("./util");function e(){this._array=[];this._set={}}e.fromArray=function a(t,l){var r=new e;for(var n=0,a=t.length;n<a;n++){r.add(t[n],l)}return r};e.prototype.add=function i(e,r){var t=this.has(e);var l=this._array.length;if(!t||r){this._array.push(e)}if(!t){this._set[n.toSetString(e)]=l}};e.prototype.has=function s(e){return Object.prototype.hasOwnProperty.call(this._set,n.toSetString(e))};e.prototype.indexOf=function o(e){if(this.has(e)){return this._set[n.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 c(){return this._array.slice()};r.ArraySet=e})},{"./util":195,amdefine:196}],188:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(i,n,u){var t=i("./base64");var e=5;var r=1<<e;var l=r-1;var a=r;function s(e){return e<0?(-e<<1)+1:(e<<1)+0}function o(e){var t=(e&1)===1;var n=e>>1;return t?-n:n}n.encode=function c(o){var i="";var r;var n=s(o);do{r=n&l;n>>>=e;if(n>0){r|=a}i+=t.encode(r)}while(n>0);return i};n.decode=function f(r,u){var i=0;var p=r.length;var s=0;var c=0;var f,n;do{if(i>=p){throw new Error("Expected more digits in base 64 VLQ value.")}n=t.decode(r.charAt(i++));f=!!(n&a);n&=l;s=s+(n<<c);c+=e}while(f);u.value=o(s);u.rest=r.slice(i)}})},{"./base64":189,amdefine:196}],189:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(r,t,l){var e={};var n={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(t,r){e[t]=r;n[r]=t});t.encode=function a(e){if(e in n){return n[e]}throw new TypeError("Must be between 0 and 63: "+e)};t.decode=function i(n){if(n in e){return e[n]}throw new TypeError("Not a valid base 64 digit: "+n)}})},{amdefine:196}],190:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(t,n,r){function e(t,r,l,a,i){var n=Math.floor((r-t)/2)+t;var s=i(l,a[n],true);if(s===0){return n}else if(s>0){if(r-n>1){return e(n,r,l,a,i)}return n}else{if(n-t>1){return e(t,n,l,a,i)}return t<0?-1:t}}n.search=function l(t,n,r){if(n.length===0){return-1}return e(-1,n.length,t,n,r)}})},{amdefine:196}],191:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(t,r,a){var n=t("./util");function l(e,t){var r=e.generatedLine;var l=t.generatedLine;var a=e.generatedColumn;var i=t.generatedColumn;return l>r||l==r&&i>=a||n.compareByGeneratedPositions(e,t)<=0}function e(){this._array=[];this._sorted=true;this._last={generatedLine:-1,generatedColumn:0}}e.prototype.unsortedForEach=function i(e,n){this._array.forEach(e,n)};e.prototype.add=function s(e){var n;if(l(this._last,e)){this._last=e;this._array.push(e)}else{this._sorted=false;this._array.push(e)}};e.prototype.toArray=function o(){if(!this._sorted){this._array.sort(n.compareByGeneratedPositions);this._sorted=true}return this._array};r.MappingList=e})},{"./util":195,amdefine:196}],192:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(r,a,s){var e=r("./util");var i=r("./binary-search");var l=r("./array-set").ArraySet;var t=r("./base64-vlq");function n(t){var n=t;if(typeof t==="string"){n=JSON.parse(t.replace(/^\)\]\}'/,""))}var a=e.getArg(n,"version");var r=e.getArg(n,"sources");var i=e.getArg(n,"names",[]);var s=e.getArg(n,"sourceRoot",null);var o=e.getArg(n,"sourcesContent",null);var u=e.getArg(n,"mappings");var c=e.getArg(n,"file",null);if(a!=this._version){throw new Error("Unsupported version: "+a)}r=r.map(e.normalize);this._names=l.fromArray(i,true);this._sources=l.fromArray(r,true);this.sourceRoot=s;this.sourcesContent=o;this._mappings=u;this.file=c}n.fromSourceMap=function o(r){var t=Object.create(n.prototype);t._names=l.fromArray(r._names.toArray(),true);t._sources=l.fromArray(r._sources.toArray(),true);t.sourceRoot=r._sourceRoot;t.sourcesContent=r._generateSourcesContent(t._sources.toArray(),t.sourceRoot);t.file=r._file;t.__generatedMappings=r._mappings.toArray().slice();t.__originalMappings=r._mappings.toArray().slice().sort(e.compareByOriginalPositions);return t};n.prototype._version=3;Object.defineProperty(n.prototype,"sources",{get:function(){return this._sources.toArray().map(function(n){return this.sourceRoot!=null?e.join(this.sourceRoot,n):n},this)}});n.prototype.__generatedMappings=null;Object.defineProperty(n.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});n.prototype.__originalMappings=null;Object.defineProperty(n.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});n.prototype._nextCharIsMappingSeparator=function u(n){var e=n.charAt(0);return e===";"||e===","};n.prototype._parseMappings=function c(f,p){var o=1;var a=0;var s=0;var i=0;var u=0;var c=0;var n=f;var r={};var l;while(n.length>0){if(n.charAt(0)===";"){o++;n=n.slice(1);a=0}else if(n.charAt(0)===","){n=n.slice(1)}else{l={};l.generatedLine=o;t.decode(n,r);l.generatedColumn=a+r.value;a=l.generatedColumn;n=r.rest;if(n.length>0&&!this._nextCharIsMappingSeparator(n)){t.decode(n,r);l.source=this._sources.at(u+r.value);u+=r.value;n=r.rest;if(n.length===0||this._nextCharIsMappingSeparator(n)){throw new Error("Found a source, but no line and column")}t.decode(n,r);l.originalLine=s+r.value;s=l.originalLine;l.originalLine+=1;n=r.rest;if(n.length===0||this._nextCharIsMappingSeparator(n)){throw new Error("Found a source and line, but no column")}t.decode(n,r);l.originalColumn=i+r.value;i=l.originalColumn;n=r.rest;if(n.length>0&&!this._nextCharIsMappingSeparator(n)){t.decode(n,r);l.name=this._names.at(c+r.value);c+=r.value;n=r.rest}}this.__generatedMappings.push(l);if(typeof l.originalLine==="number"){this.__originalMappings.push(l)}}}this.__generatedMappings.sort(e.compareByGeneratedPositions);this.__originalMappings.sort(e.compareByOriginalPositions)};n.prototype._findMapping=function f(e,r,n,t,l){if(e[n]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+e[n])}if(e[t]<0){throw new TypeError("Column must be greater than or equal to 0, got "+e[t])}return i.search(e,r,l)};n.prototype.computeColumnSpans=function p(){for(var e=0;e<this._generatedMappings.length;++e){var n=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var t=this._generatedMappings[e+1];if(n.generatedLine===t.generatedLine){n.lastGeneratedColumn=t.generatedColumn-1;continue}}n.lastGeneratedColumn=Infinity}};n.prototype.originalPositionFor=function d(r){var l={generatedLine:e.getArg(r,"line"),generatedColumn:e.getArg(r,"column")};var a=this._findMapping(l,this._generatedMappings,"generatedLine","generatedColumn",e.compareByGeneratedPositions);if(a>=0){var n=this._generatedMappings[a];if(n.generatedLine===l.generatedLine){var t=e.getArg(n,"source",null);if(t!=null&&this.sourceRoot!=null){t=e.join(this.sourceRoot,t)}return{source:t,line:e.getArg(n,"originalLine",null),column:e.getArg(n,"originalColumn",null),name:e.getArg(n,"name",null)}}}return{source:null,line:null,column:null,name:null}};n.prototype.sourceContentFor=function m(n){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){n=e.relative(this.sourceRoot,n)}if(this._sources.has(n)){return this.sourcesContent[this._sources.indexOf(n)]}var t;if(this.sourceRoot!=null&&(t=e.urlParse(this.sourceRoot))){var r=n.replace(/^file:\/\//,"");if(t.scheme=="file"&&this._sources.has(r)){return this.sourcesContent[this._sources.indexOf(r)]}if((!t.path||t.path=="/")&&this._sources.has("/"+n)){return this.sourcesContent[this._sources.indexOf("/"+n)]}}throw new Error('"'+n+'" is not in the SourceMap.')};n.prototype.generatedPositionFor=function h(n){var t={source:e.getArg(n,"source"),originalLine:e.getArg(n,"line"),originalColumn:e.getArg(n,"column")};if(this.sourceRoot!=null){t.source=e.relative(this.sourceRoot,t.source)}var l=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",e.compareByOriginalPositions);if(l>=0){var r=this._originalMappings[l];return{line:e.getArg(r,"generatedLine",null),column:e.getArg(r,"generatedColumn",null),lastColumn:e.getArg(r,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};n.prototype.allGeneratedPositionsFor=function g(l){var t={source:e.getArg(l,"source"),originalLine:e.getArg(l,"line"),originalColumn:Infinity};if(this.sourceRoot!=null){t.source=e.relative(this.sourceRoot,t.source)}var a=[];var r=this._findMapping(t,this._originalMappings,"originalLine","originalColumn",e.compareByOriginalPositions);if(r>=0){var n=this._originalMappings[r];while(n&&n.originalLine===t.originalLine){a.push({line:e.getArg(n,"generatedLine",null),column:e.getArg(n,"generatedColumn",null),lastColumn:e.getArg(n,"lastGeneratedColumn",null)});n=this._originalMappings[--r]}}return a.reverse()};n.GENERATED_ORDER=1;n.ORIGINAL_ORDER=2;n.prototype.eachMapping=function y(l,a,i){var s=a||null;var o=i||n.GENERATED_ORDER;var t;switch(o){case n.GENERATED_ORDER:t=this._generatedMappings;break;case n.ORIGINAL_ORDER:t=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var r=this.sourceRoot;t.map(function(n){var t=n.source;if(t!=null&&r!=null){t=e.join(r,t)}return{source:t,generatedLine:n.generatedLine,generatedColumn:n.generatedColumn,originalLine:n.originalLine,originalColumn:n.originalColumn,name:n.name}}).forEach(l,s)};a.SourceMapConsumer=n})},{"./array-set":187,"./base64-vlq":188,"./binary-search":190,"./util":195,amdefine:196}],193:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(r,a,s){var t=r("./base64-vlq");var e=r("./util");var l=r("./array-set").ArraySet;var i=r("./mapping-list").MappingList;function n(n){if(!n){n={}}this._file=e.getArg(n,"file",null);this._sourceRoot=e.getArg(n,"sourceRoot",null);this._skipValidation=e.getArg(n,"skipValidation",false);this._sources=new l;this._names=new l;this._mappings=new i;this._sourcesContents=null}n.prototype._version=3;n.fromSourceMap=function o(t){var r=t.sourceRoot;var l=new n({file:t.file,sourceRoot:r});t.eachMapping(function(n){var t={generated:{line:n.generatedLine,column:n.generatedColumn}};if(n.source!=null){t.source=n.source;if(r!=null){t.source=e.relative(r,t.source)}t.original={line:n.originalLine,column:n.originalColumn};if(n.name!=null){t.name=n.name}}l.addMapping(t)});t.sources.forEach(function(e){var n=t.sourceContentFor(e);if(n!=null){l.setSourceContent(e,n)}});return l};n.prototype.addMapping=function u(l){var a=e.getArg(l,"generated");var n=e.getArg(l,"original",null);var t=e.getArg(l,"source",null);var r=e.getArg(l,"name",null);if(!this._skipValidation){this._validateMapping(a,n,t,r)}if(t!=null&&!this._sources.has(t)){this._sources.add(t)}if(r!=null&&!this._names.has(r)){this._names.add(r)}this._mappings.add({generatedLine:a.line,generatedColumn:a.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:t,name:r})};n.prototype.setSourceContent=function c(r,t){var n=r;if(this._sourceRoot!=null){n=e.relative(this._sourceRoot,n)}if(t!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[e.toSetString(n)]=t}else if(this._sourcesContents){delete this._sourcesContents[e.toSetString(n)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};n.prototype.applySourceMap=function f(t,o,r){var a=o;if(o==null){if(t.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=t.file}var n=this._sourceRoot;if(n!=null){a=e.relative(n,a)}var i=new l;var s=new l;this._mappings.unsortedForEach(function(l){if(l.source===a&&l.originalLine!=null){var o=t.originalPositionFor({line:l.originalLine,column:l.originalColumn});if(o.source!=null){l.source=o.source;if(r!=null){l.source=e.join(r,l.source)}if(n!=null){l.source=e.relative(n,l.source)}l.originalLine=o.line;l.originalColumn=o.column;if(o.name!=null){l.name=o.name}}}var u=l.source;if(u!=null&&!i.has(u)){i.add(u)}var c=l.name;if(c!=null&&!s.has(c)){s.add(c)}},this);this._sources=i;this._names=s;t.sources.forEach(function(l){var a=t.sourceContentFor(l);if(a!=null){if(r!=null){l=e.join(r,l)}if(n!=null){l=e.relative(n,l)}this.setSourceContent(l,a)}},this)};n.prototype._validateMapping=function p(e,n,t,r){if(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!n&&!t&&!r){return}else if(e&&"line"in e&&"column"in e&&n&&"line"in n&&"column"in n&&e.line>0&&e.column>=0&&n.line>0&&n.column>=0&&t){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:t,original:n,name:r}))}};n.prototype._serializeMappings=function d(){var i=0;var a=1;var u=0;var c=0;var f=0;var o=0;var r="";var n;var s=this._mappings.toArray();for(var l=0,p=s.length;l<p;l++){n=s[l];if(n.generatedLine!==a){i=0;while(n.generatedLine!==a){r+=";";a++}}else{if(l>0){if(!e.compareByGeneratedPositions(n,s[l-1])){continue}r+=","}}r+=t.encode(n.generatedColumn-i);i=n.generatedColumn;if(n.source!=null){r+=t.encode(this._sources.indexOf(n.source)-o);o=this._sources.indexOf(n.source);r+=t.encode(n.originalLine-1-c);c=n.originalLine-1;r+=t.encode(n.originalColumn-u);u=n.originalColumn;if(n.name!=null){r+=t.encode(this._names.indexOf(n.name)-f);f=this._names.indexOf(n.name)}}}return r};n.prototype._generateSourcesContent=function m(t,n){return t.map(function(t){if(!this._sourcesContents){return null}if(n!=null){t=e.relative(n,t)}var r=e.toSetString(t);return Object.prototype.hasOwnProperty.call(this._sourcesContents,r)?this._sourcesContents[r]:null},this)};n.prototype.toJSON=function h(){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};n.prototype.toString=function g(){return JSON.stringify(this)};a.SourceMapGenerator=n})},{"./array-set":187,"./base64-vlq":188,"./mapping-list":191,"./util":195,amdefine:196}],194:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(r,l,o){var a=r("./source-map-generator").SourceMapGenerator;var t=r("./util");var i=/(\r?\n)/;var s=10;var n="$$$isSourceNode$$$";function e(e,t,r,l,a){this.children=[];this.sourceContents={};this.line=e==null?null:e;this.column=t==null?null:t;this.source=r==null?null:r;this.name=a==null?null:a;this[n]=true;if(l!=null)this.add(l)}e.fromStringWithSourceMap=function u(p,c,s){var r=new e;var n=p.split(i);var u=function(){var e=n.shift();var t=n.shift()||"";return e+t};var o=1,a=0;var l=null;c.eachMapping(function(e){if(l!==null){if(o<e.generatedLine){var i="";f(l,u());o++;a=0}else{var t=n[0];var i=t.substr(0,e.generatedColumn-a);n[0]=t.substr(e.generatedColumn-a);a=e.generatedColumn;f(l,i);l=e;return}}while(o<e.generatedLine){r.add(u());o++}if(a<e.generatedColumn){var t=n[0];r.add(t.substr(0,e.generatedColumn));n[0]=t.substr(e.generatedColumn);a=e.generatedColumn}l=e},this);if(n.length>0){if(l){f(l,u())}r.add(n.join(""))}c.sources.forEach(function(e){var n=c.sourceContentFor(e);if(n!=null){if(s!=null){e=t.join(s,e)}r.setSourceContent(e,n)}});return r;function f(n,l){if(n===null||n.source===undefined){r.add(l)}else{var a=s?t.join(s,n.source):n.source;r.add(new e(n.originalLine,n.originalColumn,a,l,n.name))}}};e.prototype.add=function c(e){if(Array.isArray(e)){e.forEach(function(e){this.add(e)},this)}else if(e[n]||typeof e==="string"){if(e){this.children.push(e)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e)}return this};e.prototype.prepend=function f(e){if(Array.isArray(e)){for(var t=e.length-1;t>=0;t--){this.prepend(e[t])}}else if(e[n]||typeof e==="string"){this.children.unshift(e)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e)}return this};e.prototype.walk=function p(r){var e;for(var t=0,l=this.children.length;t<l;t++){e=this.children[t];if(e[n]){e.walk(r)}else{if(e!==""){r(e,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};e.prototype.join=function d(r){var e;var n;var t=this.children.length;if(t>0){e=[];for(n=0;n<t-1;n++){e.push(this.children[n]);e.push(r)}e.push(this.children[n]);this.children=e}return this};e.prototype.replaceRight=function m(t,r){var e=this.children[this.children.length-1];if(e[n]){e.replaceRight(t,r)}else if(typeof e==="string"){this.children[this.children.length-1]=e.replace(t,r)}else{this.children.push("".replace(t,r))}return this};e.prototype.setSourceContent=function h(e,n){this.sourceContents[t.toSetString(e)]=n};e.prototype.walkSourceContents=function g(l){for(var e=0,a=this.children.length;e<a;e++){if(this.children[e][n]){this.children[e].walkSourceContents(l)}}var r=Object.keys(this.sourceContents);for(var e=0,a=r.length;e<a;e++){l(t.fromSetString(r[e]),this.sourceContents[r[e]])}};e.prototype.toString=function y(){var e="";this.walk(function(n){e+=n});return e};e.prototype.toStringWithSourceMap=function v(u){var e={code:"",line:1,column:0};var n=new a(u);var t=false;var r=null;var l=null;var i=null;var o=null;this.walk(function(c,a){e.code+=c;if(a.source!==null&&a.line!==null&&a.column!==null){if(r!==a.source||l!==a.line||i!==a.column||o!==a.name){n.addMapping({source:a.source,original:{line:a.line,column:a.column},generated:{line:e.line,column:e.column},name:a.name})}r=a.source;l=a.line;i=a.column;o=a.name;t=true}else if(t){n.addMapping({generated:{line:e.line,column:e.column}});r=null;t=false}for(var u=0,f=c.length;u<f;u++){if(c.charCodeAt(u)===s){e.line++;e.column=0;if(u+1===f){r=null;t=false}else if(t){n.addMapping({source:a.source,original:{line:a.line,column:a.column},generated:{line:e.line,column:e.column},name:a.name})}}else{e.column++}}});this.walkSourceContents(function(e,t){n.setSourceContent(e,t)});return{code:e.code,map:n}};l.SourceNode=e})},{"./source-map-generator":193,"./util":195,amdefine:196}],195:[function(e,t,r){if(typeof n!=="function"){var n=e("amdefine")(t,e)}n(function(h,e,m){function o(n,e,t){if(e in n){return n[e]}else if(arguments.length===3){return t}else{throw new Error('"'+e+'" is a required argument.')}}e.getArg=o;var d=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var a=/^data:.+\,.+$/;function n(n){var e=n.match(d);if(!e){return null}return{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}}e.urlParse=n;function t(e){var n="";if(e.scheme){n+=e.scheme+":"}n+="//";if(e.auth){n+=e.auth+"@"}if(e.host){n+=e.host}if(e.port){n+=":"+e.port}if(e.path){n+=e.path}return n}e.urlGenerate=t;function l(o){var e=o;var r=n(o);if(r){if(!r.path){return o}e=r.path}var u=e.charAt(0)==="/";var l=e.split(/\/+/);for(var s,i=0,a=l.length-1;a>=0;a--){s=l[a];if(s==="."){l.splice(a,1)}else if(s===".."){i++}else if(i>0){if(s===""){l.splice(a+1,i);i=0}else{l.splice(a,2);i--}}}e=l.join("/");if(e===""){e=u?"/":"."}if(r){r.path=e;return t(r)}return e}e.normalize=l;function u(i,r){if(i===""){i="."}if(r===""){r="."}var s=n(r);var e=n(i);if(e){i=e.path||"/"}if(s&&!s.scheme){if(e){s.scheme=e.scheme}return t(s)}if(s||r.match(a)){return r}if(e&&!e.host&&!e.path){e.host=r;return t(e)}var o=r.charAt(0)==="/"?r:l(i.replace(/\/+$/,"")+"/"+r);if(e){e.path=o;return t(e)}return o}e.join=u;function c(e,t){if(e===""){e="."}e=e.replace(/\/$/,"");var r=n(e);if(t.charAt(0)=="/"&&r&&r.path=="/"){return t.slice(1)}return t.indexOf(e+"/")===0?t.substr(e.length+1):t}e.relative=c;function f(e){return"$"+e}e.toSetString=f;function p(e){return e.substr(1)}e.fromSetString=p;function r(t,r){var e=t||"";var n=r||"";return(e>n)-(e<n)}function s(n,t,l){var e;e=r(n.source,t.source);if(e){return e}e=n.originalLine-t.originalLine;if(e){return e}e=n.originalColumn-t.originalColumn;if(e||l){return e}e=r(n.name,t.name);if(e){return e}e=n.generatedLine-t.generatedLine;if(e){return e}return n.generatedColumn-t.generatedColumn}e.compareByOriginalPositions=s;function i(n,t,l){var e;e=n.generatedLine-t.generatedLine;if(e){return e}e=n.generatedColumn-t.generatedColumn;if(e||l){return e}e=r(n.source,t.source);if(e){return e}e=n.originalLine-t.originalLine;if(e){return e}e=n.originalColumn-t.originalColumn;if(e){return e}return r(n.name,t.name)}e.compareByGeneratedPositions=i})},{amdefine:196}],196:[function(e,n,t){(function(t,r){"use strict";function l(l,o){"use strict";var a={},n={},p=false,d=e("path"),i,u;function m(n){var e,t;for(e=0;n[e];e+=1){t=n[e];if(t==="."){n.splice(e,1);e-=1}else if(t===".."){if(e===1&&(n[2]===".."||n[0]==="..")){break}else if(e>0){n.splice(e-1,2);e-=2}}}}function s(n,t){var e;if(n&&n.charAt(0)==="."){if(t){e=t.split("/");e=e.slice(0,e.length-1);e=e.concat(n.split("/"));m(e);n=e.join("/")}}return n}function h(e){return function(n){return s(n,e)}}function g(t){function e(e){n[t]=e}e.fromText=function(e,n){throw new Error("amdefine does not implement load.fromText")};return e}i=function(n,r,e,l){function a(a,i){if(typeof a==="string"){return u(n,r,e,a,l)}else{a=a.map(function(t){return u(n,r,e,t,l)});t.nextTick(function(){i.apply(null,a)})}}a.toUrl=function(n){if(n.indexOf(".")===0){return s(n,d.dirname(e.filename))}else{return n}};return a};o=o||function y(){return l.require.apply(l,arguments)};function c(t,s,c){var f,a,e,u;if(t){a=n[t]={};e={id:t,uri:r,exports:a};f=i(o,a,e,t)}else{if(p){throw new Error("amdefine with no module ID cannot be called more than once per file.")}p=true;a=l.exports;e=l;f=i(o,a,e,l.id)}if(s){s=s.map(function(e){return f(e)})}if(typeof c==="function"){u=c.apply(e.exports,s)
}else{u=c}if(u!==undefined){e.exports=u;if(t){n[t]=e.exports}}}u=function(r,l,o,e,t){var p=e.indexOf("!"),m=e,d,f;if(p===-1){e=s(e,t);if(e==="require"){return i(r,l,o,t)}else if(e==="exports"){return l}else if(e==="module"){return o}else if(n.hasOwnProperty(e)){return n[e]}else if(a[e]){c.apply(null,a[e]);return n[e]}else{if(r){return r(m)}else{throw new Error("No module with ID: "+e)}}}else{d=e.substring(0,p);e=e.substring(p+1,e.length);f=u(r,l,o,d,t);if(f.normalize){e=f.normalize(e,h(t))}else{e=s(e,t)}if(n[e]){return n[e]}else{f.load(e,i(r,l,o,t),g(e),{});return n[e]}}};function f(n,e,t){if(Array.isArray(n)){t=e;e=n;n=undefined}else if(typeof n!=="string"){t=n;n=e=undefined}if(e&&!Array.isArray(e)){t=e;e=undefined}if(!e){e=["require","exports","module"]}if(n){a[n]=[n,e,t]}else{c(n,e,t)}}f.require=function(e){if(n[e]){return n[e]}if(a[e]){c.apply(null,a[e]);return n[e]}};f.amd={};return f}n.exports=l}).call(this,e("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:119,path:118}],197:[function(n,e,t){e.exports={name:"6to5",description:"Turn ES6 code into readable vanilla ES5 with source maps",version:"2.13.1",author:"Sebastian McKenzie <sebmck@gmail.com>",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-18","ast-types":"~0.6.1",chokidar:"0.12.6",commander:"2.6.0","core-js":"0.4.5",estraverse:"1.9.1",esutils:"1.1.6",esvalid:"1.1.0","fs-readdir-recursive":"0.1.0",jshint:"2.5.11",lodash:"2.4.1","output-file-sync":"^1.1.0","private":"0.1.6",regenerator:"0.8.9",regexpu:"1.0.0",roadrunner:"1.0.4","source-map":"0.1.43","source-map-support":"0.2.9"},devDependencies:{browserify:"8.1.1",chai:"1.10.0",istanbul:"0.3.5","jshint-stylish":"1.0.0",matcha:"0.6.0",mocha:"2.1.0",rimraf:"2.2.8","uglify-js":"2.4.16"},optionalDependencies:{kexec:"0.2.0"}}},{}],198:[function(n,e,t){e.exports={"abstract-expression-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-delete":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceDelete",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-get":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceGet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"abstract-expression-set":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"PROPERTY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"referenceSet",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"apply-constructor":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"args",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"result",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instance",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-container":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-comprehension-for-each":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"forEach",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-from":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"array-push":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STATEMENT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"async-to-generator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"fn",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"FunctionDeclaration",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"TryStatement",start:null,end:null,loc:null,range:null,block:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getNext",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},handler:{type:"CatchClause",start:null,end:null,loc:null,range:null,param:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"e",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},guard:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"reject",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"e",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},guardedHandlers:[],finalizer:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Promise",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"resolve",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"then",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"e",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Literal",start:null,end:null,loc:null,range:null,value:"throw",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"e",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"gen",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},bind:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Function",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"bind",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},call:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CONTEXT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SUPER_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"class-super-constructor-call":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"common-export-default-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXTENDS_HELPER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Literal",start:null,end:null,loc:null,range:null,value:"default",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"corejs-iterator":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CORE_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"$for",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getIterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"default-parameter":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"DEFAULT_VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENT_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},defaults:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defaults",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"define-property":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-assign":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-module-override":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"exports-default-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VALUE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"extends":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:1,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"source",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"key",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:null,update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"IS_ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LOOP_OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"INDEX",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"for-of":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"OBJECT",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"STEP_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ITERATOR_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},get:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getOwnPropertyDescriptor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getPrototypeOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"parent",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"property",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"value",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"in",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"desc",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"get",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"undefined",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"getter",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"receiver",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"has-own":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},inherits:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:null,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ThrowStatement",start:null,end:null,loc:null,range:null,argument:{type:"NewExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"TypeError",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Literal",start:null,end:null,loc:null,range:null,value:"Super expression must either be null or a function, not ",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},operator:"+",right:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"create",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"enumerable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:false,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"writable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"configurable",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Literal",start:null,end:null,loc:null,range:null,value:true,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"subClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"__proto__",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"superClass",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require-wildcard":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"default",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"interop-require":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Literal",start:null,end:null,loc:null,range:null,value:"default",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"||",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"let-scoping-return":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"object",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"RETURN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"v",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"object-without-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForInStatement",start:null,end:null,loc:null,range:null,left:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"keys",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"indexOf",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:">=",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:0,raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"hasOwnProperty",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"call",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ContinueStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"target",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"property-method-assignment-wrapper":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_ID",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"apply",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"ThisExpression",start:null,end:null,loc:null,range:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arguments",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"toString",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"WRAPPER_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"FUNCTION",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-identifier":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"CLASS_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"prototype-properties":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"staticProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"child",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"instanceProps",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"require-assign-key":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"VARIABLE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},require:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"require",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},rest:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"START",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"<",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"LEN",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:{type:"UpdateExpression",start:null,end:null,loc:null,range:null,operator:"++",prefix:false,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARRAY_KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"KEY",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"self-global":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"self",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"global",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},slice:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"prototype",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"slice",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"sliced-to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"ArrayExpression",start:null,end:null,loc:null,range:null,elements:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ForStatement",start:null,end:null,loc:null,range:null,init:{type:"VariableDeclaration",start:null,end:null,loc:null,range:null,declarations:[{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:true,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"VariableDeclarator",start:null,end:null,loc:null,range:null,id:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},init:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],kind:"var",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},test:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"!",prefix:true,argument:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_iterator",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"next",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"done",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},update:null,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"push",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_step",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"length",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"i",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BreakStatement",start:null,end:null,loc:null,range:null,label:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"_arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},system:{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"System",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"register",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_NAME",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"MODULE_DEPENDENCIES",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXPORT_IDENTIFIER",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"setters",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"SETTERS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"execute",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"EXECUTE",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal-loose":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"AssignmentExpression",start:null,end:null,loc:null,range:null,operator:"=",left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"tagged-template-literal":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"defineProperties",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"strings",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"ObjectExpression",start:null,end:null,loc:null,range:null,properties:[{type:"Property",start:null,end:null,loc:null,range:null,method:false,shorthand:false,computed:false,key:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"value",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},value:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Object",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"freeze",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"raw",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},kind:"init",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-exports":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"exports",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"test-module":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"module",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"!==",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"undefined",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"to-array":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"isArray",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},alternate:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Array",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"from",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"arr",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"typeof":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ReturnStatement",start:null,end:null,loc:null,range:null,argument:{type:"ConditionalExpression",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"constructor",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"Symbol",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"Literal",start:null,end:null,loc:null,range:null,value:"symbol",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},alternate:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"obj",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},"umd-runner-body":{type:"Program",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"FunctionExpression",start:null,end:null,loc:null,range:null,id:null,params:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"LogicalExpression",start:null,end:null,loc:null,range:null,left:{type:"BinaryExpression",start:null,end:null,loc:null,range:null,left:{type:"UnaryExpression",start:null,end:null,loc:null,range:null,operator:"typeof",prefix:true,argument:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"===",right:{type:"Literal",start:null,end:null,loc:null,range:null,value:"function",raw:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},operator:"&&",right:{type:"MemberExpression",start:null,end:null,loc:null,range:null,object:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},property:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"amd",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},computed:false,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"define",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"AMD_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:{type:"IfStatement",start:null,end:null,loc:null,range:null,test:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_TEST",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},consequent:{type:"BlockStatement",start:null,end:null,loc:null,range:null,body:[{type:"ExpressionStatement",start:null,end:null,loc:null,range:null,expression:{type:"CallExpression",start:null,end:null,loc:null,range:null,callee:{type:"Identifier",start:null,end:null,loc:null,range:null,name:"factory",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},arguments:[{type:"Identifier",start:null,end:null,loc:null,range:null,name:"COMMON_ARGUMENTS",_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},alternate:null,_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},expression:false,_scopeInfo:null,_declarations:null,extendedRange:null,tokens:null,raw:null},_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}],_declarations:null,extendedRange:null,_scopeInfo:null,tokens:null,raw:null}}
},{}]},{},[2])(2)});
|
client/tests/components/groups/CreateGroup.spec.js
|
johadi10/PostIt
|
import 'babel-polyfill';
import React from 'react';
import expect from 'expect';
import sinon from 'sinon';
import { mount } from 'enzyme';
import { CreateGroup } from '../../../src/components/groups/CreateGroup';
describe('<CreateGroup/>', () => {
// create a spy function for createGroup Action
const createGroup = sinon.spy();
// spy on handleCreateGroup of CreateGroup Page
sinon.spy(CreateGroup.prototype, 'handleCreateGroup');
const props = {
groupState: {},
createGroup
};
const wrapper = mount(<CreateGroup { ...props} />);
it('should check that there is a text field with group name', () => {
expect(wrapper.find('input').first().props().name).toBe('name');
});
it('Should check that there is a create group submit button', () => {
expect(wrapper.find('button').text()).toBe('Create group');
expect(wrapper.find('button').props().type).toBe('submit');
});
it('Should check that handleCreateGroup is called when form is submitted', () => {
wrapper.find('form').simulate('submit'); // trigger an event by form
// handleCreateGroup is called
expect(CreateGroup.prototype.handleCreateGroup.calledOnce).toBe(true);
});
});
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js
|
emmenko/react-router
|
import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
//static loadProps (params, cb) {
//cb(null, {
//assignments: COURSES[params.courseId].assignments
//});
//}
render () {
//var { assignments } = this.props;
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
packages/react-ui-components/src/Dialog/index.story.js
|
dimaip/neos-ui
|
import React from 'react';
import {storiesOf, action} from '@kadira/storybook';
import {withKnobs, text, boolean} from '@kadira/storybook-addon-knobs';
import {StoryWrapper} from './../_lib/storyUtils.js';
import Dialog from './index.js';
import Button from './../Button/index.js';
storiesOf('Dialog', module)
.addDecorator(withKnobs)
.addWithInfo(
'default',
'Dialog',
() => (
<StoryWrapper>
<Dialog
isOpen={boolean('Is opened?', true)}
title={text('Title', 'Hello title!')}
onRequestClose={action('onRequestClose')}
actions={[
<Button key="foo">An action button</Button>
]}
style="wide"
>
{text('Inner content', 'Hello world!')}
</Dialog>
</StoryWrapper>
),
{inline: true, source: false}
)
.addWithInfo(
'narrow',
'Dialog',
() => (
<StoryWrapper>
<Dialog
isOpen={boolean('Is opened?', true)}
title={text('Title', 'Hello title!')}
onRequestClose={action('onRequestClose')}
actions={[
<Button key="foo">An action button</Button>
]}
style="narrow"
>
{text('Inner content', 'Hello world!')}
</Dialog>
</StoryWrapper>
),
{inline: true, source: false}
);
|
packages/forms/src/deprecated/fields/ObjectField.js
|
Talend/ui
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
getUiOptions,
getWidget,
orderProperties,
retrieveSchema,
getDefaultRegistry,
} from 'react-jsonschema-form/lib/utils';
function DefaultObjectFieldTemplate(props) {
const { TitleField, DescriptionField } = props;
return (
<fieldset>
{(props.uiSchema['ui:title'] || props.title) && (
<TitleField
id={`${props.idSchema.$id}__title`}
title={props.title || props.uiSchema['ui:title']}
required={props.required}
formContext={props.formContext}
/>
)}
{props.description && (
<DescriptionField
id={`${props.idSchema.$id}__description`}
description={props.description}
formContext={props.formContext}
/>
)}
{props.properties.map(prop => prop.content)}
</fieldset>
);
}
if (process.env.NODE_ENV !== 'production') {
DefaultObjectFieldTemplate.propTypes = {
TitleField: PropTypes.func.isRequired,
DescriptionField: PropTypes.func.isRequired,
description: PropTypes.string,
formContext: PropTypes.object,
idSchema: PropTypes.shape({
$id: PropTypes.string,
}).isRequired,
properties: PropTypes.arrayOf(PropTypes.object).isRequired,
required: PropTypes.bool,
title: PropTypes.string,
uiSchema: PropTypes.object.isRequired,
};
}
class ObjectField extends Component {
static defaultProps = {
uiSchema: {},
formData: {},
errorSchema: {},
idSchema: {},
registry: getDefaultRegistry(),
required: false,
disabled: false,
readonly: false,
};
onPropertyChange = (id, name) => (value, options) => {
const newFormData = { ...this.props.formData, [name]: value };
if (this.props.registry.formContext.handleSchemaChange) {
this.props.registry.formContext.handleSchemaChange(newFormData, id, name, value, options);
}
this.props.onChange(newFormData, options);
};
isRequired(name) {
const schema = this.props.schema;
return Array.isArray(schema.required) && schema.required.indexOf(name) !== -1;
}
render() {
const {
uiSchema,
formData,
errorSchema,
idSchema,
name,
required,
disabled,
readonly,
onBlur,
onChange,
onFocus,
registry,
} = this.props;
const { definitions, fields, formContext, widgets } = registry;
const { SchemaField, TitleField, DescriptionField } = fields;
const schema = retrieveSchema(this.props.schema, definitions);
const { widget, ...options } = getUiOptions(uiSchema);
if (typeof widget === 'string') {
if (widget === 'hidden') {
return null;
}
const Widget = getWidget(schema, widget, widgets);
const onChangeHandler = value => {
onChange(value, options);
};
return (
<Widget
id={idSchema && idSchema.$id}
onChange={onChangeHandler}
schema={schema}
formData={formData}
uiSchema={uiSchema}
registry={this.props.registry}
definitions={definitions}
/>
);
}
const title = schema.title === undefined ? name : schema.title;
const description = uiSchema['ui:description'] || schema.description;
let orderedProperties;
try {
const properties = Object.keys(schema.properties);
orderedProperties = orderProperties(properties, uiSchema['ui:order']);
} catch (err) {
return (
<div>
<p className="config-error" style={{ color: 'red' }}>
Invalid {name || 'root'} object field configuration:
<em>{err.message}</em>.
</p>
<pre>{JSON.stringify(schema)}</pre>
</div>
);
}
const Template = registry.ObjectFieldTemplate || DefaultObjectFieldTemplate;
const templateProps = {
title: uiSchema['ui:title'] || title,
description,
TitleField,
DescriptionField,
properties: orderedProperties.map(propName => ({
content: (
<SchemaField
key={propName}
name={propName}
required={this.isRequired(propName)}
schema={schema.properties[propName]}
uiSchema={uiSchema[propName]}
errorSchema={errorSchema[propName]}
idSchema={idSchema[propName]}
formData={formData[propName]}
onChange={this.onPropertyChange(schema.id, propName)}
onBlur={onBlur}
onFocus={onFocus}
registry={registry}
disabled={disabled}
readonly={readonly}
/>
),
propName,
readonly,
disabled,
required,
})),
required,
idSchema,
uiSchema,
schema,
formData,
formContext,
};
return <Template {...templateProps} />;
}
}
if (process.env.NODE_ENV !== 'production') {
ObjectField.propTypes = {
schema: PropTypes.object.isRequired,
uiSchema: PropTypes.object,
errorSchema: PropTypes.object,
idSchema: PropTypes.object,
onChange: PropTypes.func.isRequired,
formData: PropTypes.object,
onBlur: PropTypes.func,
onFocus: PropTypes.func,
required: PropTypes.bool,
disabled: PropTypes.bool,
name: PropTypes.string,
readonly: PropTypes.bool,
registry: PropTypes.shape({
widgets: PropTypes.objectOf(PropTypes.oneOfType([PropTypes.func, PropTypes.object]))
.isRequired,
fields: PropTypes.objectOf(PropTypes.func).isRequired,
definitions: PropTypes.object.isRequired,
formContext: PropTypes.object.isRequired,
}),
};
}
export default ObjectField;
|
src/components/utilities/icons/TwitterIcon.js
|
jackson-/hireblack.io
|
import React from 'react'
import PropTypes from 'prop-types'
const Twitter = () => (
<svg className='twitter' x='0px' y='0px' width='30px' height='24px' viewBox='-4.98 -0.5 41.96 33' enableBackground='new -4.98 -0.5 41.96 33'>
<path d='M8.624,32c-4.403,0-8.807-1.205-12.683-3.614c-0.352-0.172-0.529-0.689-0.352-1.032s0.529-0.689,0.881-0.516c3.171,0.344,6.517-0.344,9.335-1.72c-2.642-0.86-4.932-2.925-5.813-5.677c-0.177-0.344,0-0.689,0.177-0.86s0.352-0.172,0.529-0.344c-2.113-1.549-3.523-4.129-3.523-6.71c0-0.344,0.177-0.689,0.352-0.86c0.352,0,0.704,0,0.881,0.172c0.177,0,0.177,0,0.352,0c-1.057-1.376-1.585-2.925-1.585-4.817c0-1.549,0.352-2.925,1.233-4.301c0.177-0.172,0.352-0.344,0.704-0.344S-0.36,1.548-0.184,1.72c3.699,4.301,8.983,7.054,14.619,7.57c0-0.344,0-0.516,0-0.86c0-4.645,3.875-8.43,8.807-8.43c2.29,0,4.403,0.86,6.165,2.409c1.585-0.344,2.994-0.86,4.403-1.72c0.352-0.172,0.704-0.172,1.057,0c0.352,0.172,0.352,0.516,0.352,0.86c-0.352,0.86-0.704,1.72-1.233,2.409c0.352-0.172,0.704-0.344,1.233-0.516c0.352-0.172,0.704,0,1.057,0.172c0.177,0.344,0.352,0.689,0,1.032c-1.057,1.549-2.29,2.753-3.875,3.957c0,0.172,0,0.344,0,0.516C32.227,20.473,23.42,32,8.624,32z'
/>
</svg>
)
Twitter.propTypes = {
fill: PropTypes.string, // this is the fill color for CSS use
width: PropTypes.string,
height: PropTypes.string
}
export default Twitter
|
resources/assets/js/components/AlertsComponent.js
|
jrm2k6/i-heart-reading
|
import React from 'react';
const AlertsComponent = ({ type, content }) => {
const _className = `alert-container ${type}`;
return (
<div className={_className}>
{content}
</div>
);
}
export default AlertsComponent;
|
src/components/tests/Comic.spec.js
|
laurazenc/react-marvel-comics
|
import React from 'react';
import {shallow} from 'enzyme';
import {Comic} from './../';
describe('<Comic />', () => {
const comic = {
thumbnail: {
path: '',
url: ''
},
creators: {
items: []
},
dates: [
{data: ''}
],
title: 'Spider-man'
};
const id = 0;
function openModal() {}
it('Should render the character\'s name', () => {
const wrapper = shallow(<Comic comic={comic} id={id} openModal={openModal()} />);
const actual = wrapper.find('.comic-name').text().trim();
const expected = 'Spider-man';
expect(actual).toEqual(expected);
});
});
|
ajax/libs/webshim/1.15.8/dev/shims/moxie/js/moxie-html4.js
|
JimBobSquarePants/cdnjs
|
/**
* mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill
* v1.2.1
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*
* Date: 2014-05-14
*/
/**
* Compiled inline version. (Library mode)
*/
/*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */
/*globals $code */
(function(exports, undefined) {
"use strict";
var modules = {};
function require(ids, callback) {
var module, defs = [];
for (var i = 0; i < ids.length; ++i) {
module = modules[ids[i]] || resolve(ids[i]);
if (!module) {
throw 'module definition dependecy not found: ' + ids[i];
}
defs.push(module);
}
callback.apply(null, defs);
}
function define(id, dependencies, definition) {
if (typeof id !== 'string') {
throw 'invalid module definition, module id must be defined and be a string';
}
if (dependencies === undefined) {
throw 'invalid module definition, dependencies must be specified';
}
if (definition === undefined) {
throw 'invalid module definition, definition function must be specified';
}
require(dependencies, function() {
modules[id] = definition.apply(null, arguments);
});
}
function defined(id) {
return !!modules[id];
}
function resolve(id) {
var target = exports;
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length; ++fi) {
if (!target[fragments[fi]]) {
return;
}
target = target[fragments[fi]];
}
return target;
}
function expose(ids) {
for (var i = 0; i < ids.length; i++) {
var target = exports;
var id = ids[i];
var fragments = id.split(/[.\/]/);
for (var fi = 0; fi < fragments.length - 1; ++fi) {
if (target[fragments[fi]] === undefined) {
target[fragments[fi]] = {};
}
target = target[fragments[fi]];
}
target[fragments[fragments.length - 1]] = modules[id];
}
}
// Included from: src/javascript/core/utils/Basic.js
/**
* Basic.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Basic', [], function() {
/**
Gets the true type of the built-in object (better version of typeof).
@author Angus Croll (http://javascriptweblog.wordpress.com/)
@method typeOf
@for Utils
@static
@param {Object} o Object to check.
@return {String} Object [[Class]]
*/
var typeOf = function(o) {
var undef;
if (o === undef) {
return 'undefined';
} else if (o === null) {
return 'null';
} else if (o.nodeType) {
return 'node';
}
// the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8
return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase();
};
/**
Extends the specified object with another object.
@method extend
@static
@param {Object} target Object to extend.
@param {Object} [obj]* Multiple objects to extend with.
@return {Object} Same as target, the extended object.
*/
var extend = function(target) {
var undef;
each(arguments, function(arg, i) {
if (i > 0) {
each(arg, function(value, key) {
if (value !== undef) {
if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) {
extend(target[key], value);
} else {
target[key] = value;
}
}
});
}
});
return target;
};
/**
Executes the callback function for each item in array/object. If you return false in the
callback it will break the loop.
@method each
@static
@param {Object} obj Object to iterate.
@param {function} callback Callback function to execute for each item.
*/
var each = function(obj, callback) {
var length, key, i, undef;
if (obj) {
try {
length = obj.length;
} catch(ex) {
length = undef;
}
if (length === undef) {
// Loop object items
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (callback(obj[key], key) === false) {
return;
}
}
}
} else {
// Loop array items
for (i = 0; i < length; i++) {
if (callback(obj[i], i) === false) {
return;
}
}
}
}
};
/**
Checks if object is empty.
@method isEmptyObj
@static
@param {Object} o Object to check.
@return {Boolean}
*/
var isEmptyObj = function(obj) {
var prop;
if (!obj || typeOf(obj) !== 'object') {
return true;
}
for (prop in obj) {
return false;
}
return true;
};
/**
Recieve an array of functions (usually async) to call in sequence, each function
receives a callback as first argument that it should call, when it completes. Finally,
after everything is complete, main callback is called. Passing truthy value to the
callback as a first argument will interrupt the sequence and invoke main callback
immediately.
@method inSeries
@static
@param {Array} queue Array of functions to call in sequence
@param {Function} cb Main callback that is called in the end, or in case of error
*/
var inSeries = function(queue, cb) {
var i = 0, length = queue.length;
if (typeOf(cb) !== 'function') {
cb = function() {};
}
if (!queue || !queue.length) {
cb();
}
function callNext(i) {
if (typeOf(queue[i]) === 'function') {
queue[i](function(error) {
/*jshint expr:true */
++i < length && !error ? callNext(i) : cb(error);
});
}
}
callNext(i);
};
/**
Recieve an array of functions (usually async) to call in parallel, each function
receives a callback as first argument that it should call, when it completes. After
everything is complete, main callback is called. Passing truthy value to the
callback as a first argument will interrupt the process and invoke main callback
immediately.
@method inParallel
@static
@param {Array} queue Array of functions to call in sequence
@param {Function} cb Main callback that is called in the end, or in case of erro
*/
var inParallel = function(queue, cb) {
var count = 0, num = queue.length, cbArgs = new Array(num);
each(queue, function(fn, i) {
fn(function(error) {
if (error) {
return cb(error);
}
var args = [].slice.call(arguments);
args.shift(); // strip error - undefined or not
cbArgs[i] = args;
count++;
if (count === num) {
cbArgs.unshift(null);
cb.apply(this, cbArgs);
}
});
});
};
/**
Find an element in array and return it's index if present, otherwise return -1.
@method inArray
@static
@param {Mixed} needle Element to find
@param {Array} array
@return {Int} Index of the element, or -1 if not found
*/
var inArray = function(needle, array) {
if (array) {
if (Array.prototype.indexOf) {
return Array.prototype.indexOf.call(array, needle);
}
for (var i = 0, length = array.length; i < length; i++) {
if (array[i] === needle) {
return i;
}
}
}
return -1;
};
/**
Returns elements of first array if they are not present in second. And false - otherwise.
@private
@method arrayDiff
@param {Array} needles
@param {Array} array
@return {Array|Boolean}
*/
var arrayDiff = function(needles, array) {
var diff = [];
if (typeOf(needles) !== 'array') {
needles = [needles];
}
if (typeOf(array) !== 'array') {
array = [array];
}
for (var i in needles) {
if (inArray(needles[i], array) === -1) {
diff.push(needles[i]);
}
}
return diff.length ? diff : false;
};
/**
Find intersection of two arrays.
@private
@method arrayIntersect
@param {Array} array1
@param {Array} array2
@return {Array} Intersection of two arrays or null if there is none
*/
var arrayIntersect = function(array1, array2) {
var result = [];
each(array1, function(item) {
if (inArray(item, array2) !== -1) {
result.push(item);
}
});
return result.length ? result : null;
};
/**
Forces anything into an array.
@method toArray
@static
@param {Object} obj Object with length field.
@return {Array} Array object containing all items.
*/
var toArray = function(obj) {
var i, arr = [];
for (i = 0; i < obj.length; i++) {
arr[i] = obj[i];
}
return arr;
};
/**
Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers.
The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages
to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique.
It's more probable for the earth to be hit with an ansteriod. Y
@method guid
@static
@param {String} prefix to prepend (by default 'o' will be prepended).
@method guid
@return {String} Virtually unique id.
*/
var guid = (function() {
var counter = 0;
return function(prefix) {
var guid = new Date().getTime().toString(32), i;
for (i = 0; i < 5; i++) {
guid += Math.floor(Math.random() * 65535).toString(32);
}
return (prefix || 'o_') + guid + (counter++).toString(32);
};
}());
/**
Trims white spaces around the string
@method trim
@static
@param {String} str
@return {String}
*/
var trim = function(str) {
if (!str) {
return str;
}
return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, '');
};
/**
Parses the specified size string into a byte value. For example 10kb becomes 10240.
@method parseSizeStr
@static
@param {String/Number} size String to parse or number to just pass through.
@return {Number} Size in bytes.
*/
var parseSizeStr = function(size) {
if (typeof(size) !== 'string') {
return size;
}
var muls = {
t: 1099511627776,
g: 1073741824,
m: 1048576,
k: 1024
},
mul;
size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, ''));
mul = size[2];
size = +size[1];
if (muls.hasOwnProperty(mul)) {
size *= muls[mul];
}
return size;
};
return {
guid: guid,
typeOf: typeOf,
extend: extend,
each: each,
isEmptyObj: isEmptyObj,
inSeries: inSeries,
inParallel: inParallel,
inArray: inArray,
arrayDiff: arrayDiff,
arrayIntersect: arrayIntersect,
toArray: toArray,
trim: trim,
parseSizeStr: parseSizeStr
};
});
// Included from: src/javascript/core/I18n.js
/**
* I18n.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/I18n", [
"moxie/core/utils/Basic"
], function(Basic) {
var i18n = {};
return {
/**
* Extends the language pack object with new items.
*
* @param {Object} pack Language pack items to add.
* @return {Object} Extended language pack object.
*/
addI18n: function(pack) {
return Basic.extend(i18n, pack);
},
/**
* Translates the specified string by checking for the english string in the language pack lookup.
*
* @param {String} str String to look for.
* @return {String} Translated string or the input string if it wasn't found.
*/
translate: function(str) {
return i18n[str] || str;
},
/**
* Shortcut for translate function
*
* @param {String} str String to look for.
* @return {String} Translated string or the input string if it wasn't found.
*/
_: function(str) {
return this.translate(str);
},
/**
* Pseudo sprintf implementation - simple way to replace tokens with specified values.
*
* @param {String} str String with tokens
* @return {String} String with replaced tokens
*/
sprintf: function(str) {
var args = [].slice.call(arguments, 1);
return str.replace(/%[a-z]/g, function() {
var value = args.shift();
return Basic.typeOf(value) !== 'undefined' ? value : '';
});
}
};
});
// Included from: src/javascript/core/utils/Mime.js
/**
* Mime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/utils/Mime", [
"moxie/core/utils/Basic",
"moxie/core/I18n"
], function(Basic, I18n) {
var mimeData = "" +
"application/msword,doc dot," +
"application/pdf,pdf," +
"application/pgp-signature,pgp," +
"application/postscript,ps ai eps," +
"application/rtf,rtf," +
"application/vnd.ms-excel,xls xlb," +
"application/vnd.ms-powerpoint,ppt pps pot," +
"application/zip,zip," +
"application/x-shockwave-flash,swf swfl," +
"application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," +
"application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," +
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," +
"application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," +
"application/vnd.openxmlformats-officedocument.presentationml.template,potx," +
"application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," +
"application/x-javascript,js," +
"application/json,json," +
"audio/mpeg,mp3 mpga mpega mp2," +
"audio/x-wav,wav," +
"audio/x-m4a,m4a," +
"audio/ogg,oga ogg," +
"audio/aiff,aiff aif," +
"audio/flac,flac," +
"audio/aac,aac," +
"audio/ac3,ac3," +
"audio/x-ms-wma,wma," +
"image/bmp,bmp," +
"image/gif,gif," +
"image/jpeg,jpg jpeg jpe," +
"image/photoshop,psd," +
"image/png,png," +
"image/svg+xml,svg svgz," +
"image/tiff,tiff tif," +
"text/plain,asc txt text diff log," +
"text/html,htm html xhtml," +
"text/css,css," +
"text/csv,csv," +
"text/rtf,rtf," +
"video/mpeg,mpeg mpg mpe m2v," +
"video/quicktime,qt mov," +
"video/mp4,mp4," +
"video/x-m4v,m4v," +
"video/x-flv,flv," +
"video/x-ms-wmv,wmv," +
"video/avi,avi," +
"video/webm,webm," +
"video/3gpp,3gpp 3gp," +
"video/3gpp2,3g2," +
"video/vnd.rn-realvideo,rv," +
"video/ogg,ogv," +
"video/x-matroska,mkv," +
"application/vnd.oasis.opendocument.formula-template,otf," +
"application/octet-stream,exe";
var Mime = {
mimes: {},
extensions: {},
// Parses the default mime types string into a mimes and extensions lookup maps
addMimeType: function (mimeData) {
var items = mimeData.split(/,/), i, ii, ext;
for (i = 0; i < items.length; i += 2) {
ext = items[i + 1].split(/ /);
// extension to mime lookup
for (ii = 0; ii < ext.length; ii++) {
this.mimes[ext[ii]] = items[i];
}
// mime to extension lookup
this.extensions[items[i]] = ext;
}
},
extList2mimes: function (filters, addMissingExtensions) {
var self = this, ext, i, ii, type, mimes = [];
// convert extensions to mime types list
for (i = 0; i < filters.length; i++) {
ext = filters[i].extensions.split(/\s*,\s*/);
for (ii = 0; ii < ext.length; ii++) {
// if there's an asterisk in the list, then accept attribute is not required
if (ext[ii] === '*') {
return [];
}
type = self.mimes[ext[ii]];
if (!type) {
if (addMissingExtensions && /^\w+$/.test(ext[ii])) {
mimes.push('.' + ext[ii]);
} else {
return []; // accept all
}
} else if (Basic.inArray(type, mimes) === -1) {
mimes.push(type);
}
}
}
return mimes;
},
mimes2exts: function(mimes) {
var self = this, exts = [];
Basic.each(mimes, function(mime) {
if (mime === '*') {
exts = [];
return false;
}
// check if this thing looks like mime type
var m = mime.match(/^(\w+)\/(\*|\w+)$/);
if (m) {
if (m[2] === '*') {
// wildcard mime type detected
Basic.each(self.extensions, function(arr, mime) {
if ((new RegExp('^' + m[1] + '/')).test(mime)) {
[].push.apply(exts, self.extensions[mime]);
}
});
} else if (self.extensions[mime]) {
[].push.apply(exts, self.extensions[mime]);
}
}
});
return exts;
},
mimes2extList: function(mimes) {
var accept = [], exts = [];
if (Basic.typeOf(mimes) === 'string') {
mimes = Basic.trim(mimes).split(/\s*,\s*/);
}
exts = this.mimes2exts(mimes);
accept.push({
title: I18n.translate('Files'),
extensions: exts.length ? exts.join(',') : '*'
});
// save original mimes string
accept.mimes = mimes;
return accept;
},
getFileExtension: function(fileName) {
var matches = fileName && fileName.match(/\.([^.]+)$/);
if (matches) {
return matches[1].toLowerCase();
}
return '';
},
getFileMime: function(fileName) {
return this.mimes[this.getFileExtension(fileName)] || '';
}
};
Mime.addMimeType(mimeData);
return Mime;
});
// Included from: src/javascript/core/utils/Env.js
/**
* Env.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/core/utils/Env", [
"moxie/core/utils/Basic"
], function(Basic) {
// UAParser.js v0.6.2
// Lightweight JavaScript-based User-Agent string parser
// https://github.com/faisalman/ua-parser-js
//
// Copyright © 2012-2013 Faisalman <fyzlman@gmail.com>
// Dual licensed under GPLv2 & MIT
var UAParser = (function (undefined) {
//////////////
// Constants
/////////////
var EMPTY = '',
UNKNOWN = '?',
FUNC_TYPE = 'function',
UNDEF_TYPE = 'undefined',
OBJ_TYPE = 'object',
MAJOR = 'major',
MODEL = 'model',
NAME = 'name',
TYPE = 'type',
VENDOR = 'vendor',
VERSION = 'version',
ARCHITECTURE= 'architecture',
CONSOLE = 'console',
MOBILE = 'mobile',
TABLET = 'tablet';
///////////
// Helper
//////////
var util = {
has : function (str1, str2) {
return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1;
},
lowerize : function (str) {
return str.toLowerCase();
}
};
///////////////
// Map helper
//////////////
var mapper = {
rgx : function () {
// loop through all regexes maps
for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) {
var regex = args[i], // even sequence (0,2,4,..)
props = args[i + 1]; // odd sequence (1,3,5,..)
// construct object barebones
if (typeof(result) === UNDEF_TYPE) {
result = {};
for (p in props) {
q = props[p];
if (typeof(q) === OBJ_TYPE) {
result[q[0]] = undefined;
} else {
result[q] = undefined;
}
}
}
// try matching uastring with regexes
for (j = k = 0; j < regex.length; j++) {
matches = regex[j].exec(this.getUA());
if (!!matches) {
for (p = 0; p < props.length; p++) {
match = matches[++k];
q = props[p];
// check if given property is actually array
if (typeof(q) === OBJ_TYPE && q.length > 0) {
if (q.length == 2) {
if (typeof(q[1]) == FUNC_TYPE) {
// assign modified match
result[q[0]] = q[1].call(this, match);
} else {
// assign given value, ignore regex match
result[q[0]] = q[1];
}
} else if (q.length == 3) {
// check whether function or regex
if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) {
// call function (usually string mapper)
result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined;
} else {
// sanitize match using given regex
result[q[0]] = match ? match.replace(q[1], q[2]) : undefined;
}
} else if (q.length == 4) {
result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined;
}
} else {
result[q] = match ? match : undefined;
}
}
break;
}
}
if(!!matches) break; // break the loop immediately if match found
}
return result;
},
str : function (str, map) {
for (var i in map) {
// check if array
if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) {
for (var j = 0; j < map[i].length; j++) {
if (util.has(map[i][j], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
} else if (util.has(map[i], str)) {
return (i === UNKNOWN) ? undefined : i;
}
}
return str;
}
};
///////////////
// String map
//////////////
var maps = {
browser : {
oldsafari : {
major : {
'1' : ['/8', '/1', '/3'],
'2' : '/4',
'?' : '/'
},
version : {
'1.0' : '/8',
'1.2' : '/1',
'1.3' : '/3',
'2.0' : '/412',
'2.0.2' : '/416',
'2.0.3' : '/417',
'2.0.4' : '/419',
'?' : '/'
}
}
},
device : {
sprint : {
model : {
'Evo Shift 4G' : '7373KT'
},
vendor : {
'HTC' : 'APA',
'Sprint' : 'Sprint'
}
}
},
os : {
windows : {
version : {
'ME' : '4.90',
'NT 3.11' : 'NT3.51',
'NT 4.0' : 'NT4.0',
'2000' : 'NT 5.0',
'XP' : ['NT 5.1', 'NT 5.2'],
'Vista' : 'NT 6.0',
'7' : 'NT 6.1',
'8' : 'NT 6.2',
'8.1' : 'NT 6.3',
'RT' : 'ARM'
}
}
}
};
//////////////
// Regex map
/////////////
var regexes = {
browser : [[
// Presto based
/(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini
/(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet
/(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80
/(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80
], [NAME, VERSION, MAJOR], [
/\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit
], [[NAME, 'Opera'], VERSION, MAJOR], [
// Mixed
/(kindle)\/((\d+)?[\w\.]+)/i, // Kindle
/(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i,
// Lunascape/Maxthon/Netfront/Jasmine/Blazer
// Trident based
/(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i,
// Avant/IEMobile/SlimBrowser/Baidu
/(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer
// Webkit/KHTML based
/(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq
/(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i
// Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron
], [NAME, VERSION, MAJOR], [
/(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11
], [[NAME, 'IE'], VERSION, MAJOR], [
/(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex
], [[NAME, 'Yandex'], VERSION, MAJOR], [
/(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon
], [[NAME, /_/g, ' '], VERSION, MAJOR], [
/(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i
// Chrome/OmniWeb/Arora/Tizen/Nokia
], [NAME, VERSION, MAJOR], [
/(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin
], [[NAME, 'Dolphin'], VERSION, MAJOR], [
/((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS
], [[NAME, 'Chrome'], VERSION, MAJOR], [
/((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser
], [[NAME, 'Android Browser'], VERSION, MAJOR], [
/version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari
], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [
/version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile
], [VERSION, MAJOR, NAME], [
/webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0
], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [
/(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror
/(webkit|khtml)\/((\d+)?[\w\.]+)/i
], [NAME, VERSION, MAJOR], [
// Gecko based
/(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape
], [[NAME, 'Netscape'], VERSION, MAJOR], [
/(swiftfox)/i, // Swiftfox
/(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i,
// IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror
/(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i,
// Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix
/(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla
// Other
/(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i,
// UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser
/(links)\s\(((\d+)?[\w\.]+)/i, // Links
/(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser
/(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser
/(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic
], [NAME, VERSION, MAJOR]
],
engine : [[
/(presto)\/([\w\.]+)/i, // Presto
/(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m
/(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links
/(icab)[\/\s]([23]\.[\d\.]+)/i // iCab
], [NAME, VERSION], [
/rv\:([\w\.]+).*(gecko)/i // Gecko
], [VERSION, NAME]
],
os : [[
// Windows based
/(windows)\snt\s6\.2;\s(arm)/i, // Windows RT
/(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i
], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [
/(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i
], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [
// Mobile/Embedded OS
/\((bb)(10);/i // BlackBerry 10
], [[NAME, 'BlackBerry'], VERSION], [
/(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry
/(tizen)\/([\w\.]+)/i, // Tizen
/(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i
// Android/WebOS/Palm/QNX/Bada/RIM/MeeGo
], [NAME, VERSION], [
/(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian
], [[NAME, 'Symbian'], VERSION],[
/mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS
], [[NAME, 'Firefox OS'], VERSION], [
// Console
/(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation
// GNU/Linux based
/(mint)[\/\s\(]?(\w+)*/i, // Mint
/(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i,
// Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware
// Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk
/(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux
/(gnu)\s?([\w\.]+)*/i // GNU
], [NAME, VERSION], [
/(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS
], [[NAME, 'Chromium OS'], VERSION],[
// Solaris
/(sunos)\s?([\w\.]+\d)*/i // Solaris
], [[NAME, 'Solaris'], VERSION], [
// BSD based
/\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly
], [NAME, VERSION],[
/(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS
], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [
/(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS
], [NAME, [VERSION, /_/g, '.']], [
// Other
/(haiku)\s(\w+)/i, // Haiku
/(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX
/(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i,
// Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS
/(unix)\s?([\w\.]+)*/i // UNIX
], [NAME, VERSION]
]
};
/////////////////
// Constructor
////////////////
var UAParser = function (uastring) {
var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY);
this.getBrowser = function () {
return mapper.rgx.apply(this, regexes.browser);
};
this.getEngine = function () {
return mapper.rgx.apply(this, regexes.engine);
};
this.getOS = function () {
return mapper.rgx.apply(this, regexes.os);
};
this.getResult = function() {
return {
ua : this.getUA(),
browser : this.getBrowser(),
engine : this.getEngine(),
os : this.getOS()
};
};
this.getUA = function () {
return ua;
};
this.setUA = function (uastring) {
ua = uastring;
return this;
};
this.setUA(ua);
};
return new UAParser().getResult();
})();
function version_compare(v1, v2, operator) {
// From: http://phpjs.org/functions
// + original by: Philippe Jausions (http://pear.php.net/user/jausions)
// + original by: Aidan Lister (http://aidanlister.com/)
// + reimplemented by: Kankrelune (http://www.webfaktory.info/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// + improved by: Scott Baker
// + improved by: Theriault
// * example 1: version_compare('8.2.5rc', '8.2.5a');
// * returns 1: 1
// * example 2: version_compare('8.2.50', '8.2.52', '<');
// * returns 2: true
// * example 3: version_compare('5.3.0-dev', '5.3.0');
// * returns 3: -1
// * example 4: version_compare('4.1.0.52','4.01.0.51');
// * returns 4: 1
// Important: compare must be initialized at 0.
var i = 0,
x = 0,
compare = 0,
// vm maps textual PHP versions to negatives so they're less than 0.
// PHP currently defines these as CASE-SENSITIVE. It is important to
// leave these as negatives so that they can come before numerical versions
// and as if no letters were there to begin with.
// (1alpha is < 1 and < 1.1 but > 1dev1)
// If a non-numerical value can't be mapped to this table, it receives
// -7 as its value.
vm = {
'dev': -6,
'alpha': -5,
'a': -5,
'beta': -4,
'b': -4,
'RC': -3,
'rc': -3,
'#': -2,
'p': 1,
'pl': 1
},
// This function will be called to prepare each version argument.
// It replaces every _, -, and + with a dot.
// It surrounds any nonsequence of numbers/dots with dots.
// It replaces sequences of dots with a single dot.
// version_compare('4..0', '4.0') == 0
// Important: A string of 0 length needs to be converted into a value
// even less than an unexisting value in vm (-7), hence [-8].
// It's also important to not strip spaces because of this.
// version_compare('', ' ') == 1
prepVersion = function (v) {
v = ('' + v).replace(/[_\-+]/g, '.');
v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.');
return (!v.length ? [-8] : v.split('.'));
},
// This converts a version component to a number.
// Empty component becomes 0.
// Non-numerical component becomes a negative number.
// Numerical component becomes itself as an integer.
numVersion = function (v) {
return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10));
};
v1 = prepVersion(v1);
v2 = prepVersion(v2);
x = Math.max(v1.length, v2.length);
for (i = 0; i < x; i++) {
if (v1[i] == v2[i]) {
continue;
}
v1[i] = numVersion(v1[i]);
v2[i] = numVersion(v2[i]);
if (v1[i] < v2[i]) {
compare = -1;
break;
} else if (v1[i] > v2[i]) {
compare = 1;
break;
}
}
if (!operator) {
return compare;
}
// Important: operator is CASE-SENSITIVE.
// "No operator" seems to be treated as "<."
// Any other values seem to make the function return null.
switch (operator) {
case '>':
case 'gt':
return (compare > 0);
case '>=':
case 'ge':
return (compare >= 0);
case '<=':
case 'le':
return (compare <= 0);
case '==':
case '=':
case 'eq':
return (compare === 0);
case '<>':
case '!=':
case 'ne':
return (compare !== 0);
case '':
case '<':
case 'lt':
return (compare < 0);
default:
return null;
}
}
var can = (function() {
var caps = {
define_property: (function() {
/* // currently too much extra code required, not exactly worth it
try { // as of IE8, getters/setters are supported only on DOM elements
var obj = {};
if (Object.defineProperty) {
Object.defineProperty(obj, 'prop', {
enumerable: true,
configurable: true
});
return true;
}
} catch(ex) {}
if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) {
return true;
}*/
return false;
}()),
create_canvas: (function() {
// On the S60 and BB Storm, getContext exists, but always returns undefined
// so we actually have to call getContext() to verify
// github.com/Modernizr/Modernizr/issues/issue/97/
var el = document.createElement('canvas');
return !!(el.getContext && el.getContext('2d'));
}()),
return_response_type: function(responseType) {
try {
if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) {
return true;
} else if (window.XMLHttpRequest) {
var xhr = new XMLHttpRequest();
xhr.open('get', '/'); // otherwise Gecko throws an exception
if ('responseType' in xhr) {
xhr.responseType = responseType;
// as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?)
if (xhr.responseType !== responseType) {
return false;
}
return true;
}
}
} catch (ex) {}
return false;
},
// ideas for this heavily come from Modernizr (http://modernizr.com/)
use_data_uri: (function() {
var du = new Image();
du.onload = function() {
caps.use_data_uri = (du.width === 1 && du.height === 1);
};
setTimeout(function() {
du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==";
}, 1);
return false;
}()),
use_data_uri_over32kb: function() { // IE8
return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9);
},
use_data_uri_of: function(bytes) {
return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb());
},
use_fileinput: function() {
var el = document.createElement('input');
el.setAttribute('type', 'file');
return !el.disabled;
}
};
return function(cap) {
var args = [].slice.call(arguments);
args.shift(); // shift of cap
return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap];
};
}());
var Env = {
can: can,
browser: UAParser.browser.name,
version: parseFloat(UAParser.browser.major),
os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason
osVersion: UAParser.os.version,
verComp: version_compare,
swf_url: "../flash/Moxie.swf",
xap_url: "../silverlight/Moxie.xap",
global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent"
};
// for backward compatibility
// @deprecated Use `Env.os` instead
Env.OS = Env.os;
return Env;
});
// Included from: src/javascript/core/utils/Dom.js
/**
* Dom.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) {
/**
Get DOM Element by it's id.
@method get
@for Utils
@param {String} id Identifier of the DOM Element
@return {DOMElement}
*/
var get = function(id) {
if (typeof id !== 'string') {
return id;
}
return document.getElementById(id);
};
/**
Checks if specified DOM element has specified class.
@method hasClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var hasClass = function(obj, name) {
if (!obj.className) {
return false;
}
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
return regExp.test(obj.className);
};
/**
Adds specified className to specified DOM element.
@method addClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var addClass = function(obj, name) {
if (!hasClass(obj, name)) {
obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name;
}
};
/**
Removes specified className from specified DOM element.
@method removeClass
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Class name
*/
var removeClass = function(obj, name) {
if (obj.className) {
var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)");
obj.className = obj.className.replace(regExp, function($0, $1, $2) {
return $1 === ' ' && $2 === ' ' ? ' ' : '';
});
}
};
/**
Returns a given computed style of a DOM element.
@method getStyle
@static
@param {Object} obj DOM element like object.
@param {String} name Style you want to get from the DOM element
*/
var getStyle = function(obj, name) {
if (obj.currentStyle) {
return obj.currentStyle[name];
} else if (window.getComputedStyle) {
return window.getComputedStyle(obj, null)[name];
}
};
/**
Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields.
@method getPos
@static
@param {Element} node HTML element or element id to get x, y position from.
@param {Element} root Optional root element to stop calculations at.
@return {object} Absolute position of the specified element object with x, y fields.
*/
var getPos = function(node, root) {
var x = 0, y = 0, parent, doc = document, nodeRect, rootRect;
node = node;
root = root || doc.body;
// Returns the x, y cordinate for an element on IE 6 and IE 7
function getIEPos(node) {
var bodyElm, rect, x = 0, y = 0;
if (node) {
rect = node.getBoundingClientRect();
bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body;
x = rect.left + bodyElm.scrollLeft;
y = rect.top + bodyElm.scrollTop;
}
return {
x : x,
y : y
};
}
// Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode
if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) {
nodeRect = getIEPos(node);
rootRect = getIEPos(root);
return {
x : nodeRect.x - rootRect.x,
y : nodeRect.y - rootRect.y
};
}
parent = node;
while (parent && parent != root && parent.nodeType) {
x += parent.offsetLeft || 0;
y += parent.offsetTop || 0;
parent = parent.offsetParent;
}
parent = node.parentNode;
while (parent && parent != root && parent.nodeType) {
x -= parent.scrollLeft || 0;
y -= parent.scrollTop || 0;
parent = parent.parentNode;
}
return {
x : x,
y : y
};
};
/**
Returns the size of the specified node in pixels.
@method getSize
@static
@param {Node} node Node to get the size of.
@return {Object} Object with a w and h property.
*/
var getSize = function(node) {
return {
w : node.offsetWidth || node.clientWidth,
h : node.offsetHeight || node.clientHeight
};
};
return {
get: get,
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
getStyle: getStyle,
getPos: getPos,
getSize: getSize
};
});
// Included from: src/javascript/core/Exceptions.js
/**
* Exceptions.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/Exceptions', [
'moxie/core/utils/Basic'
], function(Basic) {
function _findKey(obj, value) {
var key;
for (key in obj) {
if (obj[key] === value) {
return key;
}
}
return null;
}
return {
RuntimeError: (function() {
var namecodes = {
NOT_INIT_ERR: 1,
NOT_SUPPORTED_ERR: 9,
JS_ERR: 4
};
function RuntimeError(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": RuntimeError " + this.code;
}
Basic.extend(RuntimeError, namecodes);
RuntimeError.prototype = Error.prototype;
return RuntimeError;
}()),
OperationNotAllowedException: (function() {
function OperationNotAllowedException(code) {
this.code = code;
this.name = 'OperationNotAllowedException';
}
Basic.extend(OperationNotAllowedException, {
NOT_ALLOWED_ERR: 1
});
OperationNotAllowedException.prototype = Error.prototype;
return OperationNotAllowedException;
}()),
ImageError: (function() {
var namecodes = {
WRONG_FORMAT: 1,
MAX_RESOLUTION_ERR: 2
};
function ImageError(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": ImageError " + this.code;
}
Basic.extend(ImageError, namecodes);
ImageError.prototype = Error.prototype;
return ImageError;
}()),
FileException: (function() {
var namecodes = {
NOT_FOUND_ERR: 1,
SECURITY_ERR: 2,
ABORT_ERR: 3,
NOT_READABLE_ERR: 4,
ENCODING_ERR: 5,
NO_MODIFICATION_ALLOWED_ERR: 6,
INVALID_STATE_ERR: 7,
SYNTAX_ERR: 8
};
function FileException(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": FileException " + this.code;
}
Basic.extend(FileException, namecodes);
FileException.prototype = Error.prototype;
return FileException;
}()),
DOMException: (function() {
var namecodes = {
INDEX_SIZE_ERR: 1,
DOMSTRING_SIZE_ERR: 2,
HIERARCHY_REQUEST_ERR: 3,
WRONG_DOCUMENT_ERR: 4,
INVALID_CHARACTER_ERR: 5,
NO_DATA_ALLOWED_ERR: 6,
NO_MODIFICATION_ALLOWED_ERR: 7,
NOT_FOUND_ERR: 8,
NOT_SUPPORTED_ERR: 9,
INUSE_ATTRIBUTE_ERR: 10,
INVALID_STATE_ERR: 11,
SYNTAX_ERR: 12,
INVALID_MODIFICATION_ERR: 13,
NAMESPACE_ERR: 14,
INVALID_ACCESS_ERR: 15,
VALIDATION_ERR: 16,
TYPE_MISMATCH_ERR: 17,
SECURITY_ERR: 18,
NETWORK_ERR: 19,
ABORT_ERR: 20,
URL_MISMATCH_ERR: 21,
QUOTA_EXCEEDED_ERR: 22,
TIMEOUT_ERR: 23,
INVALID_NODE_TYPE_ERR: 24,
DATA_CLONE_ERR: 25
};
function DOMException(code) {
this.code = code;
this.name = _findKey(namecodes, code);
this.message = this.name + ": DOMException " + this.code;
}
Basic.extend(DOMException, namecodes);
DOMException.prototype = Error.prototype;
return DOMException;
}()),
EventException: (function() {
function EventException(code) {
this.code = code;
this.name = 'EventException';
}
Basic.extend(EventException, {
UNSPECIFIED_EVENT_TYPE_ERR: 0
});
EventException.prototype = Error.prototype;
return EventException;
}())
};
});
// Included from: src/javascript/core/EventTarget.js
/**
* EventTarget.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/EventTarget', [
'moxie/core/Exceptions',
'moxie/core/utils/Basic'
], function(x, Basic) {
/**
Parent object for all event dispatching components and objects
@class EventTarget
@constructor EventTarget
*/
function EventTarget() {
// hash of event listeners by object uid
var eventpool = {};
Basic.extend(this, {
/**
Unique id of the event dispatcher, usually overriden by children
@property uid
@type String
*/
uid: null,
/**
Can be called from within a child in order to acquire uniqie id in automated manner
@method init
*/
init: function() {
if (!this.uid) {
this.uid = Basic.guid('uid_');
}
},
/**
Register a handler to a specific event dispatched by the object
@method addEventListener
@param {String} type Type or basically a name of the event to subscribe to
@param {Function} fn Callback function that will be called when event happens
@param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first
@param {Object} [scope=this] A scope to invoke event handler in
*/
addEventListener: function(type, fn, priority, scope) {
var self = this, list;
type = Basic.trim(type);
if (/\s/.test(type)) {
// multiple event types were passed for one handler
Basic.each(type.split(/\s+/), function(type) {
self.addEventListener(type, fn, priority, scope);
});
return;
}
type = type.toLowerCase();
priority = parseInt(priority, 10) || 0;
list = eventpool[this.uid] && eventpool[this.uid][type] || [];
list.push({fn : fn, priority : priority, scope : scope || this});
if (!eventpool[this.uid]) {
eventpool[this.uid] = {};
}
eventpool[this.uid][type] = list;
},
/**
Check if any handlers were registered to the specified event
@method hasEventListener
@param {String} type Type or basically a name of the event to check
@return {Mixed} Returns a handler if it was found and false, if - not
*/
hasEventListener: function(type) {
return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid];
},
/**
Unregister the handler from the event, or if former was not specified - unregister all handlers
@method removeEventListener
@param {String} type Type or basically a name of the event
@param {Function} [fn] Handler to unregister
*/
removeEventListener: function(type, fn) {
type = type.toLowerCase();
var list = eventpool[this.uid] && eventpool[this.uid][type], i;
if (list) {
if (fn) {
for (i = list.length - 1; i >= 0; i--) {
if (list[i].fn === fn) {
list.splice(i, 1);
break;
}
}
} else {
list = [];
}
// delete event list if it has become empty
if (!list.length) {
delete eventpool[this.uid][type];
// and object specific entry in a hash if it has no more listeners attached
if (Basic.isEmptyObj(eventpool[this.uid])) {
delete eventpool[this.uid];
}
}
}
},
/**
Remove all event handlers from the object
@method removeAllEventListeners
*/
removeAllEventListeners: function() {
if (eventpool[this.uid]) {
delete eventpool[this.uid];
}
},
/**
Dispatch the event
@method dispatchEvent
@param {String/Object} Type of event or event object to dispatch
@param {Mixed} [...] Variable number of arguments to be passed to a handlers
@return {Boolean} true by default and false if any handler returned false
*/
dispatchEvent: function(type) {
var uid, list, args, tmpEvt, evt = {}, result = true, undef;
if (Basic.typeOf(type) !== 'string') {
// we can't use original object directly (because of Silverlight)
tmpEvt = type;
if (Basic.typeOf(tmpEvt.type) === 'string') {
type = tmpEvt.type;
if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event
evt.total = tmpEvt.total;
evt.loaded = tmpEvt.loaded;
}
evt.async = tmpEvt.async || false;
} else {
throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR);
}
}
// check if event is meant to be dispatched on an object having specific uid
if (type.indexOf('::') !== -1) {
(function(arr) {
uid = arr[0];
type = arr[1];
}(type.split('::')));
} else {
uid = this.uid;
}
type = type.toLowerCase();
list = eventpool[uid] && eventpool[uid][type];
if (list) {
// sort event list by prority
list.sort(function(a, b) { return b.priority - a.priority; });
args = [].slice.call(arguments);
// first argument will be pseudo-event object
args.shift();
evt.type = type;
args.unshift(evt);
// Dispatch event to all listeners
var queue = [];
Basic.each(list, function(handler) {
// explicitly set the target, otherwise events fired from shims do not get it
args[0].target = handler.scope;
// if event is marked as async, detach the handler
if (evt.async) {
queue.push(function(cb) {
setTimeout(function() {
cb(handler.fn.apply(handler.scope, args) === false);
}, 1);
});
} else {
queue.push(function(cb) {
cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation
});
}
});
if (queue.length) {
Basic.inSeries(queue, function(err) {
result = !err;
});
}
}
return result;
},
/**
Alias for addEventListener
@method bind
@protected
*/
bind: function() {
this.addEventListener.apply(this, arguments);
},
/**
Alias for removeEventListener
@method unbind
@protected
*/
unbind: function() {
this.removeEventListener.apply(this, arguments);
},
/**
Alias for removeAllEventListeners
@method unbindAll
@protected
*/
unbindAll: function() {
this.removeAllEventListeners.apply(this, arguments);
},
/**
Alias for dispatchEvent
@method trigger
@protected
*/
trigger: function() {
return this.dispatchEvent.apply(this, arguments);
},
/**
Converts properties of on[event] type to corresponding event handlers,
is used to avoid extra hassle around the process of calling them back
@method convertEventPropsToHandlers
@private
*/
convertEventPropsToHandlers: function(handlers) {
var h;
if (Basic.typeOf(handlers) !== 'array') {
handlers = [handlers];
}
for (var i = 0; i < handlers.length; i++) {
h = 'on' + handlers[i];
if (Basic.typeOf(this[h]) === 'function') {
this.addEventListener(handlers[i], this[h]);
} else if (Basic.typeOf(this[h]) === 'undefined') {
this[h] = null; // object must have defined event properties, even if it doesn't make use of them
}
}
}
});
}
EventTarget.instance = new EventTarget();
return EventTarget;
});
// Included from: src/javascript/core/utils/Encode.js
/**
* Encode.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Encode', [], function() {
/**
Encode string with UTF-8
@method utf8_encode
@for Utils
@static
@param {String} str String to encode
@return {String} UTF-8 encoded string
*/
var utf8_encode = function(str) {
return unescape(encodeURIComponent(str));
};
/**
Decode UTF-8 encoded string
@method utf8_decode
@static
@param {String} str String to decode
@return {String} Decoded string
*/
var utf8_decode = function(str_data) {
return decodeURIComponent(escape(str_data));
};
/**
Decode Base64 encoded string (uses browser's default method if available),
from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js
@method atob
@static
@param {String} data String to decode
@return {String} Decoded string
*/
var atob = function(data, utf8) {
if (typeof(window.atob) === 'function') {
return utf8 ? utf8_decode(window.atob(data)) : window.atob(data);
}
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window.atob == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 == 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return utf8 ? utf8_decode(dec) : dec;
};
/**
Base64 encode string (uses browser's default method if available),
from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js
@method btoa
@static
@param {String} data String to encode
@return {String} Base64 encoded string
*/
var btoa = function(data, utf8) {
if (utf8) {
utf8_encode(data);
}
if (typeof(window.btoa) === 'function') {
return window.btoa(data);
}
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Bayron Guevara
// + improved by: Thunder.m
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + improved by: Rafał Kukawski (http://kukawski.pl)
// * example 1: base64_encode('Kevin van Zonneveld');
// * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
// mozilla has this native
// - but breaks in 2.0.0.12!
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
var o1, o2, o3, h1, h2, h3, h4, bits, i = 0,
ac = 0,
enc = "",
tmp_arr = [];
if (!data) {
return data;
}
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
} while (i < data.length);
enc = tmp_arr.join('');
var r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
};
return {
utf8_encode: utf8_encode,
utf8_decode: utf8_decode,
atob: atob,
btoa: btoa
};
});
// Included from: src/javascript/runtime/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/Runtime', [
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/EventTarget"
], function(Basic, Dom, EventTarget) {
var runtimeConstructors = {}, runtimes = {};
/**
Common set of methods and properties for every runtime instance
@class Runtime
@param {Object} options
@param {String} type Sanitized name of the runtime
@param {Object} [caps] Set of capabilities that differentiate specified runtime
@param {Object} [modeCaps] Set of capabilities that do require specific operational mode
@param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested
*/
function Runtime(options, type, caps, modeCaps, preferredMode) {
/**
Dispatched when runtime is initialized and ready.
Results in RuntimeInit on a connected component.
@event Init
*/
/**
Dispatched when runtime fails to initialize.
Results in RuntimeError on a connected component.
@event Error
*/
var self = this
, _shim
, _uid = Basic.guid(type + '_')
, defaultMode = preferredMode || 'browser'
;
options = options || {};
// register runtime in private hash
runtimes[_uid] = this;
/**
Default set of capabilities, which can be redifined later by specific runtime
@private
@property caps
@type Object
*/
caps = Basic.extend({
// Runtime can:
// provide access to raw binary data of the file
access_binary: false,
// provide access to raw binary data of the image (image extension is optional)
access_image_binary: false,
// display binary data as thumbs for example
display_media: false,
// make cross-domain requests
do_cors: false,
// accept files dragged and dropped from the desktop
drag_and_drop: false,
// filter files in selection dialog by their extensions
filter_by_extension: true,
// resize image (and manipulate it raw data of any file in general)
resize_image: false,
// periodically report how many bytes of total in the file were uploaded (loaded)
report_upload_progress: false,
// provide access to the headers of http response
return_response_headers: false,
// support response of specific type, which should be passed as an argument
// e.g. runtime.can('return_response_type', 'blob')
return_response_type: false,
// return http status code of the response
return_status_code: true,
// send custom http header with the request
send_custom_headers: false,
// pick up the files from a dialog
select_file: false,
// select whole folder in file browse dialog
select_folder: false,
// select multiple files at once in file browse dialog
select_multiple: true,
// send raw binary data, that is generated after image resizing or manipulation of other kind
send_binary_string: false,
// send cookies with http request and therefore retain session
send_browser_cookies: true,
// send data formatted as multipart/form-data
send_multipart: true,
// slice the file or blob to smaller parts
slice_blob: false,
// upload file without preloading it to memory, stream it out directly from disk
stream_upload: false,
// programmatically trigger file browse dialog
summon_file_dialog: false,
// upload file of specific size, size should be passed as argument
// e.g. runtime.can('upload_filesize', '500mb')
upload_filesize: true,
// initiate http request with specific http method, method should be passed as argument
// e.g. runtime.can('use_http_method', 'put')
use_http_method: true
}, caps);
// default to the mode that is compatible with preferred caps
if (options.preferred_caps) {
defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode);
}
// small extension factory here (is meant to be extended with actual extensions constructors)
_shim = (function() {
var objpool = {};
return {
exec: function(uid, comp, fn, args) {
if (_shim[comp]) {
if (!objpool[uid]) {
objpool[uid] = {
context: this,
instance: new _shim[comp]()
};
}
if (objpool[uid].instance[fn]) {
return objpool[uid].instance[fn].apply(this, args);
}
}
},
removeInstance: function(uid) {
delete objpool[uid];
},
removeAllInstances: function() {
var self = this;
Basic.each(objpool, function(obj, uid) {
if (Basic.typeOf(obj.instance.destroy) === 'function') {
obj.instance.destroy.call(obj.context);
}
self.removeInstance(uid);
});
}
};
}());
// public methods
Basic.extend(this, {
/**
Specifies whether runtime instance was initialized or not
@property initialized
@type {Boolean}
@default false
*/
initialized: false, // shims require this flag to stop initialization retries
/**
Unique ID of the runtime
@property uid
@type {String}
*/
uid: _uid,
/**
Runtime type (e.g. flash, html5, etc)
@property type
@type {String}
*/
type: type,
/**
Runtime (not native one) may operate in browser or client mode.
@property mode
@private
@type {String|Boolean} current mode or false, if none possible
*/
mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode),
/**
id of the DOM container for the runtime (if available)
@property shimid
@type {String}
*/
shimid: _uid + '_container',
/**
Number of connected clients. If equal to zero, runtime can be destroyed
@property clients
@type {Number}
*/
clients: 0,
/**
Runtime initialization options
@property options
@type {Object}
*/
options: options,
/**
Checks if the runtime has specific capability
@method can
@param {String} cap Name of capability to check
@param {Mixed} [value] If passed, capability should somehow correlate to the value
@param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set)
@return {Boolean} true if runtime has such capability and false, if - not
*/
can: function(cap, value) {
var refCaps = arguments[2] || caps;
// if cap var is a comma-separated list of caps, convert it to object (key/value)
if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') {
cap = Runtime.parseCaps(cap);
}
if (Basic.typeOf(cap) === 'object') {
for (var key in cap) {
if (!this.can(key, cap[key], refCaps)) {
return false;
}
}
return true;
}
// check the individual cap
if (Basic.typeOf(refCaps[cap]) === 'function') {
return refCaps[cap].call(this, value);
} else {
return (value === refCaps[cap]);
}
},
/**
Returns container for the runtime as DOM element
@method getShimContainer
@return {DOMElement}
*/
getShimContainer: function() {
var container, shimContainer = Dom.get(this.shimid);
// if no container for shim, create one
if (!shimContainer) {
container = this.options.container ? Dom.get(this.options.container) : document.body;
// create shim container and insert it at an absolute position into the outer container
shimContainer = document.createElement('div');
shimContainer.id = this.shimid;
shimContainer.className = 'moxie-shim moxie-shim-' + this.type;
Basic.extend(shimContainer.style, {
position: 'absolute',
top: '0px',
left: '0px',
width: '1px',
height: '1px',
overflow: 'hidden'
});
container.appendChild(shimContainer);
container = null;
}
return shimContainer;
},
/**
Returns runtime as DOM element (if appropriate)
@method getShim
@return {DOMElement}
*/
getShim: function() {
return _shim;
},
/**
Invokes a method within the runtime itself (might differ across the runtimes)
@method shimExec
@param {Mixed} []
@protected
@return {Mixed} Depends on the action and component
*/
shimExec: function(component, action) {
var args = [].slice.call(arguments, 2);
return self.getShim().exec.call(this, this.uid, component, action, args);
},
/**
Operaional interface that is used by components to invoke specific actions on the runtime
(is invoked in the scope of component)
@method exec
@param {Mixed} []*
@protected
@return {Mixed} Depends on the action and component
*/
exec: function(component, action) { // this is called in the context of component, not runtime
var args = [].slice.call(arguments, 2);
if (self[component] && self[component][action]) {
return self[component][action].apply(this, args);
}
return self.shimExec.apply(this, arguments);
},
/**
Destroys the runtime (removes all events and deletes DOM structures)
@method destroy
*/
destroy: function() {
if (!self) {
return; // obviously already destroyed
}
var shimContainer = Dom.get(this.shimid);
if (shimContainer) {
shimContainer.parentNode.removeChild(shimContainer);
}
if (_shim) {
_shim.removeAllInstances();
}
this.unbindAll();
delete runtimes[this.uid];
this.uid = null; // mark this runtime as destroyed
_uid = self = _shim = shimContainer = null;
}
});
// once we got the mode, test against all caps
if (this.mode && options.required_caps && !this.can(options.required_caps)) {
this.mode = false;
}
}
/**
Default order to try different runtime types
@property order
@type String
@static
*/
Runtime.order = 'html5,flash,silverlight,html4';
/**
Retrieves runtime from private hash by it's uid
@method getRuntime
@private
@static
@param {String} uid Unique identifier of the runtime
@return {Runtime|Boolean} Returns runtime, if it exists and false, if - not
*/
Runtime.getRuntime = function(uid) {
return runtimes[uid] ? runtimes[uid] : false;
};
/**
Register constructor for the Runtime of new (or perhaps modified) type
@method addConstructor
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@param {Function} construct Constructor for the Runtime type
*/
Runtime.addConstructor = function(type, constructor) {
constructor.prototype = EventTarget.instance;
runtimeConstructors[type] = constructor;
};
/**
Get the constructor for the specified type.
method getConstructor
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@return {Function} Constructor for the Runtime type
*/
Runtime.getConstructor = function(type) {
return runtimeConstructors[type] || null;
};
/**
Get info about the runtime (uid, type, capabilities)
@method getInfo
@static
@param {String} uid Unique identifier of the runtime
@return {Mixed} Info object or null if runtime doesn't exist
*/
Runtime.getInfo = function(uid) {
var runtime = Runtime.getRuntime(uid);
if (runtime) {
return {
uid: runtime.uid,
type: runtime.type,
mode: runtime.mode,
can: function() {
return runtime.can.apply(runtime, arguments);
}
};
}
return null;
};
/**
Convert caps represented by a comma-separated string to the object representation.
@method parseCaps
@static
@param {String} capStr Comma-separated list of capabilities
@return {Object}
*/
Runtime.parseCaps = function(capStr) {
var capObj = {};
if (Basic.typeOf(capStr) !== 'string') {
return capStr || {};
}
Basic.each(capStr.split(','), function(key) {
capObj[key] = true; // we assume it to be - true
});
return capObj;
};
/**
Test the specified runtime for specific capabilities.
@method can
@static
@param {String} type Runtime type (e.g. flash, html5, etc)
@param {String|Object} caps Set of capabilities to check
@return {Boolean} Result of the test
*/
Runtime.can = function(type, caps) {
var runtime
, constructor = Runtime.getConstructor(type)
, mode
;
if (constructor) {
runtime = new constructor({
required_caps: caps
});
mode = runtime.mode;
runtime.destroy();
return !!mode;
}
return false;
};
/**
Figure out a runtime that supports specified capabilities.
@method thatCan
@static
@param {String|Object} caps Set of capabilities to check
@param {String} [runtimeOrder] Comma-separated list of runtimes to check against
@return {String} Usable runtime identifier or null
*/
Runtime.thatCan = function(caps, runtimeOrder) {
var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/);
for (var i in types) {
if (Runtime.can(types[i], caps)) {
return types[i];
}
}
return null;
};
/**
Figure out an operational mode for the specified set of capabilities.
@method getMode
@static
@param {Object} modeCaps Set of capabilities that depend on particular runtime mode
@param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for
@param {String|Boolean} [defaultMode='browser'] Default mode to use
@return {String|Boolean} Compatible operational mode
*/
Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) {
var mode = null;
if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified
defaultMode = 'browser';
}
if (requiredCaps && !Basic.isEmptyObj(modeCaps)) {
// loop over required caps and check if they do require the same mode
Basic.each(requiredCaps, function(value, cap) {
if (modeCaps.hasOwnProperty(cap)) {
var capMode = modeCaps[cap](value);
// make sure we always have an array
if (typeof(capMode) === 'string') {
capMode = [capMode];
}
if (!mode) {
mode = capMode;
} else if (!(mode = Basic.arrayIntersect(mode, capMode))) {
// if cap requires conflicting mode - runtime cannot fulfill required caps
return (mode = false);
}
}
});
if (mode) {
return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0];
} else if (mode === false) {
return false;
}
}
return defaultMode;
};
/**
Capability check that always returns true
@private
@static
@return {True}
*/
Runtime.capTrue = function() {
return true;
};
/**
Capability check that always returns false
@private
@static
@return {False}
*/
Runtime.capFalse = function() {
return false;
};
/**
Evaluate the expression to boolean value and create a function that always returns it.
@private
@static
@param {Mixed} expr Expression to evaluate
@return {Function} Function returning the result of evaluation
*/
Runtime.capTest = function(expr) {
return function() {
return !!expr;
};
};
return Runtime;
});
// Included from: src/javascript/runtime/RuntimeClient.js
/**
* RuntimeClient.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/RuntimeClient', [
'moxie/core/Exceptions',
'moxie/core/utils/Basic',
'moxie/runtime/Runtime'
], function(x, Basic, Runtime) {
/**
Set of methods and properties, required by a component to acquire ability to connect to a runtime
@class RuntimeClient
*/
return function RuntimeClient() {
var runtime;
Basic.extend(this, {
/**
Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one.
Increments number of clients connected to the specified runtime.
@method connectRuntime
@param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites
*/
connectRuntime: function(options) {
var comp = this, ruid;
function initialize(items) {
var type, constructor;
// if we ran out of runtimes
if (!items.length) {
comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR));
runtime = null;
return;
}
type = items.shift();
constructor = Runtime.getConstructor(type);
if (!constructor) {
initialize(items);
return;
}
// try initializing the runtime
runtime = new constructor(options);
runtime.bind('Init', function() {
// mark runtime as initialized
runtime.initialized = true;
// jailbreak ...
setTimeout(function() {
runtime.clients++;
// this will be triggered on component
comp.trigger('RuntimeInit', runtime);
}, 1);
});
runtime.bind('Error', function() {
runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here
initialize(items);
});
/*runtime.bind('Exception', function() { });*/
// check if runtime managed to pick-up operational mode
if (!runtime.mode) {
runtime.trigger('Error');
return;
}
runtime.init();
}
// check if a particular runtime was requested
if (Basic.typeOf(options) === 'string') {
ruid = options;
} else if (Basic.typeOf(options.ruid) === 'string') {
ruid = options.ruid;
}
if (ruid) {
runtime = Runtime.getRuntime(ruid);
if (runtime) {
runtime.clients++;
return runtime;
} else {
// there should be a runtime and there's none - weird case
throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR);
}
}
// initialize a fresh one, that fits runtime list and required features best
initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/));
},
/**
Returns the runtime to which the client is currently connected.
@method getRuntime
@return {Runtime} Runtime or null if client is not connected
*/
getRuntime: function() {
if (runtime && runtime.uid) {
return runtime;
}
runtime = null; // make sure we do not leave zombies rambling around
return null;
},
/**
Disconnects from the runtime. Decrements number of clients connected to the specified runtime.
@method disconnectRuntime
*/
disconnectRuntime: function() {
if (runtime && --runtime.clients <= 0) {
runtime.destroy();
runtime = null;
}
}
});
};
});
// Included from: src/javascript/file/Blob.js
/**
* Blob.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/Blob', [
'moxie/core/utils/Basic',
'moxie/core/utils/Encode',
'moxie/runtime/RuntimeClient'
], function(Basic, Encode, RuntimeClient) {
var blobpool = {};
/**
@class Blob
@constructor
@param {String} ruid Unique id of the runtime, to which this blob belongs to
@param {Object} blob Object "Native" blob object, as it is represented in the runtime
*/
function Blob(ruid, blob) {
function _sliceDetached(start, end, type) {
var blob, data = blobpool[this.uid];
if (Basic.typeOf(data) !== 'string' || !data.length) {
return null; // or throw exception
}
blob = new Blob(null, {
type: type,
size: end - start
});
blob.detach(data.substr(start, blob.size));
return blob;
}
RuntimeClient.call(this);
if (ruid) {
this.connectRuntime(ruid);
}
if (!blob) {
blob = {};
} else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string
blob = { data: blob };
}
Basic.extend(this, {
/**
Unique id of the component
@property uid
@type {String}
*/
uid: blob.uid || Basic.guid('uid_'),
/**
Unique id of the connected runtime, if falsy, then runtime will have to be initialized
before this Blob can be used, modified or sent
@property ruid
@type {String}
*/
ruid: ruid,
/**
Size of blob
@property size
@type {Number}
@default 0
*/
size: blob.size || 0,
/**
Mime type of blob
@property type
@type {String}
@default ''
*/
type: blob.type || '',
/**
@method slice
@param {Number} [start=0]
*/
slice: function(start, end, type) {
if (this.isDetached()) {
return _sliceDetached.apply(this, arguments);
}
return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type);
},
/**
Returns "native" blob object (as it is represented in connected runtime) or null if not found
@method getSource
@return {Blob} Returns "native" blob object or null if not found
*/
getSource: function() {
if (!blobpool[this.uid]) {
return null;
}
return blobpool[this.uid];
},
/**
Detaches blob from any runtime that it depends on and initialize with standalone value
@method detach
@protected
@param {DOMString} [data=''] Standalone value
*/
detach: function(data) {
if (this.ruid) {
this.getRuntime().exec.call(this, 'Blob', 'destroy');
this.disconnectRuntime();
this.ruid = null;
}
data = data || '';
// if dataUrl, convert to binary string
var matches = data.match(/^data:([^;]*);base64,/);
if (matches) {
this.type = matches[1];
data = Encode.atob(data.substring(data.indexOf('base64,') + 7));
}
this.size = data.length;
blobpool[this.uid] = data;
},
/**
Checks if blob is standalone (detached of any runtime)
@method isDetached
@protected
@return {Boolean}
*/
isDetached: function() {
return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string';
},
/**
Destroy Blob and free any resources it was using
@method destroy
*/
destroy: function() {
this.detach();
delete blobpool[this.uid];
}
});
if (blob.data) {
this.detach(blob.data); // auto-detach if payload has been passed
} else {
blobpool[this.uid] = blob;
}
}
return Blob;
});
// Included from: src/javascript/file/File.js
/**
* File.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/File', [
'moxie/core/utils/Basic',
'moxie/core/utils/Mime',
'moxie/file/Blob'
], function(Basic, Mime, Blob) {
/**
@class File
@extends Blob
@constructor
@param {String} ruid Unique id of the runtime, to which this blob belongs to
@param {Object} file Object "Native" file object, as it is represented in the runtime
*/
function File(ruid, file) {
var name, type;
if (!file) { // avoid extra errors in case we overlooked something
file = {};
}
// figure out the type
if (file.type && file.type !== '') {
type = file.type;
} else {
type = Mime.getFileMime(file.name);
}
// sanitize file name or generate new one
if (file.name) {
name = file.name.replace(/\\/g, '/');
name = name.substr(name.lastIndexOf('/') + 1);
} else {
var prefix = type.split('/')[0];
name = Basic.guid((prefix !== '' ? prefix : 'file') + '_');
if (Mime.extensions[type]) {
name += '.' + Mime.extensions[type][0]; // append proper extension if possible
}
}
Blob.apply(this, arguments);
Basic.extend(this, {
/**
File mime type
@property type
@type {String}
@default ''
*/
type: type || '',
/**
File name
@property name
@type {String}
@default UID
*/
name: name || Basic.guid('file_'),
/**
Relative path to the file inside a directory
@property relativePath
@type {String}
@default ''
*/
relativePath: '',
/**
Date of last modification
@property lastModifiedDate
@type {String}
@default now
*/
lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET)
});
}
File.prototype = Blob.prototype;
return File;
});
// Included from: src/javascript/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileInput', [
'moxie/core/utils/Basic',
'moxie/core/utils/Mime',
'moxie/core/utils/Dom',
'moxie/core/Exceptions',
'moxie/core/EventTarget',
'moxie/core/I18n',
'moxie/file/File',
'moxie/runtime/Runtime',
'moxie/runtime/RuntimeClient'
], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) {
/**
Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click,
converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory
with _FileReader_ or uploaded to a server through _XMLHttpRequest_.
@class FileInput
@constructor
@extends EventTarget
@uses RuntimeClient
@param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_.
@param {String|DOMElement} options.browse_button DOM Element to turn into file picker.
@param {Array} [options.accept] Array of mime types to accept. By default accepts all.
@param {String} [options.file='file'] Name of the file field (not the filename).
@param {Boolean} [options.multiple=false] Enable selection of multiple files.
@param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time).
@param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode
for _browse\_button_.
@param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support.
@example
<div id="container">
<a id="file-picker" href="javascript:;">Browse...</a>
</div>
<script>
var fileInput = new mOxie.FileInput({
browse_button: 'file-picker', // or document.getElementById('file-picker')
container: 'container',
accept: [
{title: "Image files", extensions: "jpg,gif,png"} // accept only images
],
multiple: true // allow multiple file selection
});
fileInput.onchange = function(e) {
// do something to files array
console.info(e.target.files); // or this.files or fileInput.files
};
fileInput.init(); // initialize
</script>
*/
var dispatches = [
/**
Dispatched when runtime is connected and file-picker is ready to be used.
@event ready
@param {Object} event
*/
'ready',
/**
Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked.
Check [corresponding documentation entry](#method_refresh) for more info.
@event refresh
@param {Object} event
*/
/**
Dispatched when selection of files in the dialog is complete.
@event change
@param {Object} event
*/
'change',
'cancel', // TODO: might be useful
/**
Dispatched when mouse cursor enters file-picker area. Can be used to style element
accordingly.
@event mouseenter
@param {Object} event
*/
'mouseenter',
/**
Dispatched when mouse cursor leaves file-picker area. Can be used to style element
accordingly.
@event mouseleave
@param {Object} event
*/
'mouseleave',
/**
Dispatched when functional mouse button is pressed on top of file-picker area.
@event mousedown
@param {Object} event
*/
'mousedown',
/**
Dispatched when functional mouse button is released on top of file-picker area.
@event mouseup
@param {Object} event
*/
'mouseup'
];
function FileInput(options) {
var self = this,
container, browseButton, defaults;
// if flat argument passed it should be browse_button id
if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) {
options = { browse_button : options };
}
// this will help us to find proper default container
browseButton = Dom.get(options.browse_button);
if (!browseButton) {
// browse button is required
throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
}
// figure out the options
defaults = {
accept: [{
title: I18n.translate('All Files'),
extensions: '*'
}],
name: 'file',
multiple: false,
required_caps: false,
container: browseButton.parentNode || document.body
};
options = Basic.extend({}, defaults, options);
// convert to object representation
if (typeof(options.required_caps) === 'string') {
options.required_caps = Runtime.parseCaps(options.required_caps);
}
// normalize accept option (could be list of mime types or array of title/extensions pairs)
if (typeof(options.accept) === 'string') {
options.accept = Mime.mimes2extList(options.accept);
}
container = Dom.get(options.container);
// make sure we have container
if (!container) {
container = document.body;
}
// make container relative, if it's not
if (Dom.getStyle(container, 'position') === 'static') {
container.style.position = 'relative';
}
container = browseButton = null; // IE
RuntimeClient.call(self);
Basic.extend(self, {
/**
Unique id of the component
@property uid
@protected
@readOnly
@type {String}
@default UID
*/
uid: Basic.guid('uid_'),
/**
Unique id of the connected runtime, if any.
@property ruid
@protected
@type {String}
*/
ruid: null,
/**
Unique id of the runtime container. Useful to get hold of it for various manipulations.
@property shimid
@protected
@type {String}
*/
shimid: null,
/**
Array of selected mOxie.File objects
@property files
@type {Array}
@default null
*/
files: null,
/**
Initializes the file-picker, connects it to runtime and dispatches event ready when done.
@method init
*/
init: function() {
self.convertEventPropsToHandlers(dispatches);
self.bind('RuntimeInit', function(e, runtime) {
self.ruid = runtime.uid;
self.shimid = runtime.shimid;
self.bind("Ready", function() {
self.trigger("Refresh");
}, 999);
self.bind("Change", function() {
var files = runtime.exec.call(self, 'FileInput', 'getFiles');
self.files = [];
Basic.each(files, function(file) {
// ignore empty files (IE10 for example hangs if you try to send them via XHR)
if (file.size === 0) {
return true;
}
self.files.push(new File(self.ruid, file));
});
}, 999);
// re-position and resize shim container
self.bind('Refresh', function() {
var pos, size, browseButton, shimContainer;
browseButton = Dom.get(options.browse_button);
shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist
if (browseButton) {
pos = Dom.getPos(browseButton, Dom.get(options.container));
size = Dom.getSize(browseButton);
if (shimContainer) {
Basic.extend(shimContainer.style, {
top : pos.y + 'px',
left : pos.x + 'px',
width : size.w + 'px',
height : size.h + 'px'
});
}
}
shimContainer = browseButton = null;
});
runtime.exec.call(self, 'FileInput', 'init', options);
});
// runtime needs: options.required_features, options.runtime_order and options.container
self.connectRuntime(Basic.extend({}, options, {
required_caps: {
select_file: true
}
}));
},
/**
Disables file-picker element, so that it doesn't react to mouse clicks.
@method disable
@param {Boolean} [state=true] Disable component if - true, enable if - false
*/
disable: function(state) {
var runtime = this.getRuntime();
if (runtime) {
runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state);
}
},
/**
Reposition and resize dialog trigger to match the position and size of browse_button element.
@method refresh
*/
refresh: function() {
self.trigger("Refresh");
},
/**
Destroy component.
@method destroy
*/
destroy: function() {
var runtime = this.getRuntime();
if (runtime) {
runtime.exec.call(this, 'FileInput', 'destroy');
this.disconnectRuntime();
}
if (Basic.typeOf(this.files) === 'array') {
// no sense in leaving associated files behind
Basic.each(this.files, function(file) {
file.destroy();
});
}
this.files = null;
}
});
}
FileInput.prototype = EventTarget.instance;
return FileInput;
});
// Included from: src/javascript/runtime/RuntimeTarget.js
/**
* RuntimeTarget.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/runtime/RuntimeTarget', [
'moxie/core/utils/Basic',
'moxie/runtime/RuntimeClient',
"moxie/core/EventTarget"
], function(Basic, RuntimeClient, EventTarget) {
/**
Instance of this class can be used as a target for the events dispatched by shims,
when allowing them onto components is for either reason inappropriate
@class RuntimeTarget
@constructor
@protected
@extends EventTarget
*/
function RuntimeTarget() {
this.uid = Basic.guid('uid_');
RuntimeClient.call(this);
this.destroy = function() {
this.disconnectRuntime();
this.unbindAll();
};
}
RuntimeTarget.prototype = EventTarget.instance;
return RuntimeTarget;
});
// Included from: src/javascript/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileReader', [
'moxie/core/utils/Basic',
'moxie/core/utils/Encode',
'moxie/core/Exceptions',
'moxie/core/EventTarget',
'moxie/file/Blob',
'moxie/file/File',
'moxie/runtime/RuntimeTarget'
], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) {
/**
Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader)
interface. Where possible uses native FileReader, where - not falls back to shims.
@class FileReader
@constructor FileReader
@extends EventTarget
@uses RuntimeClient
*/
var dispatches = [
/**
Dispatched when the read starts.
@event loadstart
@param {Object} event
*/
'loadstart',
/**
Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total).
@event progress
@param {Object} event
*/
'progress',
/**
Dispatched when the read has successfully completed.
@event load
@param {Object} event
*/
'load',
/**
Dispatched when the read has been aborted. For instance, by invoking the abort() method.
@event abort
@param {Object} event
*/
'abort',
/**
Dispatched when the read has failed.
@event error
@param {Object} event
*/
'error',
/**
Dispatched when the request has completed (either in success or failure).
@event loadend
@param {Object} event
*/
'loadend'
];
function FileReader() {
var self = this, _fr;
Basic.extend(this, {
/**
UID of the component instance.
@property uid
@type {String}
*/
uid: Basic.guid('uid_'),
/**
Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING
and FileReader.DONE.
@property readyState
@type {Number}
@default FileReader.EMPTY
*/
readyState: FileReader.EMPTY,
/**
Result of the successful read operation.
@property result
@type {String}
*/
result: null,
/**
Stores the error of failed asynchronous read operation.
@property error
@type {DOMError}
*/
error: null,
/**
Initiates reading of File/Blob object contents to binary string.
@method readAsBinaryString
@param {Blob|File} blob Object to preload
*/
readAsBinaryString: function(blob) {
_read.call(this, 'readAsBinaryString', blob);
},
/**
Initiates reading of File/Blob object contents to dataURL string.
@method readAsDataURL
@param {Blob|File} blob Object to preload
*/
readAsDataURL: function(blob) {
_read.call(this, 'readAsDataURL', blob);
},
/**
Initiates reading of File/Blob object contents to string.
@method readAsText
@param {Blob|File} blob Object to preload
*/
readAsText: function(blob) {
_read.call(this, 'readAsText', blob);
},
/**
Aborts preloading process.
@method abort
*/
abort: function() {
this.result = null;
if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) {
return;
} else if (this.readyState === FileReader.LOADING) {
this.readyState = FileReader.DONE;
}
if (_fr) {
_fr.getRuntime().exec.call(this, 'FileReader', 'abort');
}
this.trigger('abort');
this.trigger('loadend');
},
/**
Destroy component and release resources.
@method destroy
*/
destroy: function() {
this.abort();
if (_fr) {
_fr.getRuntime().exec.call(this, 'FileReader', 'destroy');
_fr.disconnectRuntime();
}
self = _fr = null;
}
});
function _read(op, blob) {
_fr = new RuntimeTarget();
function error(err) {
self.readyState = FileReader.DONE;
self.error = err;
self.trigger('error');
loadEnd();
}
function loadEnd() {
_fr.destroy();
_fr = null;
self.trigger('loadend');
}
function exec(runtime) {
_fr.bind('Error', function(e, err) {
error(err);
});
_fr.bind('Progress', function(e) {
self.result = runtime.exec.call(_fr, 'FileReader', 'getResult');
self.trigger(e);
});
_fr.bind('Load', function(e) {
self.readyState = FileReader.DONE;
self.result = runtime.exec.call(_fr, 'FileReader', 'getResult');
self.trigger(e);
loadEnd();
});
runtime.exec.call(_fr, 'FileReader', 'read', op, blob);
}
this.convertEventPropsToHandlers(dispatches);
if (this.readyState === FileReader.LOADING) {
return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR));
}
this.readyState = FileReader.LOADING;
this.trigger('loadstart');
// if source is o.Blob/o.File
if (blob instanceof Blob) {
if (blob.isDetached()) {
var src = blob.getSource();
switch (op) {
case 'readAsText':
case 'readAsBinaryString':
this.result = src;
break;
case 'readAsDataURL':
this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src);
break;
}
this.readyState = FileReader.DONE;
this.trigger('load');
loadEnd();
} else {
exec(_fr.connectRuntime(blob.ruid));
}
} else {
error(new x.DOMException(x.DOMException.NOT_FOUND_ERR));
}
}
}
/**
Initial FileReader state
@property EMPTY
@type {Number}
@final
@static
@default 0
*/
FileReader.EMPTY = 0;
/**
FileReader switches to this state when it is preloading the source
@property LOADING
@type {Number}
@final
@static
@default 1
*/
FileReader.LOADING = 1;
/**
Preloading is complete, this is a final state
@property DONE
@type {Number}
@final
@static
@default 2
*/
FileReader.DONE = 2;
FileReader.prototype = EventTarget.instance;
return FileReader;
});
// Included from: src/javascript/core/utils/Url.js
/**
* Url.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Url', [], function() {
/**
Parse url into separate components and fill in absent parts with parts from current url,
based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js
@method parseUrl
@for Utils
@static
@param {String} url Url to parse (defaults to empty string if undefined)
@return {Object} Hash containing extracted uri components
*/
var parseUrl = function(url, currentUrl) {
var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment']
, i = key.length
, ports = {
http: 80,
https: 443
}
, uri = {}
, regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/
, m = regex.exec(url || '')
;
while (i--) {
if (m[i]) {
uri[key[i]] = m[i];
}
}
// when url is relative, we set the origin and the path ourselves
if (!uri.scheme) {
// come up with defaults
if (!currentUrl || typeof(currentUrl) === 'string') {
currentUrl = parseUrl(currentUrl || document.location.href);
}
uri.scheme = currentUrl.scheme;
uri.host = currentUrl.host;
uri.port = currentUrl.port;
var path = '';
// for urls without trailing slash we need to figure out the path
if (/^[^\/]/.test(uri.path)) {
path = currentUrl.path;
// if path ends with a filename, strip it
if (!/(\/|\/[^\.]+)$/.test(path)) {
path = path.replace(/\/[^\/]+$/, '/');
} else {
path += '/';
}
}
uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir
}
if (!uri.port) {
uri.port = ports[uri.scheme] || 80;
}
uri.port = parseInt(uri.port, 10);
if (!uri.path) {
uri.path = "/";
}
delete uri.source;
return uri;
};
/**
Resolve url - among other things will turn relative url to absolute
@method resolveUrl
@static
@param {String} url Either absolute or relative
@return {String} Resolved, absolute url
*/
var resolveUrl = function(url) {
var ports = { // we ignore default ports
http: 80,
https: 443
}
, urlp = parseUrl(url)
;
return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : '');
};
/**
Check if specified url has the same origin as the current document
@method hasSameOrigin
@param {String|Object} url
@return {Boolean}
*/
var hasSameOrigin = function(url) {
function origin(url) {
return [url.scheme, url.host, url.port].join('/');
}
if (typeof url === 'string') {
url = parseUrl(url);
}
return origin(parseUrl()) === origin(url);
};
return {
parseUrl: parseUrl,
resolveUrl: resolveUrl,
hasSameOrigin: hasSameOrigin
};
});
// Included from: src/javascript/file/FileReaderSync.js
/**
* FileReaderSync.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/file/FileReaderSync', [
'moxie/core/utils/Basic',
'moxie/runtime/RuntimeClient',
'moxie/core/utils/Encode'
], function(Basic, RuntimeClient, Encode) {
/**
Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here
it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be,
but probably < 1mb). Not meant to be used directly by user.
@class FileReaderSync
@private
@constructor
*/
return function() {
RuntimeClient.call(this);
Basic.extend(this, {
uid: Basic.guid('uid_'),
readAsBinaryString: function(blob) {
return _read.call(this, 'readAsBinaryString', blob);
},
readAsDataURL: function(blob) {
return _read.call(this, 'readAsDataURL', blob);
},
/*readAsArrayBuffer: function(blob) {
return _read.call(this, 'readAsArrayBuffer', blob);
},*/
readAsText: function(blob) {
return _read.call(this, 'readAsText', blob);
}
});
function _read(op, blob) {
if (blob.isDetached()) {
var src = blob.getSource();
switch (op) {
case 'readAsBinaryString':
return src;
case 'readAsDataURL':
return 'data:' + blob.type + ';base64,' + Encode.btoa(src);
case 'readAsText':
var txt = '';
for (var i = 0, length = src.length; i < length; i++) {
txt += String.fromCharCode(src[i]);
}
return txt;
}
} else {
var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob);
this.disconnectRuntime();
return result;
}
}
};
});
// Included from: src/javascript/xhr/FormData.js
/**
* FormData.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/xhr/FormData", [
"moxie/core/Exceptions",
"moxie/core/utils/Basic",
"moxie/file/Blob"
], function(x, Basic, Blob) {
/**
FormData
@class FormData
@constructor
*/
function FormData() {
var _blob, _fields = [];
Basic.extend(this, {
/**
Append another key-value pair to the FormData object
@method append
@param {String} name Name for the new field
@param {String|Blob|Array|Object} value Value for the field
*/
append: function(name, value) {
var self = this, valueType = Basic.typeOf(value);
// according to specs value might be either Blob or String
if (value instanceof Blob) {
_blob = {
name: name,
value: value // unfortunately we can only send single Blob in one FormData
};
} else if ('array' === valueType) {
name += '[]';
Basic.each(value, function(value) {
self.append(name, value);
});
} else if ('object' === valueType) {
Basic.each(value, function(value, key) {
self.append(name + '[' + key + ']', value);
});
} else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) {
self.append(name, "false");
} else {
_fields.push({
name: name,
value: value.toString()
});
}
},
/**
Checks if FormData contains Blob.
@method hasBlob
@return {Boolean}
*/
hasBlob: function() {
return !!this.getBlob();
},
/**
Retrieves blob.
@method getBlob
@return {Object} Either Blob if found or null
*/
getBlob: function() {
return _blob && _blob.value || null;
},
/**
Retrieves blob field name.
@method getBlobName
@return {String} Either Blob field name or null
*/
getBlobName: function() {
return _blob && _blob.name || null;
},
/**
Loop over the fields in FormData and invoke the callback for each of them.
@method each
@param {Function} cb Callback to call for each field
*/
each: function(cb) {
Basic.each(_fields, function(field) {
cb(field.value, field.name);
});
if (_blob) {
cb(_blob.value, _blob.name);
}
},
destroy: function() {
_blob = null;
_fields = [];
}
});
}
return FormData;
});
// Included from: src/javascript/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/xhr/XMLHttpRequest", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/core/EventTarget",
"moxie/core/utils/Encode",
"moxie/core/utils/Url",
"moxie/runtime/Runtime",
"moxie/runtime/RuntimeTarget",
"moxie/file/Blob",
"moxie/file/FileReaderSync",
"moxie/xhr/FormData",
"moxie/core/utils/Env",
"moxie/core/utils/Mime"
], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) {
var httpCode = {
100: 'Continue',
101: 'Switching Protocols',
102: 'Processing',
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-Authoritative Information',
204: 'No Content',
205: 'Reset Content',
206: 'Partial Content',
207: 'Multi-Status',
226: 'IM Used',
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Found',
303: 'See Other',
304: 'Not Modified',
305: 'Use Proxy',
306: 'Reserved',
307: 'Temporary Redirect',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
409: 'Conflict',
410: 'Gone',
411: 'Length Required',
412: 'Precondition Failed',
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Requested Range Not Satisfiable',
417: 'Expectation Failed',
422: 'Unprocessable Entity',
423: 'Locked',
424: 'Failed Dependency',
426: 'Upgrade Required',
500: 'Internal Server Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Gateway Timeout',
505: 'HTTP Version Not Supported',
506: 'Variant Also Negotiates',
507: 'Insufficient Storage',
510: 'Not Extended'
};
function XMLHttpRequestUpload() {
this.uid = Basic.guid('uid_');
}
XMLHttpRequestUpload.prototype = EventTarget.instance;
/**
Implementation of XMLHttpRequest
@class XMLHttpRequest
@constructor
@uses RuntimeClient
@extends EventTarget
*/
var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons)
var NATIVE = 1, RUNTIME = 2;
function XMLHttpRequest() {
var self = this,
// this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible
props = {
/**
The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout.
@property timeout
@type Number
@default 0
*/
timeout: 0,
/**
Current state, can take following values:
UNSENT (numeric value 0)
The object has been constructed.
OPENED (numeric value 1)
The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method.
HEADERS_RECEIVED (numeric value 2)
All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available.
LOADING (numeric value 3)
The response entity body is being received.
DONE (numeric value 4)
@property readyState
@type Number
@default 0 (UNSENT)
*/
readyState: XMLHttpRequest.UNSENT,
/**
True when user credentials are to be included in a cross-origin request. False when they are to be excluded
in a cross-origin request and when cookies are to be ignored in its response. Initially false.
@property withCredentials
@type Boolean
@default false
*/
withCredentials: false,
/**
Returns the HTTP status code.
@property status
@type Number
@default 0
*/
status: 0,
/**
Returns the HTTP status text.
@property statusText
@type String
*/
statusText: "",
/**
Returns the response type. Can be set to change the response type. Values are:
the empty string (default), "arraybuffer", "blob", "document", "json", and "text".
@property responseType
@type String
*/
responseType: "",
/**
Returns the document response entity body.
Throws an "InvalidStateError" exception if responseType is not the empty string or "document".
@property responseXML
@type Document
*/
responseXML: null,
/**
Returns the text response entity body.
Throws an "InvalidStateError" exception if responseType is not the empty string or "text".
@property responseText
@type String
*/
responseText: null,
/**
Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body).
Can become: ArrayBuffer, Blob, Document, JSON, Text
@property response
@type Mixed
*/
response: null
},
_async = true,
_url,
_method,
_headers = {},
_user,
_password,
_encoding = null,
_mimeType = null,
// flags
_sync_flag = false,
_send_flag = false,
_upload_events_flag = false,
_upload_complete_flag = false,
_error_flag = false,
_same_origin_flag = false,
// times
_start_time,
_timeoutset_time,
_finalMime = null,
_finalCharset = null,
_options = {},
_xhr,
_responseHeaders = '',
_responseHeadersBag
;
Basic.extend(this, props, {
/**
Unique id of the component
@property uid
@type String
*/
uid: Basic.guid('uid_'),
/**
Target for Upload events
@property upload
@type XMLHttpRequestUpload
*/
upload: new XMLHttpRequestUpload(),
/**
Sets the request method, request URL, synchronous flag, request username, and request password.
Throws a "SyntaxError" exception if one of the following is true:
method is not a valid HTTP method.
url cannot be resolved.
url contains the "user:password" format in the userinfo production.
Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK.
Throws an "InvalidAccessError" exception if one of the following is true:
Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin.
There is an associated XMLHttpRequest document and either the timeout attribute is not zero,
the withCredentials attribute is true, or the responseType attribute is not the empty string.
@method open
@param {String} method HTTP method to use on request
@param {String} url URL to request
@param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default.
@param {String} [user] Username to use in HTTP authentication process on server-side
@param {String} [password] Password to use in HTTP authentication process on server-side
*/
open: function(method, url, async, user, password) {
var urlp;
// first two arguments are required
if (!method || !url) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method
if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3
if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) {
_method = method.toUpperCase();
}
// 4 - allowing these methods poses a security risk
if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) {
throw new x.DOMException(x.DOMException.SECURITY_ERR);
}
// 5
url = Encode.utf8_encode(url);
// 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError".
urlp = Url.parseUrl(url);
_same_origin_flag = Url.hasSameOrigin(urlp);
// 7 - manually build up absolute url
_url = Url.resolveUrl(url);
// 9-10, 12-13
if ((user || password) && !_same_origin_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
_user = user || urlp.user;
_password = password || urlp.pass;
// 11
_async = async || true;
if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 14 - terminate abort()
// 15 - terminate send()
// 18
_sync_flag = !_async;
_send_flag = false;
_headers = {};
_reset.call(this);
// 19
_p('readyState', XMLHttpRequest.OPENED);
// 20
this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers
this.dispatchEvent('readystatechange');
},
/**
Appends an header to the list of author request headers, or if header is already
in the list of author request headers, combines its value with value.
Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value
is not a valid HTTP header field value.
@method setRequestHeader
@param {String} header
@param {String|Number} value
*/
setRequestHeader: function(header, value) {
var uaHeaders = [ // these headers are controlled by the user agent
"accept-charset",
"accept-encoding",
"access-control-request-headers",
"access-control-request-method",
"connection",
"content-length",
"cookie",
"cookie2",
"content-transfer-encoding",
"date",
"expect",
"host",
"keep-alive",
"origin",
"referer",
"te",
"trailer",
"transfer-encoding",
"upgrade",
"user-agent",
"via"
];
// 1-2
if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 4
/* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values
if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}*/
header = Basic.trim(header).toLowerCase();
// setting of proxy-* and sec-* headers is prohibited by spec
if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) {
return false;
}
// camelize
// browsers lowercase header names (at least for custom ones)
// header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); });
if (!_headers[header]) {
_headers[header] = value;
} else {
// http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph)
_headers[header] += ', ' + value;
}
return true;
},
/**
Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2.
@method getAllResponseHeaders
@return {String} reponse headers or empty string
*/
getAllResponseHeaders: function() {
return _responseHeaders || '';
},
/**
Returns the header field value from the response of which the field name matches header,
unless the field name is Set-Cookie or Set-Cookie2.
@method getResponseHeader
@param {String} header
@return {String} value(s) for the specified header or null
*/
getResponseHeader: function(header) {
header = header.toLowerCase();
if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) {
return null;
}
if (_responseHeaders && _responseHeaders !== '') {
// if we didn't parse response headers until now, do it and keep for later
if (!_responseHeadersBag) {
_responseHeadersBag = {};
Basic.each(_responseHeaders.split(/\r\n/), function(line) {
var pair = line.split(/:\s+/);
if (pair.length === 2) { // last line might be empty, omit
pair[0] = Basic.trim(pair[0]); // just in case
_responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form
header: pair[0],
value: Basic.trim(pair[1])
};
}
});
}
if (_responseHeadersBag.hasOwnProperty(header)) {
return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value;
}
}
return null;
},
/**
Sets the Content-Type header for the response to mime.
Throws an "InvalidStateError" exception if the state is LOADING or DONE.
Throws a "SyntaxError" exception if mime is not a valid media type.
@method overrideMimeType
@param String mime Mime type to set
*/
overrideMimeType: function(mime) {
var matches, charset;
// 1
if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
mime = Basic.trim(mime.toLowerCase());
if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) {
mime = matches[1];
if (matches[2]) {
charset = matches[2];
}
}
if (!Mime.mimes[mime]) {
throw new x.DOMException(x.DOMException.SYNTAX_ERR);
}
// 3-4
_finalMime = mime;
_finalCharset = charset;
},
/**
Initiates the request. The optional argument provides the request entity body.
The argument is ignored if request method is GET or HEAD.
Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set.
@method send
@param {Blob|Document|String|FormData} [data] Request entity body
@param {Object} [options] Set of requirements and pre-requisities for runtime initialization
*/
send: function(data, options) {
if (Basic.typeOf(options) === 'string') {
_options = { ruid: options };
} else if (!options) {
_options = {};
} else {
_options = options;
}
this.convertEventPropsToHandlers(dispatches);
this.upload.convertEventPropsToHandlers(dispatches);
// 1-2
if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3
// sending Blob
if (data instanceof Blob) {
_options.ruid = data.ruid;
_mimeType = data.type || 'application/octet-stream';
}
// FormData
else if (data instanceof FormData) {
if (data.hasBlob()) {
var blob = data.getBlob();
_options.ruid = blob.ruid;
_mimeType = blob.type || 'application/octet-stream';
}
}
// DOMString
else if (typeof data === 'string') {
_encoding = 'UTF-8';
_mimeType = 'text/plain;charset=UTF-8';
// data should be converted to Unicode and encoded as UTF-8
data = Encode.utf8_encode(data);
}
// if withCredentials not set, but requested, set it automatically
if (!this.withCredentials) {
this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag;
}
// 4 - storage mutex
// 5
_upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP
// 6
_error_flag = false;
// 7
_upload_complete_flag = !data;
// 8 - Asynchronous steps
if (!_sync_flag) {
// 8.1
_send_flag = true;
// 8.2
// this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
// 8.3
//if (!_upload_complete_flag) {
// this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr
//}
}
// 8.5 - Return the send() method call, but continue running the steps in this algorithm.
_doXHR.call(this, data);
},
/**
Cancels any network activity.
@method abort
*/
abort: function() {
_error_flag = true;
_sync_flag = false;
if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) {
_p('readyState', XMLHttpRequest.DONE);
_send_flag = false;
if (_xhr) {
_xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag);
} else {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
_upload_complete_flag = true;
} else {
_p('readyState', XMLHttpRequest.UNSENT);
}
},
destroy: function() {
if (_xhr) {
if (Basic.typeOf(_xhr.destroy) === 'function') {
_xhr.destroy();
}
_xhr = null;
}
this.unbindAll();
if (this.upload) {
this.upload.unbindAll();
this.upload = null;
}
}
});
/* this is nice, but maybe too lengthy
// if supported by JS version, set getters/setters for specific properties
o.defineProperty(this, 'readyState', {
configurable: false,
get: function() {
return _p('readyState');
}
});
o.defineProperty(this, 'timeout', {
configurable: false,
get: function() {
return _p('timeout');
},
set: function(value) {
if (_sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// timeout still should be measured relative to the start time of request
_timeoutset_time = (new Date).getTime();
_p('timeout', value);
}
});
// the withCredentials attribute has no effect when fetching same-origin resources
o.defineProperty(this, 'withCredentials', {
configurable: false,
get: function() {
return _p('withCredentials');
},
set: function(value) {
// 1-2
if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 3-4
if (_anonymous_flag || _sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 5
_p('withCredentials', value);
}
});
o.defineProperty(this, 'status', {
configurable: false,
get: function() {
return _p('status');
}
});
o.defineProperty(this, 'statusText', {
configurable: false,
get: function() {
return _p('statusText');
}
});
o.defineProperty(this, 'responseType', {
configurable: false,
get: function() {
return _p('responseType');
},
set: function(value) {
// 1
if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2
if (_sync_flag) {
throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR);
}
// 3
_p('responseType', value.toLowerCase());
}
});
o.defineProperty(this, 'responseText', {
configurable: false,
get: function() {
// 1
if (!~o.inArray(_p('responseType'), ['', 'text'])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2-3
if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return _p('responseText');
}
});
o.defineProperty(this, 'responseXML', {
configurable: false,
get: function() {
// 1
if (!~o.inArray(_p('responseType'), ['', 'document'])) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// 2-3
if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return _p('responseXML');
}
});
o.defineProperty(this, 'response', {
configurable: false,
get: function() {
if (!!~o.inArray(_p('responseType'), ['', 'text'])) {
if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) {
return '';
}
}
if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) {
return null;
}
return _p('response');
}
});
*/
function _p(prop, value) {
if (!props.hasOwnProperty(prop)) {
return;
}
if (arguments.length === 1) { // get
return Env.can('define_property') ? props[prop] : self[prop];
} else { // set
if (Env.can('define_property')) {
props[prop] = value;
} else {
self[prop] = value;
}
}
}
/*
function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) {
// TODO: http://tools.ietf.org/html/rfc3490#section-4.1
return str.toLowerCase();
}
*/
function _doXHR(data) {
var self = this;
_start_time = new Date().getTime();
_xhr = new RuntimeTarget();
function loadEnd() {
if (_xhr) { // it could have been destroyed by now
_xhr.destroy();
_xhr = null;
}
self.dispatchEvent('loadend');
self = null;
}
function exec(runtime) {
_xhr.bind('LoadStart', function(e) {
_p('readyState', XMLHttpRequest.LOADING);
self.dispatchEvent('readystatechange');
self.dispatchEvent(e);
if (_upload_events_flag) {
self.upload.dispatchEvent(e);
}
});
_xhr.bind('Progress', function(e) {
if (_p('readyState') !== XMLHttpRequest.LOADING) {
_p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example)
self.dispatchEvent('readystatechange');
}
self.dispatchEvent(e);
});
_xhr.bind('UploadProgress', function(e) {
if (_upload_events_flag) {
self.upload.dispatchEvent({
type: 'progress',
lengthComputable: false,
total: e.total,
loaded: e.loaded
});
}
});
_xhr.bind('Load', function(e) {
_p('readyState', XMLHttpRequest.DONE);
_p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0));
_p('statusText', httpCode[_p('status')] || "");
_p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType')));
if (!!~Basic.inArray(_p('responseType'), ['text', ''])) {
_p('responseText', _p('response'));
} else if (_p('responseType') === 'document') {
_p('responseXML', _p('response'));
}
_responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders');
self.dispatchEvent('readystatechange');
if (_p('status') > 0) { // status 0 usually means that server is unreachable
if (_upload_events_flag) {
self.upload.dispatchEvent(e);
}
self.dispatchEvent(e);
} else {
_error_flag = true;
self.dispatchEvent('error');
}
loadEnd();
});
_xhr.bind('Abort', function(e) {
self.dispatchEvent(e);
loadEnd();
});
_xhr.bind('Error', function(e) {
_error_flag = true;
_p('readyState', XMLHttpRequest.DONE);
self.dispatchEvent('readystatechange');
_upload_complete_flag = true;
self.dispatchEvent(e);
loadEnd();
});
runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', {
url: _url,
method: _method,
async: _async,
user: _user,
password: _password,
headers: _headers,
mimeType: _mimeType,
encoding: _encoding,
responseType: self.responseType,
withCredentials: self.withCredentials,
options: _options
}, data);
}
// clarify our requirements
if (typeof(_options.required_caps) === 'string') {
_options.required_caps = Runtime.parseCaps(_options.required_caps);
}
_options.required_caps = Basic.extend({}, _options.required_caps, {
return_response_type: self.responseType
});
if (data instanceof FormData) {
_options.required_caps.send_multipart = true;
}
if (!_same_origin_flag) {
_options.required_caps.do_cors = true;
}
if (_options.ruid) { // we do not need to wait if we can connect directly
exec(_xhr.connectRuntime(_options));
} else {
_xhr.bind('RuntimeInit', function(e, runtime) {
exec(runtime);
});
_xhr.bind('RuntimeError', function(e, err) {
self.dispatchEvent('RuntimeError', err);
});
_xhr.connectRuntime(_options);
}
}
function _reset() {
_p('responseText', "");
_p('responseXML', null);
_p('response', null);
_p('status', 0);
_p('statusText', "");
_start_time = _timeoutset_time = null;
}
}
XMLHttpRequest.UNSENT = 0;
XMLHttpRequest.OPENED = 1;
XMLHttpRequest.HEADERS_RECEIVED = 2;
XMLHttpRequest.LOADING = 3;
XMLHttpRequest.DONE = 4;
XMLHttpRequest.prototype = EventTarget.instance;
return XMLHttpRequest;
});
// Included from: src/javascript/runtime/Transporter.js
/**
* Transporter.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/runtime/Transporter", [
"moxie/core/utils/Basic",
"moxie/core/utils/Encode",
"moxie/runtime/RuntimeClient",
"moxie/core/EventTarget"
], function(Basic, Encode, RuntimeClient, EventTarget) {
function Transporter() {
var mod, _runtime, _data, _size, _pos, _chunk_size;
RuntimeClient.call(this);
Basic.extend(this, {
uid: Basic.guid('uid_'),
state: Transporter.IDLE,
result: null,
transport: function(data, type, options) {
var self = this;
options = Basic.extend({
chunk_size: 204798
}, options);
// should divide by three, base64 requires this
if ((mod = options.chunk_size % 3)) {
options.chunk_size += 3 - mod;
}
_chunk_size = options.chunk_size;
_reset.call(this);
_data = data;
_size = data.length;
if (Basic.typeOf(options) === 'string' || options.ruid) {
_run.call(self, type, this.connectRuntime(options));
} else {
// we require this to run only once
var cb = function(e, runtime) {
self.unbind("RuntimeInit", cb);
_run.call(self, type, runtime);
};
this.bind("RuntimeInit", cb);
this.connectRuntime(options);
}
},
abort: function() {
var self = this;
self.state = Transporter.IDLE;
if (_runtime) {
_runtime.exec.call(self, 'Transporter', 'clear');
self.trigger("TransportingAborted");
}
_reset.call(self);
},
destroy: function() {
this.unbindAll();
_runtime = null;
this.disconnectRuntime();
_reset.call(this);
}
});
function _reset() {
_size = _pos = 0;
_data = this.result = null;
}
function _run(type, runtime) {
var self = this;
_runtime = runtime;
//self.unbind("RuntimeInit");
self.bind("TransportingProgress", function(e) {
_pos = e.loaded;
if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) {
_transport.call(self);
}
}, 999);
self.bind("TransportingComplete", function() {
_pos = _size;
self.state = Transporter.DONE;
_data = null; // clean a bit
self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || '');
}, 999);
self.state = Transporter.BUSY;
self.trigger("TransportingStarted");
_transport.call(self);
}
function _transport() {
var self = this,
chunk,
bytesLeft = _size - _pos;
if (_chunk_size > bytesLeft) {
_chunk_size = bytesLeft;
}
chunk = Encode.btoa(_data.substr(_pos, _chunk_size));
_runtime.exec.call(self, 'Transporter', 'receive', chunk, _size);
}
}
Transporter.IDLE = 0;
Transporter.BUSY = 1;
Transporter.DONE = 2;
Transporter.prototype = EventTarget.instance;
return Transporter;
});
// Included from: src/javascript/image/Image.js
/**
* Image.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define("moxie/image/Image", [
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/Exceptions",
"moxie/file/FileReaderSync",
"moxie/xhr/XMLHttpRequest",
"moxie/runtime/Runtime",
"moxie/runtime/RuntimeClient",
"moxie/runtime/Transporter",
"moxie/core/utils/Env",
"moxie/core/EventTarget",
"moxie/file/Blob",
"moxie/file/File",
"moxie/core/utils/Encode"
], function(Basic, Dom, x, FileReaderSync, XMLHttpRequest, Runtime, RuntimeClient, Transporter, Env, EventTarget, Blob, File, Encode) {
/**
Image preloading and manipulation utility. Additionally it provides access to image meta info (Exif, GPS) and raw binary data.
@class Image
@constructor
@extends EventTarget
*/
var dispatches = [
'progress',
/**
Dispatched when loading is complete.
@event load
@param {Object} event
*/
'load',
'error',
/**
Dispatched when resize operation is complete.
@event resize
@param {Object} event
*/
'resize',
/**
Dispatched when visual representation of the image is successfully embedded
into the corresponsing container.
@event embedded
@param {Object} event
*/
'embedded'
];
function Image() {
RuntimeClient.call(this);
Basic.extend(this, {
/**
Unique id of the component
@property uid
@type {String}
*/
uid: Basic.guid('uid_'),
/**
Unique id of the connected runtime, if any.
@property ruid
@type {String}
*/
ruid: null,
/**
Name of the file, that was used to create an image, if available. If not equals to empty string.
@property name
@type {String}
@default ""
*/
name: "",
/**
Size of the image in bytes. Actual value is set only after image is preloaded.
@property size
@type {Number}
@default 0
*/
size: 0,
/**
Width of the image. Actual value is set only after image is preloaded.
@property width
@type {Number}
@default 0
*/
width: 0,
/**
Height of the image. Actual value is set only after image is preloaded.
@property height
@type {Number}
@default 0
*/
height: 0,
/**
Mime type of the image. Currently only image/jpeg and image/png are supported. Actual value is set only after image is preloaded.
@property type
@type {String}
@default ""
*/
type: "",
/**
Holds meta info (Exif, GPS). Is populated only for image/jpeg. Actual value is set only after image is preloaded.
@property meta
@type {Object}
@default {}
*/
meta: {},
/**
Alias for load method, that takes another mOxie.Image object as a source (see load).
@method clone
@param {Image} src Source for the image
@param {Boolean} [exact=false] Whether to activate in-depth clone mode
*/
clone: function() {
this.load.apply(this, arguments);
},
/**
Loads image from various sources. Currently the source for new image can be: mOxie.Image, mOxie.Blob/mOxie.File,
native Blob/File, dataUrl or URL. Depending on the type of the source, arguments - differ. When source is URL,
Image will be downloaded from remote destination and loaded in memory.
@example
var img = new mOxie.Image();
img.onload = function() {
var blob = img.getAsBlob();
var formData = new mOxie.FormData();
formData.append('file', blob);
var xhr = new mOxie.XMLHttpRequest();
xhr.onload = function() {
// upload complete
};
xhr.open('post', 'upload.php');
xhr.send(formData);
};
img.load("http://www.moxiecode.com/images/mox-logo.jpg"); // notice file extension (.jpg)
@method load
@param {Image|Blob|File|String} src Source for the image
@param {Boolean|Object} [mixed]
*/
load: function() {
// this is here because to bind properly we need an uid first, which is created above
this.bind('Load Resize', function() {
_updateInfo.call(this);
}, 999);
this.convertEventPropsToHandlers(dispatches);
_load.apply(this, arguments);
},
/**
Downsizes the image to fit the specified width/height. If crop is supplied, image will be cropped to exact dimensions.
@method downsize
@param {Number} width Resulting width
@param {Number} [height=width] Resulting height (optional, if not supplied will default to width)
@param {Boolean} [crop=false] Whether to crop the image to exact dimensions
@param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
*/
downsize: function(opts) {
var defaults = {
width: this.width,
height: this.height,
crop: false,
preserveHeaders: true
};
if (typeof(opts) === 'object') {
opts = Basic.extend(defaults, opts);
} else {
opts = Basic.extend(defaults, {
width: arguments[0],
height: arguments[1],
crop: arguments[2],
preserveHeaders: arguments[3]
});
}
try {
if (!this.size) { // only preloaded image objects can be used as source
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
// no way to reliably intercept the crash due to high resolution, so we simply avoid it
if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) {
throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
}
this.getRuntime().exec.call(this, 'Image', 'downsize', opts.width, opts.height, opts.crop, opts.preserveHeaders);
} catch(ex) {
// for now simply trigger error event
this.trigger('error', ex.code);
}
},
/**
Alias for downsize(width, height, true). (see downsize)
@method crop
@param {Number} width Resulting width
@param {Number} [height=width] Resulting height (optional, if not supplied will default to width)
@param {Boolean} [preserveHeaders=true] Whether to preserve meta headers (on JPEGs after resize)
*/
crop: function(width, height, preserveHeaders) {
this.downsize(width, height, true, preserveHeaders);
},
getAsCanvas: function() {
if (!Env.can('create_canvas')) {
throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
}
var runtime = this.connectRuntime(this.ruid);
return runtime.exec.call(this, 'Image', 'getAsCanvas');
},
/**
Retrieves image in it's current state as mOxie.Blob object. Cannot be run on empty or image in progress (throws
DOMException.INVALID_STATE_ERR).
@method getAsBlob
@param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
@param {Number} [quality=90] Applicable only together with mime type image/jpeg
@return {Blob} Image as Blob
*/
getAsBlob: function(type, quality) {
if (!this.size) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
if (!type) {
type = 'image/jpeg';
}
if (type === 'image/jpeg' && !quality) {
quality = 90;
}
return this.getRuntime().exec.call(this, 'Image', 'getAsBlob', type, quality);
},
/**
Retrieves image in it's current state as dataURL string. Cannot be run on empty or image in progress (throws
DOMException.INVALID_STATE_ERR).
@method getAsDataURL
@param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
@param {Number} [quality=90] Applicable only together with mime type image/jpeg
@return {String} Image as dataURL string
*/
getAsDataURL: function(type, quality) {
if (!this.size) {
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
return this.getRuntime().exec.call(this, 'Image', 'getAsDataURL', type, quality);
},
/**
Retrieves image in it's current state as binary string. Cannot be run on empty or image in progress (throws
DOMException.INVALID_STATE_ERR).
@method getAsBinaryString
@param {String} [type="image/jpeg"] Mime type of resulting blob. Can either be image/jpeg or image/png
@param {Number} [quality=90] Applicable only together with mime type image/jpeg
@return {String} Image as binary string
*/
getAsBinaryString: function(type, quality) {
var dataUrl = this.getAsDataURL(type, quality);
return Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7));
},
/**
Embeds a visual representation of the image into the specified node. Depending on the runtime,
it might be a canvas, an img node or a thrid party shim object (Flash or SilverLight - very rare,
can be used in legacy browsers that do not have canvas or proper dataURI support).
@method embed
@param {DOMElement} el DOM element to insert the image object into
@param {Object} [options]
@param {Number} [options.width] The width of an embed (defaults to the image width)
@param {Number} [options.height] The height of an embed (defaults to the image height)
@param {String} [type="image/jpeg"] Mime type
@param {Number} [quality=90] Quality of an embed, if mime type is image/jpeg
@param {Boolean} [crop=false] Whether to crop an embed to the specified dimensions
*/
embed: function(el) {
var self = this
, imgCopy
, type, quality, crop
, options = arguments[1] || {}
, width = this.width
, height = this.height
, runtime // this has to be outside of all the closures to contain proper runtime
;
function onResize() {
// if possible, embed a canvas element directly
if (Env.can('create_canvas')) {
var canvas = imgCopy.getAsCanvas();
if (canvas) {
el.appendChild(canvas);
canvas = null;
imgCopy.destroy();
self.trigger('embedded');
return;
}
}
var dataUrl = imgCopy.getAsDataURL(type, quality);
if (!dataUrl) {
throw new x.ImageError(x.ImageError.WRONG_FORMAT);
}
if (Env.can('use_data_uri_of', dataUrl.length)) {
el.innerHTML = '<img src="' + dataUrl + '" width="' + imgCopy.width + '" height="' + imgCopy.height + '" />';
imgCopy.destroy();
self.trigger('embedded');
} else {
var tr = new Transporter();
tr.bind("TransportingComplete", function() {
runtime = self.connectRuntime(this.result.ruid);
self.bind("Embedded", function() {
// position and size properly
Basic.extend(runtime.getShimContainer().style, {
//position: 'relative',
top: '0px',
left: '0px',
width: imgCopy.width + 'px',
height: imgCopy.height + 'px'
});
// some shims (Flash/SilverLight) reinitialize, if parent element is hidden, reordered or it's
// position type changes (in Gecko), but since we basically need this only in IEs 6/7 and
// sometimes 8 and they do not have this problem, we can comment this for now
/*tr.bind("RuntimeInit", function(e, runtime) {
tr.destroy();
runtime.destroy();
onResize.call(self); // re-feed our image data
});*/
runtime = null;
}, 999);
runtime.exec.call(self, "ImageView", "display", this.result.uid, width, height);
imgCopy.destroy();
});
tr.transport(Encode.atob(dataUrl.substring(dataUrl.indexOf('base64,') + 7)), type, Basic.extend({}, options, {
required_caps: {
display_media: true
},
runtime_order: 'flash,silverlight',
container: el
}));
}
}
try {
if (!(el = Dom.get(el))) {
throw new x.DOMException(x.DOMException.INVALID_NODE_TYPE_ERR);
}
if (!this.size) { // only preloaded image objects can be used as source
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
if (this.width > Image.MAX_RESIZE_WIDTH || this.height > Image.MAX_RESIZE_HEIGHT) {
throw new x.ImageError(x.ImageError.MAX_RESOLUTION_ERR);
}
type = options.type || this.type || 'image/jpeg';
quality = options.quality || 90;
crop = Basic.typeOf(options.crop) !== 'undefined' ? options.crop : false;
// figure out dimensions for the thumb
if (options.width) {
width = options.width;
height = options.height || width;
} else {
// if container element has measurable dimensions, use them
var dimensions = Dom.getSize(el);
if (dimensions.w && dimensions.h) { // both should be > 0
width = dimensions.w;
height = dimensions.h;
}
}
imgCopy = new Image();
imgCopy.bind("Resize", function() {
onResize.call(self);
});
imgCopy.bind("Load", function() {
imgCopy.downsize(width, height, crop, false);
});
imgCopy.clone(this, false);
return imgCopy;
} catch(ex) {
// for now simply trigger error event
this.trigger('error', ex.code);
}
},
/**
Properly destroys the image and frees resources in use. If any. Recommended way to dispose mOxie.Image object.
@method destroy
*/
destroy: function() {
if (this.ruid) {
this.getRuntime().exec.call(this, 'Image', 'destroy');
this.disconnectRuntime();
}
this.unbindAll();
}
});
function _updateInfo(info) {
if (!info) {
info = this.getRuntime().exec.call(this, 'Image', 'getInfo');
}
this.size = info.size;
this.width = info.width;
this.height = info.height;
this.type = info.type;
this.meta = info.meta;
// update file name, only if empty
if (this.name === '') {
this.name = info.name;
}
}
function _load(src) {
var srcType = Basic.typeOf(src);
try {
// if source is Image
if (src instanceof Image) {
if (!src.size) { // only preloaded image objects can be used as source
throw new x.DOMException(x.DOMException.INVALID_STATE_ERR);
}
_loadFromImage.apply(this, arguments);
}
// if source is o.Blob/o.File
else if (src instanceof Blob) {
if (!~Basic.inArray(src.type, ['image/jpeg', 'image/png'])) {
throw new x.ImageError(x.ImageError.WRONG_FORMAT);
}
_loadFromBlob.apply(this, arguments);
}
// if native blob/file
else if (Basic.inArray(srcType, ['blob', 'file']) !== -1) {
_load.call(this, new File(null, src), arguments[1]);
}
// if String
else if (srcType === 'string') {
// if dataUrl String
if (/^data:[^;]*;base64,/.test(src)) {
_load.call(this, new Blob(null, { data: src }), arguments[1]);
}
// else assume Url, either relative or absolute
else {
_loadFromUrl.apply(this, arguments);
}
}
// if source seems to be an img node
else if (srcType === 'node' && src.nodeName.toLowerCase() === 'img') {
_load.call(this, src.src, arguments[1]);
}
else {
throw new x.DOMException(x.DOMException.TYPE_MISMATCH_ERR);
}
} catch(ex) {
// for now simply trigger error event
this.trigger('error', ex.code);
}
}
function _loadFromImage(img, exact) {
var runtime = this.connectRuntime(img.ruid);
this.ruid = runtime.uid;
runtime.exec.call(this, 'Image', 'loadFromImage', img, (Basic.typeOf(exact) === 'undefined' ? true : exact));
}
function _loadFromBlob(blob, options) {
var self = this;
self.name = blob.name || '';
function exec(runtime) {
self.ruid = runtime.uid;
runtime.exec.call(self, 'Image', 'loadFromBlob', blob);
}
if (blob.isDetached()) {
this.bind('RuntimeInit', function(e, runtime) {
exec(runtime);
});
// convert to object representation
if (options && typeof(options.required_caps) === 'string') {
options.required_caps = Runtime.parseCaps(options.required_caps);
}
this.connectRuntime(Basic.extend({
required_caps: {
access_image_binary: true,
resize_image: true
}
}, options));
} else {
exec(this.connectRuntime(blob.ruid));
}
}
function _loadFromUrl(url, options) {
var self = this, xhr;
xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.responseType = 'blob';
xhr.onprogress = function(e) {
self.trigger(e);
};
xhr.onload = function() {
_loadFromBlob.call(self, xhr.response, true);
};
xhr.onerror = function(e) {
self.trigger(e);
};
xhr.onloadend = function() {
xhr.destroy();
};
xhr.bind('RuntimeError', function(e, err) {
self.trigger('RuntimeError', err);
});
xhr.send(null, options);
}
}
// virtual world will crash on you if image has a resolution higher than this:
Image.MAX_RESIZE_WIDTH = 6500;
Image.MAX_RESIZE_HEIGHT = 6500;
Image.prototype = EventTarget.instance;
return Image;
});
// Included from: src/javascript/runtime/html4/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global File:true */
/**
Defines constructor for HTML4 runtime.
@class moxie/runtime/html4/Runtime
@private
*/
define("moxie/runtime/html4/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/Runtime",
"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
var type = 'html4', extensions = {};
function Html4Runtime(options) {
var I = this
, Test = Runtime.capTest
, True = Runtime.capTrue
;
Runtime.call(this, options, type, {
access_binary: Test(window.FileReader || window.File && File.getAsDataURL),
access_image_binary: false,
display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))),
do_cors: false,
drag_and_drop: false,
filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10);
}()),
resize_image: function() {
return extensions.Image && I.can('access_binary') && Env.can('create_canvas');
},
report_upload_progress: false,
return_response_headers: false,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) {
return true;
}
return !!~Basic.inArray(responseType, ['text', 'document', '']);
},
return_status_code: function(code) {
return !Basic.arrayDiff(code, [200, 404]);
},
select_file: function() {
return Env.can('use_fileinput');
},
select_multiple: false,
send_binary_string: false,
send_custom_headers: false,
send_multipart: true,
slice_blob: false,
stream_upload: function() {
return I.can('select_file');
},
summon_file_dialog: Test(function() { // yeah... some dirty sniffing here...
return (Env.browser === 'Firefox' && Env.version >= 4) ||
(Env.browser === 'Opera' && Env.version >= 12) ||
!!~Basic.inArray(Env.browser, ['Chrome', 'Safari']);
}()),
upload_filesize: True,
use_http_method: function(methods) {
return !Basic.arrayDiff(methods, ['GET', 'POST']);
}
});
Basic.extend(this, {
init : function() {
this.trigger("Init");
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
destroy = I = null;
};
}(this.destroy))
});
Basic.extend(this.getShim(), extensions);
}
Runtime.addConstructor(type, Html4Runtime);
return extensions;
});
// Included from: src/javascript/core/utils/Events.js
/**
* Events.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
define('moxie/core/utils/Events', [
'moxie/core/utils/Basic'
], function(Basic) {
var eventhash = {}, uid = 'moxie_' + Basic.guid();
// IE W3C like event funcs
function preventDefault() {
this.returnValue = false;
}
function stopPropagation() {
this.cancelBubble = true;
}
/**
Adds an event handler to the specified object and store reference to the handler
in objects internal Plupload registry (@see removeEvent).
@method addEvent
@for Utils
@static
@param {Object} obj DOM element like object to add handler to.
@param {String} name Name to add event listener to.
@param {Function} callback Function to call when event occurs.
@param {String} [key] that might be used to add specifity to the event record.
*/
var addEvent = function(obj, name, callback, key) {
var func, events;
name = name.toLowerCase();
// Add event listener
if (obj.addEventListener) {
func = callback;
obj.addEventListener(name, func, false);
} else if (obj.attachEvent) {
func = function() {
var evt = window.event;
if (!evt.target) {
evt.target = evt.srcElement;
}
evt.preventDefault = preventDefault;
evt.stopPropagation = stopPropagation;
callback(evt);
};
obj.attachEvent('on' + name, func);
}
// Log event handler to objects internal mOxie registry
if (!obj[uid]) {
obj[uid] = Basic.guid();
}
if (!eventhash.hasOwnProperty(obj[uid])) {
eventhash[obj[uid]] = {};
}
events = eventhash[obj[uid]];
if (!events.hasOwnProperty(name)) {
events[name] = [];
}
events[name].push({
func: func,
orig: callback, // store original callback for IE
key: key
});
};
/**
Remove event handler from the specified object. If third argument (callback)
is not specified remove all events with the specified name.
@method removeEvent
@static
@param {Object} obj DOM element to remove event listener(s) from.
@param {String} name Name of event listener to remove.
@param {Function|String} [callback] might be a callback or unique key to match.
*/
var removeEvent = function(obj, name, callback) {
var type, undef;
name = name.toLowerCase();
if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) {
type = eventhash[obj[uid]][name];
} else {
return;
}
for (var i = type.length - 1; i >= 0; i--) {
// undefined or not, key should match
if (type[i].orig === callback || type[i].key === callback) {
if (obj.removeEventListener) {
obj.removeEventListener(name, type[i].func, false);
} else if (obj.detachEvent) {
obj.detachEvent('on'+name, type[i].func);
}
type[i].orig = null;
type[i].func = null;
type.splice(i, 1);
// If callback was passed we are done here, otherwise proceed
if (callback !== undef) {
break;
}
}
}
// If event array got empty, remove it
if (!type.length) {
delete eventhash[obj[uid]][name];
}
// If mOxie registry has become empty, remove it
if (Basic.isEmptyObj(eventhash[obj[uid]])) {
delete eventhash[obj[uid]];
// IE doesn't let you remove DOM object property with - delete
try {
delete obj[uid];
} catch(e) {
obj[uid] = undef;
}
}
};
/**
Remove all kind of events from the specified object
@method removeAllEvents
@static
@param {Object} obj DOM element to remove event listeners from.
@param {String} [key] unique key to match, when removing events.
*/
var removeAllEvents = function(obj, key) {
if (!obj || !obj[uid]) {
return;
}
Basic.each(eventhash[obj[uid]], function(events, name) {
removeEvent(obj, name, key);
});
};
return {
addEvent: addEvent,
removeEvent: removeEvent,
removeAllEvents: removeAllEvents
};
});
// Included from: src/javascript/runtime/html4/file/FileInput.js
/**
* FileInput.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/file/FileInput
@private
*/
define("moxie/runtime/html4/file/FileInput", [
"moxie/runtime/html4/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Events",
"moxie/core/utils/Mime",
"moxie/core/utils/Env"
], function(extensions, Basic, Dom, Events, Mime, Env) {
function FileInput() {
var _uid, _files = [], _mimes = [], _options;
function addInput() {
var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid;
uid = Basic.guid('uid_');
shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE
if (_uid) { // move previous form out of the view
currForm = Dom.get(_uid + '_form');
if (currForm) {
Basic.extend(currForm.style, { top: '100%' });
}
}
// build form in DOM, since innerHTML version not able to submit file for some reason
form = document.createElement('form');
form.setAttribute('id', uid + '_form');
form.setAttribute('method', 'post');
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
Basic.extend(form.style, {
overflow: 'hidden',
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
input = document.createElement('input');
input.setAttribute('id', uid);
input.setAttribute('type', 'file');
input.setAttribute('name', _options.name || 'Filedata');
input.setAttribute('accept', _mimes.join(','));
Basic.extend(input.style, {
fontSize: '999px',
opacity: 0
});
form.appendChild(input);
shimContainer.appendChild(form);
// prepare file input to be placed underneath the browse_button element
Basic.extend(input.style, {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
height: '100%'
});
if (Env.browser === 'IE' && Env.version < 10) {
Basic.extend(input.style, {
filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)"
});
}
input.onchange = function() { // there should be only one handler for this
var file;
if (!this.value) {
return;
}
if (this.files) {
file = this.files[0];
} else {
file = {
name: this.value
};
}
_files = [file];
this.onchange = function() {}; // clear event handler
addInput.call(comp);
// after file is initialized as o.File, we need to update form and input ids
comp.bind('change', function onChange() {
var input = Dom.get(uid), form = Dom.get(uid + '_form'), file;
comp.unbind('change', onChange);
if (comp.files.length && input && form) {
file = comp.files[0];
input.setAttribute('id', file.uid);
form.setAttribute('id', file.uid + '_form');
// set upload target
form.setAttribute('target', file.uid + '_iframe');
}
input = form = null;
}, 998);
input = form = null;
comp.trigger('change');
};
// route click event to the input
if (I.can('summon_file_dialog')) {
browseButton = Dom.get(_options.browse_button);
Events.removeEvent(browseButton, 'click', comp.uid);
Events.addEvent(browseButton, 'click', function(e) {
if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file]
input.click();
}
e.preventDefault();
}, comp.uid);
}
_uid = uid;
shimContainer = currForm = browseButton = null;
}
Basic.extend(this, {
init: function(options) {
var comp = this, I = comp.getRuntime(), shimContainer;
// figure out accept string
_options = options;
_mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension'));
shimContainer = I.getShimContainer();
(function() {
var browseButton, zIndex, top;
browseButton = Dom.get(options.browse_button);
// Route click event to the input[type=file] element for browsers that support such behavior
if (I.can('summon_file_dialog')) {
if (Dom.getStyle(browseButton, 'position') === 'static') {
browseButton.style.position = 'relative';
}
zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1;
browseButton.style.zIndex = zIndex;
shimContainer.style.zIndex = zIndex - 1;
}
/* Since we have to place input[type=file] on top of the browse_button for some browsers,
browse_button loses interactivity, so we restore it here */
top = I.can('summon_file_dialog') ? browseButton : shimContainer;
Events.addEvent(top, 'mouseover', function() {
comp.trigger('mouseenter');
}, comp.uid);
Events.addEvent(top, 'mouseout', function() {
comp.trigger('mouseleave');
}, comp.uid);
Events.addEvent(top, 'mousedown', function() {
comp.trigger('mousedown');
}, comp.uid);
Events.addEvent(Dom.get(options.container), 'mouseup', function() {
comp.trigger('mouseup');
}, comp.uid);
browseButton = null;
}());
addInput.call(this);
shimContainer = null;
// trigger ready event asynchronously
comp.trigger({
type: 'ready',
async: true
});
},
getFiles: function() {
return _files;
},
disable: function(state) {
var input;
if ((input = Dom.get(_uid))) {
input.disabled = !!state;
}
},
destroy: function() {
var I = this.getRuntime()
, shim = I.getShim()
, shimContainer = I.getShimContainer()
;
Events.removeAllEvents(shimContainer, this.uid);
Events.removeAllEvents(_options && Dom.get(_options.container), this.uid);
Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid);
if (shimContainer) {
shimContainer.innerHTML = '';
}
shim.removeInstance(this.uid);
_uid = _files = _mimes = _options = shimContainer = shim = null;
}
});
}
return (extensions.FileInput = FileInput);
});
// Included from: src/javascript/runtime/html5/Runtime.js
/**
* Runtime.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global File:true */
/**
Defines constructor for HTML5 runtime.
@class moxie/runtime/html5/Runtime
@private
*/
define("moxie/runtime/html5/Runtime", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/Runtime",
"moxie/core/utils/Env"
], function(Basic, x, Runtime, Env) {
var type = "html5", extensions = {};
function Html5Runtime(options) {
var I = this
, Test = Runtime.capTest
, True = Runtime.capTrue
;
var caps = Basic.extend({
access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL),
access_image_binary: function() {
return I.can('access_binary') && !!extensions.Image;
},
display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')),
do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()),
drag_and_drop: Test(function() {
// this comes directly from Modernizr: http://www.modernizr.com/
var div = document.createElement('div');
// IE has support for drag and drop since version 5, but doesn't support dropping files from desktop
return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9);
}()),
filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest
return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10);
}()),
return_response_headers: True,
return_response_type: function(responseType) {
if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported
return true;
}
return Env.can('return_response_type', responseType);
},
return_status_code: True,
report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload),
resize_image: function() {
return I.can('access_binary') && Env.can('create_canvas');
},
select_file: function() {
return Env.can('use_fileinput') && window.File;
},
select_folder: function() {
return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21;
},
select_multiple: function() {
// it is buggy on Safari Windows and iOS
return I.can('select_file') &&
!(Env.browser === 'Safari' && Env.os === 'Windows') &&
!(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<'));
},
send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))),
send_custom_headers: Test(window.XMLHttpRequest),
send_multipart: function() {
return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string');
},
slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)),
stream_upload: function(){
return I.can('slice_blob') && I.can('send_multipart');
},
summon_file_dialog: Test(function() { // yeah... some dirty sniffing here...
return (Env.browser === 'Firefox' && Env.version >= 4) ||
(Env.browser === 'Opera' && Env.version >= 12) ||
(Env.browser === 'IE' && Env.version >= 10) ||
!!~Basic.inArray(Env.browser, ['Chrome', 'Safari']);
}()),
upload_filesize: True
},
arguments[2]
);
Runtime.call(this, options, (arguments[1] || type), caps);
Basic.extend(this, {
init : function() {
this.trigger("Init");
},
destroy: (function(destroy) { // extend default destroy method
return function() {
destroy.call(I);
destroy = I = null;
};
}(this.destroy))
});
Basic.extend(this.getShim(), extensions);
}
Runtime.addConstructor(type, Html5Runtime);
return extensions;
});
// Included from: src/javascript/runtime/html5/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/file/FileReader
@private
*/
define("moxie/runtime/html5/file/FileReader", [
"moxie/runtime/html5/Runtime",
"moxie/core/utils/Encode",
"moxie/core/utils/Basic"
], function(extensions, Encode, Basic) {
function FileReader() {
var _fr, _convertToBinary = false;
Basic.extend(this, {
read: function(op, blob) {
var target = this;
_fr = new window.FileReader();
_fr.addEventListener('progress', function(e) {
target.trigger(e);
});
_fr.addEventListener('load', function(e) {
target.trigger(e);
});
_fr.addEventListener('error', function(e) {
target.trigger(e, _fr.error);
});
_fr.addEventListener('loadend', function() {
_fr = null;
});
if (Basic.typeOf(_fr[op]) === 'function') {
_convertToBinary = false;
_fr[op](blob.getSource());
} else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+
_convertToBinary = true;
_fr.readAsDataURL(blob.getSource());
}
},
getResult: function() {
return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null;
},
abort: function() {
if (_fr) {
_fr.abort();
}
},
destroy: function() {
_fr = null;
}
});
function _toBinary(str) {
return Encode.atob(str.substring(str.indexOf('base64,') + 7));
}
}
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/html4/file/FileReader.js
/**
* FileReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/file/FileReader
@private
*/
define("moxie/runtime/html4/file/FileReader", [
"moxie/runtime/html4/Runtime",
"moxie/runtime/html5/file/FileReader"
], function(extensions, FileReader) {
return (extensions.FileReader = FileReader);
});
// Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js
/**
* XMLHttpRequest.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/xhr/XMLHttpRequest
@private
*/
define("moxie/runtime/html4/xhr/XMLHttpRequest", [
"moxie/runtime/html4/Runtime",
"moxie/core/utils/Basic",
"moxie/core/utils/Dom",
"moxie/core/utils/Url",
"moxie/core/Exceptions",
"moxie/core/utils/Events",
"moxie/file/Blob",
"moxie/xhr/FormData"
], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) {
function XMLHttpRequest() {
var _status, _response, _iframe;
function cleanup(cb) {
var target = this, uid, form, inputs, i, hasFile = false;
if (!_iframe) {
return;
}
uid = _iframe.id.replace(/_iframe$/, '');
form = Dom.get(uid + '_form');
if (form) {
inputs = form.getElementsByTagName('input');
i = inputs.length;
while (i--) {
switch (inputs[i].getAttribute('type')) {
case 'hidden':
inputs[i].parentNode.removeChild(inputs[i]);
break;
case 'file':
hasFile = true; // flag the case for later
break;
}
}
inputs = [];
if (!hasFile) { // we need to keep the form for sake of possible retries
form.parentNode.removeChild(form);
}
form = null;
}
// without timeout, request is marked as canceled (in console)
setTimeout(function() {
Events.removeEvent(_iframe, 'load', target.uid);
if (_iframe.parentNode) { // #382
_iframe.parentNode.removeChild(_iframe);
}
// check if shim container has any other children, if - not, remove it as well
var shimContainer = target.getRuntime().getShimContainer();
if (!shimContainer.children.length) {
shimContainer.parentNode.removeChild(shimContainer);
}
shimContainer = _iframe = null;
cb();
}, 1);
}
Basic.extend(this, {
send: function(meta, data) {
var target = this, I = target.getRuntime(), uid, form, input, blob;
_status = _response = null;
function createIframe() {
var container = I.getShimContainer() || document.body
, temp = document.createElement('div')
;
// IE 6 won't be able to set the name using setAttribute or iframe.name
temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:""" style="display:none"></iframe>';
_iframe = temp.firstChild;
container.appendChild(_iframe);
/* _iframe.onreadystatechange = function() {
console.info(_iframe.readyState);
};*/
Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8
var el;
try {
el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document;
// try to detect some standard error pages
if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error
_status = el.title.replace(/^(\d+).*$/, '$1');
} else {
_status = 200;
// get result
_response = Basic.trim(el.body.innerHTML);
// we need to fire these at least once
target.trigger({
type: 'progress',
loaded: _response.length,
total: _response.length
});
if (blob) { // if we were uploading a file
target.trigger({
type: 'uploadprogress',
loaded: blob.size || 1025,
total: blob.size || 1025
});
}
}
} catch (ex) {
if (Url.hasSameOrigin(meta.url)) {
// if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm
// which obviously results to cross domain error (wtf?)
_status = 404;
} else {
cleanup.call(target, function() {
target.trigger('error');
});
return;
}
}
cleanup.call(target, function() {
target.trigger('load');
});
}, target.uid);
} // end createIframe
// prepare data to be sent and convert if required
if (data instanceof FormData && data.hasBlob()) {
blob = data.getBlob();
uid = blob.uid;
input = Dom.get(uid);
form = Dom.get(uid + '_form');
if (!form) {
throw new x.DOMException(x.DOMException.NOT_FOUND_ERR);
}
} else {
uid = Basic.guid('uid_');
form = document.createElement('form');
form.setAttribute('id', uid + '_form');
form.setAttribute('method', meta.method);
form.setAttribute('enctype', 'multipart/form-data');
form.setAttribute('encoding', 'multipart/form-data');
form.setAttribute('target', uid + '_iframe');
I.getShimContainer().appendChild(form);
}
if (data instanceof FormData) {
data.each(function(value, name) {
if (value instanceof Blob) {
if (input) {
input.setAttribute('name', name);
}
} else {
var hidden = document.createElement('input');
Basic.extend(hidden, {
type : 'hidden',
name : name,
value : value
});
// make sure that input[type="file"], if it's there, comes last
if (input) {
form.insertBefore(hidden, input);
} else {
form.appendChild(hidden);
}
}
});
}
// set destination url
form.setAttribute("action", meta.url);
createIframe();
form.submit();
target.trigger('loadstart');
},
getStatus: function() {
return _status;
},
getResponse: function(responseType) {
if ('json' === responseType) {
// strip off <pre>..</pre> tags that might be enclosing the response
if (Basic.typeOf(_response) === 'string' && !!window.JSON) {
try {
return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, ''));
} catch (ex) {
return null;
}
}
} else if ('document' === responseType) {
}
return _response;
},
abort: function() {
var target = this;
if (_iframe && _iframe.contentWindow) {
if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome
_iframe.contentWindow.stop();
} else if (_iframe.contentWindow.document.execCommand) { // IE
_iframe.contentWindow.document.execCommand('Stop');
} else {
_iframe.src = "about:blank";
}
}
cleanup.call(this, function() {
// target.dispatchEvent('readystatechange');
target.dispatchEvent('abort');
});
}
});
}
return (extensions.XMLHttpRequest = XMLHttpRequest);
});
// Included from: src/javascript/runtime/html5/utils/BinaryReader.js
/**
* BinaryReader.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/utils/BinaryReader
@private
*/
define("moxie/runtime/html5/utils/BinaryReader", [], function() {
return function() {
var II = false, bin;
// Private functions
function read(idx, size) {
var mv = II ? 0 : -8 * (size - 1), sum = 0, i;
for (i = 0; i < size; i++) {
sum |= (bin.charCodeAt(idx + i) << Math.abs(mv + i*8));
}
return sum;
}
function putstr(segment, idx, length) {
length = arguments.length === 3 ? length : bin.length - idx - 1;
bin = bin.substr(0, idx) + segment + bin.substr(length + idx);
}
function write(idx, num, size) {
var str = '', mv = II ? 0 : -8 * (size - 1), i;
for (i = 0; i < size; i++) {
str += String.fromCharCode((num >> Math.abs(mv + i*8)) & 255);
}
putstr(str, idx, size);
}
// Public functions
return {
II: function(order) {
if (order === undefined) {
return II;
} else {
II = order;
}
},
init: function(binData) {
II = false;
bin = binData;
},
SEGMENT: function(idx, length, segment) {
switch (arguments.length) {
case 1:
return bin.substr(idx, bin.length - idx - 1);
case 2:
return bin.substr(idx, length);
case 3:
putstr(segment, idx, length);
break;
default: return bin;
}
},
BYTE: function(idx) {
return read(idx, 1);
},
SHORT: function(idx) {
return read(idx, 2);
},
LONG: function(idx, num) {
if (num === undefined) {
return read(idx, 4);
} else {
write(idx, num, 4);
}
},
SLONG: function(idx) { // 2's complement notation
var num = read(idx, 4);
return (num > 2147483647 ? num - 4294967296 : num);
},
STRING: function(idx, size) {
var str = '';
for (size += idx; idx < size; idx++) {
str += String.fromCharCode(read(idx, 1));
}
return str;
}
};
};
});
// Included from: src/javascript/runtime/html5/image/JPEGHeaders.js
/**
* JPEGHeaders.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/image/JPEGHeaders
@private
*/
define("moxie/runtime/html5/image/JPEGHeaders", [
"moxie/runtime/html5/utils/BinaryReader"
], function(BinaryReader) {
return function JPEGHeaders(data) {
var headers = [], read, idx, marker, length = 0;
read = new BinaryReader();
read.init(data);
// Check if data is jpeg
if (read.SHORT(0) !== 0xFFD8) {
return;
}
idx = 2;
while (idx <= data.length) {
marker = read.SHORT(idx);
// omit RST (restart) markers
if (marker >= 0xFFD0 && marker <= 0xFFD7) {
idx += 2;
continue;
}
// no headers allowed after SOS marker
if (marker === 0xFFDA || marker === 0xFFD9) {
break;
}
length = read.SHORT(idx + 2) + 2;
// APPn marker detected
if (marker >= 0xFFE1 && marker <= 0xFFEF) {
headers.push({
hex: marker,
name: 'APP' + (marker & 0x000F),
start: idx,
length: length,
segment: read.SEGMENT(idx, length)
});
}
idx += length;
}
read.init(null); // free memory
return {
headers: headers,
restore: function(data) {
var max, i;
read.init(data);
idx = read.SHORT(2) == 0xFFE0 ? 4 + read.SHORT(4) : 2;
for (i = 0, max = headers.length; i < max; i++) {
read.SEGMENT(idx, 0, headers[i].segment);
idx += headers[i].length;
}
data = read.SEGMENT();
read.init(null);
return data;
},
strip: function(data) {
var headers, jpegHeaders, i;
jpegHeaders = new JPEGHeaders(data);
headers = jpegHeaders.headers;
jpegHeaders.purge();
read.init(data);
i = headers.length;
while (i--) {
read.SEGMENT(headers[i].start, headers[i].length, '');
}
data = read.SEGMENT();
read.init(null);
return data;
},
get: function(name) {
var array = [];
for (var i = 0, max = headers.length; i < max; i++) {
if (headers[i].name === name.toUpperCase()) {
array.push(headers[i].segment);
}
}
return array;
},
set: function(name, segment) {
var array = [], i, ii, max;
if (typeof(segment) === 'string') {
array.push(segment);
} else {
array = segment;
}
for (i = ii = 0, max = headers.length; i < max; i++) {
if (headers[i].name === name.toUpperCase()) {
headers[i].segment = array[ii];
headers[i].length = array[ii].length;
ii++;
}
if (ii >= array.length) {
break;
}
}
},
purge: function() {
headers = [];
read.init(null);
read = null;
}
};
};
});
// Included from: src/javascript/runtime/html5/image/ExifParser.js
/**
* ExifParser.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/image/ExifParser
@private
*/
define("moxie/runtime/html5/image/ExifParser", [
"moxie/core/utils/Basic",
"moxie/runtime/html5/utils/BinaryReader"
], function(Basic, BinaryReader) {
return function ExifParser() {
// Private ExifParser fields
var data, tags, Tiff, offsets = {}, tagDescs;
data = new BinaryReader();
tags = {
tiff : {
/*
The image orientation viewed in terms of rows and columns.
1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
*/
0x0112: 'Orientation',
0x010E: 'ImageDescription',
0x010F: 'Make',
0x0110: 'Model',
0x0131: 'Software',
0x8769: 'ExifIFDPointer',
0x8825: 'GPSInfoIFDPointer'
},
exif : {
0x9000: 'ExifVersion',
0xA001: 'ColorSpace',
0xA002: 'PixelXDimension',
0xA003: 'PixelYDimension',
0x9003: 'DateTimeOriginal',
0x829A: 'ExposureTime',
0x829D: 'FNumber',
0x8827: 'ISOSpeedRatings',
0x9201: 'ShutterSpeedValue',
0x9202: 'ApertureValue' ,
0x9207: 'MeteringMode',
0x9208: 'LightSource',
0x9209: 'Flash',
0x920A: 'FocalLength',
0xA402: 'ExposureMode',
0xA403: 'WhiteBalance',
0xA406: 'SceneCaptureType',
0xA404: 'DigitalZoomRatio',
0xA408: 'Contrast',
0xA409: 'Saturation',
0xA40A: 'Sharpness'
},
gps : {
0x0000: 'GPSVersionID',
0x0001: 'GPSLatitudeRef',
0x0002: 'GPSLatitude',
0x0003: 'GPSLongitudeRef',
0x0004: 'GPSLongitude'
}
};
tagDescs = {
'ColorSpace': {
1: 'sRGB',
0: 'Uncalibrated'
},
'MeteringMode': {
0: 'Unknown',
1: 'Average',
2: 'CenterWeightedAverage',
3: 'Spot',
4: 'MultiSpot',
5: 'Pattern',
6: 'Partial',
255: 'Other'
},
'LightSource': {
1: 'Daylight',
2: 'Fliorescent',
3: 'Tungsten',
4: 'Flash',
9: 'Fine weather',
10: 'Cloudy weather',
11: 'Shade',
12: 'Daylight fluorescent (D 5700 - 7100K)',
13: 'Day white fluorescent (N 4600 -5400K)',
14: 'Cool white fluorescent (W 3900 - 4500K)',
15: 'White fluorescent (WW 3200 - 3700K)',
17: 'Standard light A',
18: 'Standard light B',
19: 'Standard light C',
20: 'D55',
21: 'D65',
22: 'D75',
23: 'D50',
24: 'ISO studio tungsten',
255: 'Other'
},
'Flash': {
0x0000: 'Flash did not fire.',
0x0001: 'Flash fired.',
0x0005: 'Strobe return light not detected.',
0x0007: 'Strobe return light detected.',
0x0009: 'Flash fired, compulsory flash mode',
0x000D: 'Flash fired, compulsory flash mode, return light not detected',
0x000F: 'Flash fired, compulsory flash mode, return light detected',
0x0010: 'Flash did not fire, compulsory flash mode',
0x0018: 'Flash did not fire, auto mode',
0x0019: 'Flash fired, auto mode',
0x001D: 'Flash fired, auto mode, return light not detected',
0x001F: 'Flash fired, auto mode, return light detected',
0x0020: 'No flash function',
0x0041: 'Flash fired, red-eye reduction mode',
0x0045: 'Flash fired, red-eye reduction mode, return light not detected',
0x0047: 'Flash fired, red-eye reduction mode, return light detected',
0x0049: 'Flash fired, compulsory flash mode, red-eye reduction mode',
0x004D: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected',
0x004F: 'Flash fired, compulsory flash mode, red-eye reduction mode, return light detected',
0x0059: 'Flash fired, auto mode, red-eye reduction mode',
0x005D: 'Flash fired, auto mode, return light not detected, red-eye reduction mode',
0x005F: 'Flash fired, auto mode, return light detected, red-eye reduction mode'
},
'ExposureMode': {
0: 'Auto exposure',
1: 'Manual exposure',
2: 'Auto bracket'
},
'WhiteBalance': {
0: 'Auto white balance',
1: 'Manual white balance'
},
'SceneCaptureType': {
0: 'Standard',
1: 'Landscape',
2: 'Portrait',
3: 'Night scene'
},
'Contrast': {
0: 'Normal',
1: 'Soft',
2: 'Hard'
},
'Saturation': {
0: 'Normal',
1: 'Low saturation',
2: 'High saturation'
},
'Sharpness': {
0: 'Normal',
1: 'Soft',
2: 'Hard'
},
// GPS related
'GPSLatitudeRef': {
N: 'North latitude',
S: 'South latitude'
},
'GPSLongitudeRef': {
E: 'East longitude',
W: 'West longitude'
}
};
function extractTags(IFD_offset, tags2extract) {
var length = data.SHORT(IFD_offset), i, ii,
tag, type, count, tagOffset, offset, value, values = [], hash = {};
for (i = 0; i < length; i++) {
// Set binary reader pointer to beginning of the next tag
offset = tagOffset = IFD_offset + 12 * i + 2;
tag = tags2extract[data.SHORT(offset)];
if (tag === undefined) {
continue; // Not the tag we requested
}
type = data.SHORT(offset+=2);
count = data.LONG(offset+=2);
offset += 4;
values = [];
switch (type) {
case 1: // BYTE
case 7: // UNDEFINED
if (count > 4) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
for (ii = 0; ii < count; ii++) {
values[ii] = data.BYTE(offset + ii);
}
break;
case 2: // STRING
if (count > 4) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
hash[tag] = data.STRING(offset, count - 1);
continue;
case 3: // SHORT
if (count > 2) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
for (ii = 0; ii < count; ii++) {
values[ii] = data.SHORT(offset + ii*2);
}
break;
case 4: // LONG
if (count > 1) {
offset = data.LONG(offset) + offsets.tiffHeader;
}
for (ii = 0; ii < count; ii++) {
values[ii] = data.LONG(offset + ii*4);
}
break;
case 5: // RATIONAL
offset = data.LONG(offset) + offsets.tiffHeader;
for (ii = 0; ii < count; ii++) {
values[ii] = data.LONG(offset + ii*4) / data.LONG(offset + ii*4 + 4);
}
break;
case 9: // SLONG
offset = data.LONG(offset) + offsets.tiffHeader;
for (ii = 0; ii < count; ii++) {
values[ii] = data.SLONG(offset + ii*4);
}
break;
case 10: // SRATIONAL
offset = data.LONG(offset) + offsets.tiffHeader;
for (ii = 0; ii < count; ii++) {
values[ii] = data.SLONG(offset + ii*4) / data.SLONG(offset + ii*4 + 4);
}
break;
default:
continue;
}
value = (count == 1 ? values[0] : values);
if (tagDescs.hasOwnProperty(tag) && typeof value != 'object') {
hash[tag] = tagDescs[tag][value];
} else {
hash[tag] = value;
}
}
return hash;
}
function getIFDOffsets() {
var idx = offsets.tiffHeader;
// Set read order of multi-byte data
data.II(data.SHORT(idx) == 0x4949);
// Check if always present bytes are indeed present
if (data.SHORT(idx+=2) !== 0x002A) {
return false;
}
offsets.IFD0 = offsets.tiffHeader + data.LONG(idx += 2);
Tiff = extractTags(offsets.IFD0, tags.tiff);
if ('ExifIFDPointer' in Tiff) {
offsets.exifIFD = offsets.tiffHeader + Tiff.ExifIFDPointer;
delete Tiff.ExifIFDPointer;
}
if ('GPSInfoIFDPointer' in Tiff) {
offsets.gpsIFD = offsets.tiffHeader + Tiff.GPSInfoIFDPointer;
delete Tiff.GPSInfoIFDPointer;
}
return true;
}
// At the moment only setting of simple (LONG) values, that do not require offset recalculation, is supported
function setTag(ifd, tag, value) {
var offset, length, tagOffset, valueOffset = 0;
// If tag name passed translate into hex key
if (typeof(tag) === 'string') {
var tmpTags = tags[ifd.toLowerCase()];
for (var hex in tmpTags) {
if (tmpTags[hex] === tag) {
tag = hex;
break;
}
}
}
offset = offsets[ifd.toLowerCase() + 'IFD'];
length = data.SHORT(offset);
for (var i = 0; i < length; i++) {
tagOffset = offset + 12 * i + 2;
if (data.SHORT(tagOffset) == tag) {
valueOffset = tagOffset + 8;
break;
}
}
if (!valueOffset) {
return false;
}
data.LONG(valueOffset, value);
return true;
}
// Public functions
return {
init: function(segment) {
// Reset internal data
offsets = {
tiffHeader: 10
};
if (segment === undefined || !segment.length) {
return false;
}
data.init(segment);
// Check if that's APP1 and that it has EXIF
if (data.SHORT(0) === 0xFFE1 && data.STRING(4, 5).toUpperCase() === "EXIF\0") {
return getIFDOffsets();
}
return false;
},
TIFF: function() {
return Tiff;
},
EXIF: function() {
var Exif;
// Populate EXIF hash
Exif = extractTags(offsets.exifIFD, tags.exif);
// Fix formatting of some tags
if (Exif.ExifVersion && Basic.typeOf(Exif.ExifVersion) === 'array') {
for (var i = 0, exifVersion = ''; i < Exif.ExifVersion.length; i++) {
exifVersion += String.fromCharCode(Exif.ExifVersion[i]);
}
Exif.ExifVersion = exifVersion;
}
return Exif;
},
GPS: function() {
var GPS;
GPS = extractTags(offsets.gpsIFD, tags.gps);
// iOS devices (and probably some others) do not put in GPSVersionID tag (why?..)
if (GPS.GPSVersionID && Basic.typeOf(GPS.GPSVersionID) === 'array') {
GPS.GPSVersionID = GPS.GPSVersionID.join('.');
}
return GPS;
},
setExif: function(tag, value) {
// Right now only setting of width/height is possible
if (tag !== 'PixelXDimension' && tag !== 'PixelYDimension') {return false;}
return setTag('exif', tag, value);
},
getBinary: function() {
return data.SEGMENT();
},
purge: function() {
data.init(null);
data = Tiff = null;
offsets = {};
}
};
};
});
// Included from: src/javascript/runtime/html5/image/JPEG.js
/**
* JPEG.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/image/JPEG
@private
*/
define("moxie/runtime/html5/image/JPEG", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/html5/image/JPEGHeaders",
"moxie/runtime/html5/utils/BinaryReader",
"moxie/runtime/html5/image/ExifParser"
], function(Basic, x, JPEGHeaders, BinaryReader, ExifParser) {
function JPEG(binstr) {
var _binstr, _br, _hm, _ep, _info, hasExif;
function _getDimensions() {
var idx = 0, marker, length;
// examine all through the end, since some images might have very large APP segments
while (idx <= _binstr.length) {
marker = _br.SHORT(idx += 2);
if (marker >= 0xFFC0 && marker <= 0xFFC3) { // SOFn
idx += 5; // marker (2 bytes) + length (2 bytes) + Sample precision (1 byte)
return {
height: _br.SHORT(idx),
width: _br.SHORT(idx += 2)
};
}
length = _br.SHORT(idx += 2);
idx += length - 2;
}
return null;
}
_binstr = binstr;
_br = new BinaryReader();
_br.init(_binstr);
// check if it is jpeg
if (_br.SHORT(0) !== 0xFFD8) {
throw new x.ImageError(x.ImageError.WRONG_FORMAT);
}
// backup headers
_hm = new JPEGHeaders(binstr);
// extract exif info
_ep = new ExifParser();
hasExif = !!_ep.init(_hm.get('app1')[0]);
// get dimensions
_info = _getDimensions.call(this);
Basic.extend(this, {
type: 'image/jpeg',
size: _binstr.length,
width: _info && _info.width || 0,
height: _info && _info.height || 0,
setExif: function(tag, value) {
if (!hasExif) {
return false; // or throw an exception
}
if (Basic.typeOf(tag) === 'object') {
Basic.each(tag, function(value, tag) {
_ep.setExif(tag, value);
});
} else {
_ep.setExif(tag, value);
}
// update internal headers
_hm.set('app1', _ep.getBinary());
},
writeHeaders: function() {
if (!arguments.length) {
// if no arguments passed, update headers internally
return (_binstr = _hm.restore(_binstr));
}
return _hm.restore(arguments[0]);
},
stripHeaders: function(binstr) {
return _hm.strip(binstr);
},
purge: function() {
_purge.call(this);
}
});
if (hasExif) {
this.meta = {
tiff: _ep.TIFF(),
exif: _ep.EXIF(),
gps: _ep.GPS()
};
}
function _purge() {
if (!_ep || !_hm || !_br) {
return; // ignore any repeating purge requests
}
_ep.purge();
_hm.purge();
_br.init(null);
_binstr = _info = _hm = _ep = _br = null;
}
}
return JPEG;
});
// Included from: src/javascript/runtime/html5/image/PNG.js
/**
* PNG.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/image/PNG
@private
*/
define("moxie/runtime/html5/image/PNG", [
"moxie/core/Exceptions",
"moxie/core/utils/Basic",
"moxie/runtime/html5/utils/BinaryReader"
], function(x, Basic, BinaryReader) {
function PNG(binstr) {
var _binstr, _br, _hm, _ep, _info;
_binstr = binstr;
_br = new BinaryReader();
_br.init(_binstr);
// check if it's png
(function() {
var idx = 0, i = 0
, signature = [0x8950, 0x4E47, 0x0D0A, 0x1A0A]
;
for (i = 0; i < signature.length; i++, idx += 2) {
if (signature[i] != _br.SHORT(idx)) {
throw new x.ImageError(x.ImageError.WRONG_FORMAT);
}
}
}());
function _getDimensions() {
var chunk, idx;
chunk = _getChunkAt.call(this, 8);
if (chunk.type == 'IHDR') {
idx = chunk.start;
return {
width: _br.LONG(idx),
height: _br.LONG(idx += 4)
};
}
return null;
}
function _purge() {
if (!_br) {
return; // ignore any repeating purge requests
}
_br.init(null);
_binstr = _info = _hm = _ep = _br = null;
}
_info = _getDimensions.call(this);
Basic.extend(this, {
type: 'image/png',
size: _binstr.length,
width: _info.width,
height: _info.height,
purge: function() {
_purge.call(this);
}
});
// for PNG we can safely trigger purge automatically, as we do not keep any data for later
_purge.call(this);
function _getChunkAt(idx) {
var length, type, start, CRC;
length = _br.LONG(idx);
type = _br.STRING(idx += 4, 4);
start = idx += 4;
CRC = _br.LONG(idx + length);
return {
length: length,
type: type,
start: start,
CRC: CRC
};
}
}
return PNG;
});
// Included from: src/javascript/runtime/html5/image/ImageInfo.js
/**
* ImageInfo.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/image/ImageInfo
@private
*/
define("moxie/runtime/html5/image/ImageInfo", [
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/runtime/html5/image/JPEG",
"moxie/runtime/html5/image/PNG"
], function(Basic, x, JPEG, PNG) {
/**
Optional image investigation tool for HTML5 runtime. Provides the following features:
- ability to distinguish image type (JPEG or PNG) by signature
- ability to extract image width/height directly from it's internals, without preloading in memory (fast)
- ability to extract APP headers from JPEGs (Exif, GPS, etc)
- ability to replace width/height tags in extracted JPEG headers
- ability to restore APP headers, that were for example stripped during image manipulation
@class ImageInfo
@constructor
@param {String} binstr Image source as binary string
*/
return function(binstr) {
var _cs = [JPEG, PNG], _img;
// figure out the format, throw: ImageError.WRONG_FORMAT if not supported
_img = (function() {
for (var i = 0; i < _cs.length; i++) {
try {
return new _cs[i](binstr);
} catch (ex) {
// console.info(ex);
}
}
throw new x.ImageError(x.ImageError.WRONG_FORMAT);
}());
Basic.extend(this, {
/**
Image Mime Type extracted from it's depths
@property type
@type {String}
@default ''
*/
type: '',
/**
Image size in bytes
@property size
@type {Number}
@default 0
*/
size: 0,
/**
Image width extracted from image source
@property width
@type {Number}
@default 0
*/
width: 0,
/**
Image height extracted from image source
@property height
@type {Number}
@default 0
*/
height: 0,
/**
Sets Exif tag. Currently applicable only for width and height tags. Obviously works only with JPEGs.
@method setExif
@param {String} tag Tag to set
@param {Mixed} value Value to assign to the tag
*/
setExif: function() {},
/**
Restores headers to the source.
@method writeHeaders
@param {String} data Image source as binary string
@return {String} Updated binary string
*/
writeHeaders: function(data) {
return data;
},
/**
Strip all headers from the source.
@method stripHeaders
@param {String} data Image source as binary string
@return {String} Updated binary string
*/
stripHeaders: function(data) {
return data;
},
/**
Dispose resources.
@method purge
*/
purge: function() {}
});
Basic.extend(this, _img);
this.purge = function() {
_img.purge();
_img = null;
};
};
});
// Included from: src/javascript/runtime/html5/image/MegaPixel.js
/**
(The MIT License)
Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>;
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.
*/
/**
* Mega pixel image rendering library for iOS6 Safari
*
* Fixes iOS6 Safari's image file rendering issue for large size image (over mega-pixel),
* which causes unexpected subsampling when drawing it in canvas.
* By using this library, you can safely render the image with proper stretching.
*
* Copyright (c) 2012 Shinichi Tomita <shinichi.tomita@gmail.com>
* Released under the MIT license
*/
/**
@class moxie/runtime/html5/image/MegaPixel
@private
*/
define("moxie/runtime/html5/image/MegaPixel", [], function() {
/**
* Rendering image element (with resizing) into the canvas element
*/
function renderImageToCanvas(img, canvas, options) {
var iw = img.naturalWidth, ih = img.naturalHeight;
var width = options.width, height = options.height;
var x = options.x || 0, y = options.y || 0;
var ctx = canvas.getContext('2d');
if (detectSubsampling(img)) {
iw /= 2;
ih /= 2;
}
var d = 1024; // size of tiling canvas
var tmpCanvas = document.createElement('canvas');
tmpCanvas.width = tmpCanvas.height = d;
var tmpCtx = tmpCanvas.getContext('2d');
var vertSquashRatio = detectVerticalSquash(img, iw, ih);
var sy = 0;
while (sy < ih) {
var sh = sy + d > ih ? ih - sy : d;
var sx = 0;
while (sx < iw) {
var sw = sx + d > iw ? iw - sx : d;
tmpCtx.clearRect(0, 0, d, d);
tmpCtx.drawImage(img, -sx, -sy);
var dx = (sx * width / iw + x) << 0;
var dw = Math.ceil(sw * width / iw);
var dy = (sy * height / ih / vertSquashRatio + y) << 0;
var dh = Math.ceil(sh * height / ih / vertSquashRatio);
ctx.drawImage(tmpCanvas, 0, 0, sw, sh, dx, dy, dw, dh);
sx += d;
}
sy += d;
}
tmpCanvas = tmpCtx = null;
}
/**
* Detect subsampling in loaded image.
* In iOS, larger images than 2M pixels may be subsampled in rendering.
*/
function detectSubsampling(img) {
var iw = img.naturalWidth, ih = img.naturalHeight;
if (iw * ih > 1024 * 1024) { // subsampling may happen over megapixel image
var canvas = document.createElement('canvas');
canvas.width = canvas.height = 1;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, -iw + 1, 0);
// subsampled image becomes half smaller in rendering size.
// check alpha channel value to confirm image is covering edge pixel or not.
// if alpha value is 0 image is not covering, hence subsampled.
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
} else {
return false;
}
}
/**
* Detecting vertical squash in loaded image.
* Fixes a bug which squash image vertically while drawing into canvas for some images.
*/
function detectVerticalSquash(img, iw, ih) {
var canvas = document.createElement('canvas');
canvas.width = 1;
canvas.height = ih;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
var data = ctx.getImageData(0, 0, 1, ih).data;
// search image edge pixel position in case it is squashed vertically.
var sy = 0;
var ey = ih;
var py = ih;
while (py > sy) {
var alpha = data[(py - 1) * 4 + 3];
if (alpha === 0) {
ey = py;
} else {
sy = py;
}
py = (ey + sy) >> 1;
}
canvas = null;
var ratio = (py / ih);
return (ratio === 0) ? 1 : ratio;
}
return {
isSubsampled: detectSubsampling,
renderTo: renderImageToCanvas
};
});
// Included from: src/javascript/runtime/html5/image/Image.js
/**
* Image.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html5/image/Image
@private
*/
define("moxie/runtime/html5/image/Image", [
"moxie/runtime/html5/Runtime",
"moxie/core/utils/Basic",
"moxie/core/Exceptions",
"moxie/core/utils/Encode",
"moxie/file/File",
"moxie/runtime/html5/image/ImageInfo",
"moxie/runtime/html5/image/MegaPixel",
"moxie/core/utils/Mime",
"moxie/core/utils/Env"
], function(extensions, Basic, x, Encode, File, ImageInfo, MegaPixel, Mime, Env) {
function HTML5Image() {
var me = this
, _img, _imgInfo, _canvas, _binStr, _blob
, _modified = false // is set true whenever image is modified
, _preserveHeaders = true
;
Basic.extend(this, {
loadFromBlob: function(blob) {
var comp = this, I = comp.getRuntime()
, asBinary = arguments.length > 1 ? arguments[1] : true
;
if (!I.can('access_binary')) {
throw new x.RuntimeError(x.RuntimeError.NOT_SUPPORTED_ERR);
}
_blob = blob;
if (blob.isDetached()) {
_binStr = blob.getSource();
_preload.call(this, _binStr);
return;
} else {
_readAsDataUrl.call(this, blob.getSource(), function(dataUrl) {
if (asBinary) {
_binStr = _toBinary(dataUrl);
}
_preload.call(comp, dataUrl);
});
}
},
loadFromImage: function(img, exact) {
this.meta = img.meta;
_blob = new File(null, {
name: img.name,
size: img.size,
type: img.type
});
_preload.call(this, exact ? (_binStr = img.getAsBinaryString()) : img.getAsDataURL());
},
getInfo: function() {
var I = this.getRuntime(), info;
if (!_imgInfo && _binStr && I.can('access_image_binary')) {
_imgInfo = new ImageInfo(_binStr);
}
info = {
width: _getImg().width || 0,
height: _getImg().height || 0,
type: _blob.type || Mime.getFileMime(_blob.name),
size: _binStr && _binStr.length || _blob.size || 0,
name: _blob.name || '',
meta: _imgInfo && _imgInfo.meta || this.meta || {}
};
return info;
},
downsize: function() {
_downsize.apply(this, arguments);
},
getAsCanvas: function() {
if (_canvas) {
_canvas.id = this.uid + '_canvas';
}
return _canvas;
},
getAsBlob: function(type, quality) {
if (type !== this.type) {
// if different mime type requested prepare image for conversion
_downsize.call(this, this.width, this.height, false);
}
return new File(null, {
name: _blob.name || '',
type: type,
data: me.getAsBinaryString.call(this, type, quality)
});
},
getAsDataURL: function(type) {
var quality = arguments[1] || 90;
// if image has not been modified, return the source right away
if (!_modified) {
return _img.src;
}
if ('image/jpeg' !== type) {
return _canvas.toDataURL('image/png');
} else {
try {
// older Geckos used to result in an exception on quality argument
return _canvas.toDataURL('image/jpeg', quality/100);
} catch (ex) {
return _canvas.toDataURL('image/jpeg');
}
}
},
getAsBinaryString: function(type, quality) {
// if image has not been modified, return the source right away
if (!_modified) {
// if image was not loaded from binary string
if (!_binStr) {
_binStr = _toBinary(me.getAsDataURL(type, quality));
}
return _binStr;
}
if ('image/jpeg' !== type) {
_binStr = _toBinary(me.getAsDataURL(type, quality));
} else {
var dataUrl;
// if jpeg
if (!quality) {
quality = 90;
}
try {
// older Geckos used to result in an exception on quality argument
dataUrl = _canvas.toDataURL('image/jpeg', quality/100);
} catch (ex) {
dataUrl = _canvas.toDataURL('image/jpeg');
}
_binStr = _toBinary(dataUrl);
if (_imgInfo) {
_binStr = _imgInfo.stripHeaders(_binStr);
if (_preserveHeaders) {
// update dimensions info in exif
if (_imgInfo.meta && _imgInfo.meta.exif) {
_imgInfo.setExif({
PixelXDimension: this.width,
PixelYDimension: this.height
});
}
// re-inject the headers
_binStr = _imgInfo.writeHeaders(_binStr);
}
// will be re-created from fresh on next getInfo call
_imgInfo.purge();
_imgInfo = null;
}
}
_modified = false;
return _binStr;
},
destroy: function() {
me = null;
_purge.call(this);
this.getRuntime().getShim().removeInstance(this.uid);
}
});
function _getImg() {
if (!_canvas && !_img) {
throw new x.ImageError(x.DOMException.INVALID_STATE_ERR);
}
return _canvas || _img;
}
function _toBinary(str) {
return Encode.atob(str.substring(str.indexOf('base64,') + 7));
}
function _toDataUrl(str, type) {
return 'data:' + (type || '') + ';base64,' + Encode.btoa(str);
}
function _preload(str) {
var comp = this;
_img = new Image();
_img.onerror = function() {
_purge.call(this);
comp.trigger('error', x.ImageError.WRONG_FORMAT);
};
_img.onload = function() {
comp.trigger('load');
};
_img.src = /^data:[^;]*;base64,/.test(str) ? str : _toDataUrl(str, _blob.type);
}
function _readAsDataUrl(file, callback) {
var comp = this, fr;
// use FileReader if it's available
if (window.FileReader) {
fr = new FileReader();
fr.onload = function() {
callback(this.result);
};
fr.onerror = function() {
comp.trigger('error', x.ImageError.WRONG_FORMAT);
};
fr.readAsDataURL(file);
} else {
return callback(file.getAsDataURL());
}
}
function _downsize(width, height, crop, preserveHeaders) {
var self = this
, scale
, mathFn
, x = 0
, y = 0
, img
, destWidth
, destHeight
, orientation
;
_preserveHeaders = preserveHeaders; // we will need to check this on export (see getAsBinaryString())
// take into account orientation tag
orientation = (this.meta && this.meta.tiff && this.meta.tiff.Orientation) || 1;
if (Basic.inArray(orientation, [5,6,7,8]) !== -1) { // values that require 90 degree rotation
// swap dimensions
var tmp = width;
width = height;
height = tmp;
}
img = _getImg();
// unify dimensions
if (!crop) {
scale = Math.min(width/img.width, height/img.height);
} else {
// one of the dimensions may exceed the actual image dimensions - we need to take the smallest value
width = Math.min(width, img.width);
height = Math.min(height, img.height);
scale = Math.max(width/img.width, height/img.height);
}
// we only downsize here
if (scale > 1 && !crop && preserveHeaders) {
this.trigger('Resize');
return;
}
// prepare canvas if necessary
if (!_canvas) {
_canvas = document.createElement("canvas");
}
// calculate dimensions of proportionally resized image
destWidth = Math.round(img.width * scale);
destHeight = Math.round(img.height * scale);
// scale image and canvas
if (crop) {
_canvas.width = width;
_canvas.height = height;
// if dimensions of the resulting image still larger than canvas, center it
if (destWidth > width) {
x = Math.round((destWidth - width) / 2);
}
if (destHeight > height) {
y = Math.round((destHeight - height) / 2);
}
} else {
_canvas.width = destWidth;
_canvas.height = destHeight;
}
// rotate if required, according to orientation tag
if (!_preserveHeaders) {
_rotateToOrientaion(_canvas.width, _canvas.height, orientation);
}
_drawToCanvas.call(this, img, _canvas, -x, -y, destWidth, destHeight);
this.width = _canvas.width;
this.height = _canvas.height;
_modified = true;
self.trigger('Resize');
}
function _drawToCanvas(img, canvas, x, y, w, h) {
if (Env.OS === 'iOS') {
// avoid squish bug in iOS6
MegaPixel.renderTo(img, canvas, { width: w, height: h, x: x, y: y });
} else {
var ctx = canvas.getContext('2d');
ctx.drawImage(img, x, y, w, h);
}
}
/**
* Transform canvas coordination according to specified frame size and orientation
* Orientation value is from EXIF tag
* @author Shinichi Tomita <shinichi.tomita@gmail.com>
*/
function _rotateToOrientaion(width, height, orientation) {
switch (orientation) {
case 5:
case 6:
case 7:
case 8:
_canvas.width = height;
_canvas.height = width;
break;
default:
_canvas.width = width;
_canvas.height = height;
}
/**
1 = The 0th row is at the visual top of the image, and the 0th column is the visual left-hand side.
2 = The 0th row is at the visual top of the image, and the 0th column is the visual right-hand side.
3 = The 0th row is at the visual bottom of the image, and the 0th column is the visual right-hand side.
4 = The 0th row is at the visual bottom of the image, and the 0th column is the visual left-hand side.
5 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual top.
6 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual top.
7 = The 0th row is the visual right-hand side of the image, and the 0th column is the visual bottom.
8 = The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.
*/
var ctx = _canvas.getContext('2d');
switch (orientation) {
case 2:
// horizontal flip
ctx.translate(width, 0);
ctx.scale(-1, 1);
break;
case 3:
// 180 rotate left
ctx.translate(width, height);
ctx.rotate(Math.PI);
break;
case 4:
// vertical flip
ctx.translate(0, height);
ctx.scale(1, -1);
break;
case 5:
// vertical flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.scale(1, -1);
break;
case 6:
// 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(0, -height);
break;
case 7:
// horizontal flip + 90 rotate right
ctx.rotate(0.5 * Math.PI);
ctx.translate(width, -height);
ctx.scale(-1, 1);
break;
case 8:
// 90 rotate left
ctx.rotate(-0.5 * Math.PI);
ctx.translate(-width, 0);
break;
}
}
function _purge() {
if (_imgInfo) {
_imgInfo.purge();
_imgInfo = null;
}
_binStr = _img = _canvas = _blob = null;
_modified = false;
}
}
return (extensions.Image = HTML5Image);
});
// Included from: src/javascript/runtime/html4/image/Image.js
/**
* Image.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/**
@class moxie/runtime/html4/image/Image
@private
*/
define("moxie/runtime/html4/image/Image", [
"moxie/runtime/html4/Runtime",
"moxie/runtime/html5/image/Image"
], function(extensions, Image) {
return (extensions.Image = Image);
});
expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/image/Image","moxie/core/utils/Events"]);
})(this);/**
* o.js
*
* Copyright 2013, Moxiecode Systems AB
* Released under GPL License.
*
* License: http://www.plupload.com/license
* Contributing: http://www.plupload.com/contributing
*/
/*global moxie:true */
/**
Globally exposed namespace with the most frequently used public classes and handy methods.
@class o
@static
@private
*/
(function(exports) {
"use strict";
var o = {}, inArray = exports.moxie.core.utils.Basic.inArray;
// directly add some public classes
// (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included)
(function addAlias(ns) {
var name, itemType;
for (name in ns) {
itemType = typeof(ns[name]);
if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) {
addAlias(ns[name]);
} else if (itemType === 'function') {
o[name] = ns[name];
}
}
})(exports.moxie);
// add some manually
o.Env = exports.moxie.core.utils.Env;
o.Mime = exports.moxie.core.utils.Mime;
o.Exceptions = exports.moxie.core.Exceptions;
// expose globally
exports.mOxie = o;
if (!exports.o) {
exports.o = o;
}
return o;
})(this);
|
client/containers/sensors.js
|
CodeWriterWriter/vidi-dashboard
|
'use strict'
import React from 'react'
import {connect} from 'react-redux'
import {Link} from 'react-router'
import {Panel, PageHeader, InfoCell} from '../components/index'
import ChartistGraph from 'react-chartist'
import {subscribe, unsubscribe} from '../actions/vidi'
import _ from 'lodash'
export const Overview = React.createClass({
componentDidMount () {
this.props.dispatch(subscribe('sensors'))
},
componentWillUnmount () {
this.props.dispatch(unsubscribe('sensors'))
},
render () {
var sections = []
var groups = _.groupBy(this.props.sensors, 'sensor_type')
var sortedKeys = _.keys(groups).sort()
_.each(sortedKeys, (theKey) => {
var group = groups[theKey]
if (group) {
var proc_sections = []
var data = _.orderBy(group, ['sensor_id'], ['desc'])
var count = data.length
var tag = ''
var key
_.each(data, (message) => {
if (message) {
tag = message.sensor_type
proc_sections.push(makeMessageSections(message))
}
})
sections.push(
<div key={tag} className="process-group panel">
<div className="panel-heading cf">
<h3 className="m0 fl-left"><strong>{tag}</strong></h3>
<a href="" className="fl-right icon icon-collapse"></a>
</div>
<div className="panel-body">
{proc_sections}
</div>
</div>
)
}
})
return (
<div className="page page-processes">
<div className="container-fluid">
<PageHeader title={'Sensors'} />
</div>
<div className="container-fluid">
{sections}
</div>
</div>
)
}
})
export default connect((state) => {
var vidi = state.vidi
var sensors = vidi.sensors || {data: [null]}
return {
sensors: sensors.data
}
})(Overview)
function makeMessageSections (messages) {
var section = []
var now = messages.latest
return (
<div key={now.sensor_id} className="process-card">
<div className="process-heading has-icon">
<span className="status status-healthy status-small" title="Status: healthy"></span>
{`${now.topic}/${now.sensor_id}`}
</div>
<div className="row middle-xs process-stats-row no-gutter">
<InfoCell title={'UOM'} value={now.uom} />
<InfoCell title={'Broker'} value={now.broker_id} />
<InfoCell title={'Topic'} value={now.topic} />
</div>
<div className="row middle-xs no-gutter">
<div className="col-xs-12 mt">
<ChartistGraph
type={'Line'}
data={{labels: messages.series.time, series: [messages.series.value]}}
options={{
fullWidth: true,
showArea: false,
showLine: true,
showPoint: false,
chartPadding: {right: 30},
axisY: {onlyInteger: true},
axisX: {labelOffset: {x: -15}, labelInterpolationFnc: (val) => {
if (_.last(val) == '0') return val
else return null
}},
}}/>
</div>
</div>
</div>
)
}
|
ajax/libs/highmaps/1.1.0/highmaps.src.js
|
kristoferjoseph/cdnjs
|
// ==ClosureCompiler==
// @compilation_level SIMPLE_OPTIMIZATIONS
/**
* @license Highmaps JS v1.1.0 (2015-02-16)
*
* (c) 2009-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
// JSLint options:
/*global Highcharts, HighchartsAdapter, document, window, navigator, setInterval, clearInterval, clearTimeout, setTimeout, location, jQuery, $, console, each, grep */
/*jslint ass: true, sloppy: true, forin: true, plusplus: true, nomen: true, vars: true, regexp: true, newcap: true, browser: true, continue: true, white: true */
(function () {
// encapsulated variables
var UNDEFINED,
doc = document,
win = window,
math = Math,
mathRound = math.round,
mathFloor = math.floor,
mathCeil = math.ceil,
mathMax = math.max,
mathMin = math.min,
mathAbs = math.abs,
mathCos = math.cos,
mathSin = math.sin,
mathPI = math.PI,
deg2rad = mathPI * 2 / 360,
// some variables
userAgent = navigator.userAgent,
isOpera = win.opera,
isIE = /(msie|trident)/i.test(userAgent) && !isOpera,
docMode8 = doc.documentMode === 8,
isWebKit = /AppleWebKit/.test(userAgent),
isFirefox = /Firefox/.test(userAgent),
isTouchDevice = /(Mobile|Android|Windows Phone)/.test(userAgent),
SVG_NS = 'http://www.w3.org/2000/svg',
hasSVG = !!doc.createElementNS && !!doc.createElementNS(SVG_NS, 'svg').createSVGRect,
hasBidiBug = isFirefox && parseInt(userAgent.split('Firefox/')[1], 10) < 4, // issue #38
useCanVG = !hasSVG && !isIE && !!doc.createElement('canvas').getContext,
Renderer,
hasTouch,
symbolSizes = {},
idCounter = 0,
garbageBin,
defaultOptions,
dateFormat, // function
globalAnimation,
pathAnim,
timeUnits,
noop = function () { return UNDEFINED; },
charts = [],
chartCount = 0,
PRODUCT = 'Highmaps',
VERSION = '1.1.0',
// some constants for frequently used strings
DIV = 'div',
ABSOLUTE = 'absolute',
RELATIVE = 'relative',
HIDDEN = 'hidden',
PREFIX = 'highcharts-',
VISIBLE = 'visible',
PX = 'px',
NONE = 'none',
M = 'M',
L = 'L',
numRegex = /^[0-9]+$/,
NORMAL_STATE = '',
HOVER_STATE = 'hover',
SELECT_STATE = 'select',
marginNames = ['plotTop', 'marginRight', 'marginBottom', 'plotLeft'],
// Object for extending Axis
AxisPlotLineOrBandExtension,
// constants for attributes
STROKE_WIDTH = 'stroke-width',
// time methods, changed based on whether or not UTC is used
Date, // Allow using a different Date class
makeTime,
timezoneOffset,
getTimezoneOffset,
getMinutes,
getHours,
getDay,
getDate,
getMonth,
getFullYear,
setMinutes,
setHours,
setDate,
setMonth,
setFullYear,
// lookup over the types and the associated classes
seriesTypes = {},
Highcharts;
// The Highcharts namespace
Highcharts = win.Highcharts = win.Highcharts ? error(16, true) : {};
Highcharts.seriesTypes = seriesTypes;
/**
* Extend an object with the members of another
* @param {Object} a The object to be extended
* @param {Object} b The object to add to the first one
*/
var extend = Highcharts.extend = function (a, b) {
var n;
if (!a) {
a = {};
}
for (n in b) {
a[n] = b[n];
}
return a;
};
/**
* Deep merge two or more objects and return a third object. If the first argument is
* true, the contents of the second object is copied into the first object.
* Previously this function redirected to jQuery.extend(true), but this had two limitations.
* First, it deep merged arrays, which lead to workarounds in Highcharts. Second,
* it copied properties from extended prototypes.
*/
function merge() {
var i,
args = arguments,
len,
ret = {},
doCopy = function (copy, original) {
var value, key;
// An object is replacing a primitive
if (typeof copy !== 'object') {
copy = {};
}
for (key in original) {
if (original.hasOwnProperty(key)) {
value = original[key];
// Copy the contents of objects, but not arrays or DOM nodes
if (value && typeof value === 'object' && Object.prototype.toString.call(value) !== '[object Array]'
&& key !== 'renderTo' && typeof value.nodeType !== 'number') {
copy[key] = doCopy(copy[key] || {}, value);
// Primitives and arrays are copied over directly
} else {
copy[key] = original[key];
}
}
}
return copy;
};
// If first argument is true, copy into the existing object. Used in setOptions.
if (args[0] === true) {
ret = args[1];
args = Array.prototype.slice.call(args, 2);
}
// For each argument, extend the return
len = args.length;
for (i = 0; i < len; i++) {
ret = doCopy(ret, args[i]);
}
return ret;
}
/**
* Shortcut for parseInt
* @param {Object} s
* @param {Number} mag Magnitude
*/
function pInt(s, mag) {
return parseInt(s, mag || 10);
}
/**
* Check for string
* @param {Object} s
*/
function isString(s) {
return typeof s === 'string';
}
/**
* Check for object
* @param {Object} obj
*/
function isObject(obj) {
return obj && typeof obj === 'object';
}
/**
* Check for array
* @param {Object} obj
*/
function isArray(obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
}
/**
* Check for number
* @param {Object} n
*/
function isNumber(n) {
return typeof n === 'number';
}
function log2lin(num) {
return math.log(num) / math.LN10;
}
function lin2log(num) {
return math.pow(10, num);
}
/**
* Remove last occurence of an item from an array
* @param {Array} arr
* @param {Mixed} item
*/
function erase(arr, item) {
var i = arr.length;
while (i--) {
if (arr[i] === item) {
arr.splice(i, 1);
break;
}
}
//return arr;
}
/**
* Returns true if the object is not null or undefined. Like MooTools' $.defined.
* @param {Object} obj
*/
function defined(obj) {
return obj !== UNDEFINED && obj !== null;
}
/**
* Set or get an attribute or an object of attributes. Can't use jQuery attr because
* it attempts to set expando properties on the SVG element, which is not allowed.
*
* @param {Object} elem The DOM element to receive the attribute(s)
* @param {String|Object} prop The property or an abject of key-value pairs
* @param {String} value The value if a single property is set
*/
function attr(elem, prop, value) {
var key,
ret;
// if the prop is a string
if (isString(prop)) {
// set the value
if (defined(value)) {
elem.setAttribute(prop, value);
// get the value
} else if (elem && elem.getAttribute) { // elem not defined when printing pie demo...
ret = elem.getAttribute(prop);
}
// else if prop is defined, it is a hash of key/value pairs
} else if (defined(prop) && isObject(prop)) {
for (key in prop) {
elem.setAttribute(key, prop[key]);
}
}
return ret;
}
/**
* Check if an element is an array, and if not, make it into an array. Like
* MooTools' $.splat.
*/
function splat(obj) {
return isArray(obj) ? obj : [obj];
}
/**
* Return the first value that is defined. Like MooTools' $.pick.
*/
var pick = Highcharts.pick = function () {
var args = arguments,
i,
arg,
length = args.length;
for (i = 0; i < length; i++) {
arg = args[i];
if (arg !== UNDEFINED && arg !== null) {
return arg;
}
}
};
/**
* Set CSS on a given element
* @param {Object} el
* @param {Object} styles Style object with camel case property names
*/
function css(el, styles) {
if (isIE && !hasSVG) { // #2686
if (styles && styles.opacity !== UNDEFINED) {
styles.filter = 'alpha(opacity=' + (styles.opacity * 100) + ')';
}
}
extend(el.style, styles);
}
/**
* Utility function to create element with attributes and styles
* @param {Object} tag
* @param {Object} attribs
* @param {Object} styles
* @param {Object} parent
* @param {Object} nopad
*/
function createElement(tag, attribs, styles, parent, nopad) {
var el = doc.createElement(tag);
if (attribs) {
extend(el, attribs);
}
if (nopad) {
css(el, {padding: 0, border: NONE, margin: 0});
}
if (styles) {
css(el, styles);
}
if (parent) {
parent.appendChild(el);
}
return el;
}
/**
* Extend a prototyped class by new members
* @param {Object} parent
* @param {Object} members
*/
function extendClass(parent, members) {
var object = function () { return UNDEFINED; };
object.prototype = new parent();
extend(object.prototype, members);
return object;
}
/**
* Pad a string to a given length by adding 0 to the beginning
* @param {Number} number
* @param {Number} length
*/
function pad(number, length) {
// Create an array of the remaining length +1 and join it with 0's
return new Array((length || 2) + 1 - String(number).length).join(0) + number;
}
/**
* Wrap a method with extended functionality, preserving the original function
* @param {Object} obj The context object that the method belongs to
* @param {String} method The name of the method to extend
* @param {Function} func A wrapper function callback. This function is called with the same arguments
* as the original function, except that the original function is unshifted and passed as the first
* argument.
*/
var wrap = Highcharts.wrap = function (obj, method, func) {
var proceed = obj[method];
obj[method] = function () {
var args = Array.prototype.slice.call(arguments);
args.unshift(proceed);
return func.apply(this, args);
};
};
function getTZOffset(timestamp) {
return ((getTimezoneOffset && getTimezoneOffset(timestamp)) || timezoneOffset || 0) * 60000;
}
/**
* Based on http://www.php.net/manual/en/function.strftime.php
* @param {String} format
* @param {Number} timestamp
* @param {Boolean} capitalize
*/
dateFormat = function (format, timestamp, capitalize) {
if (!defined(timestamp) || isNaN(timestamp)) {
return 'Invalid date';
}
format = pick(format, '%Y-%m-%d %H:%M:%S');
var date = new Date(timestamp - getTZOffset(timestamp)),
key, // used in for constuct below
// get the basic time values
hours = date[getHours](),
day = date[getDay](),
dayOfMonth = date[getDate](),
month = date[getMonth](),
fullYear = date[getFullYear](),
lang = defaultOptions.lang,
langWeekdays = lang.weekdays,
// List all format keys. Custom formats can be added from the outside.
replacements = extend({
// Day
'a': langWeekdays[day].substr(0, 3), // Short weekday, like 'Mon'
'A': langWeekdays[day], // Long weekday, like 'Monday'
'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31
'e': dayOfMonth, // Day of the month, 1 through 31
'w': day,
// Week (none implemented)
//'W': weekNumber(),
// Month
'b': lang.shortMonths[month], // Short month, like 'Jan'
'B': lang.months[month], // Long month, like 'January'
'm': pad(month + 1), // Two digit month number, 01 through 12
// Year
'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
'Y': fullYear, // Four digits year, like 2009
// Time
'H': pad(hours), // Two digits hours in 24h format, 00 through 23
'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
'l': (hours % 12) || 12, // Hours in 12h format, 1 through 12
'M': pad(date[getMinutes]()), // Two digits minutes, 00 through 59
'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
'S': pad(date.getSeconds()), // Two digits seconds, 00 through 59
'L': pad(mathRound(timestamp % 1000), 3) // Milliseconds (naming from Ruby)
}, Highcharts.dateFormats);
// do the replaces
for (key in replacements) {
while (format.indexOf('%' + key) !== -1) { // regex would do it in one line, but this is faster
format = format.replace('%' + key, typeof replacements[key] === 'function' ? replacements[key](timestamp) : replacements[key]);
}
}
// Optionally capitalize the string and return
return capitalize ? format.substr(0, 1).toUpperCase() + format.substr(1) : format;
};
/**
* Format a single variable. Similar to sprintf, without the % prefix.
*/
function formatSingle(format, val) {
var floatRegex = /f$/,
decRegex = /\.([0-9])/,
lang = defaultOptions.lang,
decimals;
if (floatRegex.test(format)) { // float
decimals = format.match(decRegex);
decimals = decimals ? decimals[1] : -1;
if (val !== null) {
val = Highcharts.numberFormat(
val,
decimals,
lang.decimalPoint,
format.indexOf(',') > -1 ? lang.thousandsSep : ''
);
}
} else {
val = dateFormat(format, val);
}
return val;
}
/**
* Format a string according to a subset of the rules of Python's String.format method.
*/
function format(str, ctx) {
var splitter = '{',
isInside = false,
segment,
valueAndFormat,
path,
i,
len,
ret = [],
val,
index;
while ((index = str.indexOf(splitter)) !== -1) {
segment = str.slice(0, index);
if (isInside) { // we're on the closing bracket looking back
valueAndFormat = segment.split(':');
path = valueAndFormat.shift().split('.'); // get first and leave format
len = path.length;
val = ctx;
// Assign deeper paths
for (i = 0; i < len; i++) {
val = val[path[i]];
}
// Format the replacement
if (valueAndFormat.length) {
val = formatSingle(valueAndFormat.join(':'), val);
}
// Push the result and advance the cursor
ret.push(val);
} else {
ret.push(segment);
}
str = str.slice(index + 1); // the rest
isInside = !isInside; // toggle
splitter = isInside ? '}' : '{'; // now look for next matching bracket
}
ret.push(str);
return ret.join('');
}
/**
* Get the magnitude of a number
*/
function getMagnitude(num) {
return math.pow(10, mathFloor(math.log(num) / math.LN10));
}
/**
* Take an interval and normalize it to multiples of 1, 2, 2.5 and 5
* @param {Number} interval
* @param {Array} multiples
* @param {Number} magnitude
* @param {Object} options
*/
function normalizeTickInterval(interval, multiples, magnitude, allowDecimals, preventExceed) {
var normalized,
i,
retInterval = interval;
// round to a tenfold of 1, 2, 2.5 or 5
magnitude = pick(magnitude, 1);
normalized = interval / magnitude;
// multiples for a linear scale
if (!multiples) {
multiples = [1, 2, 2.5, 5, 10];
// the allowDecimals option
if (allowDecimals === false) {
if (magnitude === 1) {
multiples = [1, 2, 5, 10];
} else if (magnitude <= 0.1) {
multiples = [1 / magnitude];
}
}
}
// normalize the interval to the nearest multiple
for (i = 0; i < multiples.length; i++) {
retInterval = multiples[i];
if ((preventExceed && retInterval * magnitude >= interval) || // only allow tick amounts smaller than natural
(!preventExceed && (normalized <= (multiples[i] + (multiples[i + 1] || multiples[i])) / 2))) {
break;
}
}
// multiply back to the correct magnitude
retInterval *= magnitude;
return retInterval;
}
/**
* Utility method that sorts an object array and keeping the order of equal items.
* ECMA script standard does not specify the behaviour when items are equal.
*/
function stableSort(arr, sortFunction) {
var length = arr.length,
sortValue,
i;
// Add index to each item
for (i = 0; i < length; i++) {
arr[i].ss_i = i; // stable sort index
}
arr.sort(function (a, b) {
sortValue = sortFunction(a, b);
return sortValue === 0 ? a.ss_i - b.ss_i : sortValue;
});
// Remove index from items
for (i = 0; i < length; i++) {
delete arr[i].ss_i; // stable sort index
}
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMin(data) {
var i = data.length,
min = data[0];
while (i--) {
if (data[i] < min) {
min = data[i];
}
}
return min;
}
/**
* Non-recursive method to find the lowest member of an array. Math.min raises a maximum
* call stack size exceeded error in Chrome when trying to apply more than 150.000 points. This
* method is slightly slower, but safe.
*/
function arrayMax(data) {
var i = data.length,
max = data[0];
while (i--) {
if (data[i] > max) {
max = data[i];
}
}
return max;
}
/**
* Utility method that destroys any SVGElement or VMLElement that are properties on the given object.
* It loops all properties and invokes destroy if there is a destroy method. The property is
* then delete'ed.
* @param {Object} The object to destroy properties on
* @param {Object} Exception, do not destroy this property, only delete it.
*/
function destroyObjectProperties(obj, except) {
var n;
for (n in obj) {
// If the object is non-null and destroy is defined
if (obj[n] && obj[n] !== except && obj[n].destroy) {
// Invoke the destroy
obj[n].destroy();
}
// Delete the property from the object.
delete obj[n];
}
}
/**
* Discard an element by moving it to the bin and delete
* @param {Object} The HTML node to discard
*/
function discardElement(element) {
// create a garbage bin element, not part of the DOM
if (!garbageBin) {
garbageBin = createElement(DIV);
}
// move the node and empty bin
if (element) {
garbageBin.appendChild(element);
}
garbageBin.innerHTML = '';
}
/**
* Provide error messages for debugging, with links to online explanation
*/
function error (code, stop) {
var msg = 'Highcharts error #' + code + ': www.highcharts.com/errors/' + code;
if (stop) {
throw msg;
}
// else ...
if (win.console) {
console.log(msg);
}
}
/**
* Fix JS round off float errors
* @param {Number} num
*/
function correctFloat(num) {
return parseFloat(
num.toPrecision(14)
);
}
/**
* Set the global animation to either a given value, or fall back to the
* given chart's animation option
* @param {Object} animation
* @param {Object} chart
*/
function setAnimation(animation, chart) {
globalAnimation = pick(animation, chart.animation);
}
/**
* The time unit lookup
*/
timeUnits = {
millisecond: 1,
second: 1000,
minute: 60000,
hour: 3600000,
day: 24 * 3600000,
week: 7 * 24 * 3600000,
month: 28 * 24 * 3600000,
year: 364 * 24 * 3600000
};
/**
* Format a number and return a string based on input settings
* @param {Number} number The input number to format
* @param {Number} decimals The amount of decimals
* @param {String} decPoint The decimal point, defaults to the one given in the lang options
* @param {String} thousandsSep The thousands separator, defaults to the one given in the lang options
*/
Highcharts.numberFormat = function (number, decimals, decPoint, thousandsSep) {
var lang = defaultOptions.lang,
// http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_number_format/
n = +number || 0,
c = decimals === -1 ?
(n.toString().split('.')[1] || '').length : // preserve decimals
(isNaN(decimals = mathAbs(decimals)) ? 2 : decimals),
d = decPoint === undefined ? lang.decimalPoint : decPoint,
t = thousandsSep === undefined ? lang.thousandsSep : thousandsSep,
s = n < 0 ? "-" : "",
i = String(pInt(n = mathAbs(n).toFixed(c))),
j = i.length > 3 ? i.length % 3 : 0;
return (s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
(c ? d + mathAbs(n - i).toFixed(c).slice(2) : ""));
};
/**
* Path interpolation algorithm used across adapters
*/
pathAnim = {
/**
* Prepare start and end values so that the path can be animated one to one
*/
init: function (elem, fromD, toD) {
fromD = fromD || '';
var shift = elem.shift,
bezier = fromD.indexOf('C') > -1,
numParams = bezier ? 7 : 3,
endLength,
slice,
i,
start = fromD.split(' '),
end = [].concat(toD), // copy
startBaseLine,
endBaseLine,
sixify = function (arr) { // in splines make move points have six parameters like bezier curves
i = arr.length;
while (i--) {
if (arr[i] === M) {
arr.splice(i + 1, 0, arr[i + 1], arr[i + 2], arr[i + 1], arr[i + 2]);
}
}
};
if (bezier) {
sixify(start);
sixify(end);
}
// pull out the base lines before padding
if (elem.isArea) {
startBaseLine = start.splice(start.length - 6, 6);
endBaseLine = end.splice(end.length - 6, 6);
}
// if shifting points, prepend a dummy point to the end path
if (shift <= end.length / numParams && start.length === end.length) {
while (shift--) {
end = [].concat(end).splice(0, numParams).concat(end);
}
}
elem.shift = 0; // reset for following animations
// copy and append last point until the length matches the end length
if (start.length) {
endLength = end.length;
while (start.length < endLength) {
//bezier && sixify(start);
slice = [].concat(start).splice(start.length - numParams, numParams);
if (bezier) { // disable first control point
slice[numParams - 6] = slice[numParams - 2];
slice[numParams - 5] = slice[numParams - 1];
}
start = start.concat(slice);
}
}
if (startBaseLine) { // append the base lines for areas
start = start.concat(startBaseLine);
end = end.concat(endBaseLine);
}
return [start, end];
},
/**
* Interpolate each value of the path and return the array
*/
step: function (start, end, pos, complete) {
var ret = [],
i = start.length,
startVal;
if (pos === 1) { // land on the final path without adjustment points appended in the ends
ret = complete;
} else if (i === end.length && pos < 1) {
while (i--) {
startVal = parseFloat(start[i]);
ret[i] =
isNaN(startVal) ? // a letter instruction like M or L
start[i] :
pos * (parseFloat(end[i] - startVal)) + startVal;
}
} else { // if animation is finished or length not matching, land on right value
ret = end;
}
return ret;
}
};
(function ($) {
/**
* The default HighchartsAdapter for jQuery
*/
win.HighchartsAdapter = win.HighchartsAdapter || ($ && {
/**
* Initialize the adapter by applying some extensions to jQuery
*/
init: function (pathAnim) {
// extend the animate function to allow SVG animations
var Fx = $.fx;
/*jslint unparam: true*//* allow unused param x in this function */
$.extend($.easing, {
easeOutQuad: function (x, t, b, c, d) {
return -c * (t /= d) * (t - 2) + b;
}
});
/*jslint unparam: false*/
// extend some methods to check for elem.attr, which means it is a Highcharts SVG object
$.each(['cur', '_default', 'width', 'height', 'opacity'], function (i, fn) {
var obj = Fx.step,
base;
// Handle different parent objects
if (fn === 'cur') {
obj = Fx.prototype; // 'cur', the getter, relates to Fx.prototype
} else if (fn === '_default' && $.Tween) { // jQuery 1.8 model
obj = $.Tween.propHooks[fn];
fn = 'set';
}
// Overwrite the method
base = obj[fn];
if (base) { // step.width and step.height don't exist in jQuery < 1.7
// create the extended function replacement
obj[fn] = function (fx) {
var elem;
// Fx.prototype.cur does not use fx argument
fx = i ? fx : this;
// Don't run animations on textual properties like align (#1821)
if (fx.prop === 'align') {
return;
}
// shortcut
elem = fx.elem;
// Fx.prototype.cur returns the current value. The other ones are setters
// and returning a value has no effect.
return elem.attr ? // is SVG element wrapper
elem.attr(fx.prop, fn === 'cur' ? UNDEFINED : fx.now) : // apply the SVG wrapper's method
base.apply(this, arguments); // use jQuery's built-in method
};
}
});
// Extend the opacity getter, needed for fading opacity with IE9 and jQuery 1.10+
wrap($.cssHooks.opacity, 'get', function (proceed, elem, computed) {
return elem.attr ? (elem.opacity || 0) : proceed.call(this, elem, computed);
});
// Define the setter function for d (path definitions)
this.addAnimSetter('d', function (fx) {
var elem = fx.elem,
ends;
// Normally start and end should be set in state == 0, but sometimes,
// for reasons unknown, this doesn't happen. Perhaps state == 0 is skipped
// in these cases
if (!fx.started) {
ends = pathAnim.init(elem, elem.d, elem.toD);
fx.start = ends[0];
fx.end = ends[1];
fx.started = true;
}
// Interpolate each value of the path
elem.attr('d', pathAnim.step(fx.start, fx.end, fx.pos, elem.toD));
});
/**
* Utility for iterating over an array. Parameters are reversed compared to jQuery.
* @param {Array} arr
* @param {Function} fn
*/
this.each = Array.prototype.forEach ?
function (arr, fn) { // modern browsers
return Array.prototype.forEach.call(arr, fn);
} :
function (arr, fn) { // legacy
var i,
len = arr.length;
for (i = 0; i < len; i++) {
if (fn.call(arr[i], arr[i], i, arr) === false) {
return i;
}
}
};
/**
* Register Highcharts as a plugin in the respective framework
*/
$.fn.highcharts = function () {
var constr = 'Chart', // default constructor
args = arguments,
options,
ret,
chart;
if (this[0]) {
if (isString(args[0])) {
constr = args[0];
args = Array.prototype.slice.call(args, 1);
}
options = args[0];
// Create the chart
if (options !== UNDEFINED) {
/*jslint unused:false*/
options.chart = options.chart || {};
options.chart.renderTo = this[0];
chart = new Highcharts[constr](options, args[1]);
ret = this;
/*jslint unused:true*/
}
// When called without parameters or with the return argument, get a predefined chart
if (options === UNDEFINED) {
ret = charts[attr(this[0], 'data-highcharts-chart')];
}
}
return ret;
};
},
/**
* Add an animation setter for a specific property
*/
addAnimSetter: function (prop, setter) {
// jQuery 1.8 style
if ($.Tween) {
$.Tween.propHooks[prop] = {
set: setter
};
// pre 1.8
} else {
$.fx.step[prop] = setter;
}
},
/**
* Downloads a script and executes a callback when done.
* @param {String} scriptLocation
* @param {Function} callback
*/
getScript: $.getScript,
/**
* Return the index of an item in an array, or -1 if not found
*/
inArray: $.inArray,
/**
* A direct link to jQuery methods. MooTools and Prototype adapters must be implemented for each case of method.
* @param {Object} elem The HTML element
* @param {String} method Which method to run on the wrapped element
*/
adapterRun: function (elem, method) {
return $(elem)[method]();
},
/**
* Filter an array
*/
grep: $.grep,
/**
* Map an array
* @param {Array} arr
* @param {Function} fn
*/
map: function (arr, fn) {
//return jQuery.map(arr, fn);
var results = [],
i = 0,
len = arr.length;
for (; i < len; i++) {
results[i] = fn.call(arr[i], arr[i], i, arr);
}
return results;
},
/**
* Get the position of an element relative to the top left of the page
*/
offset: function (el) {
return $(el).offset();
},
/**
* Add an event listener
* @param {Object} el A HTML element or custom object
* @param {String} event The event type
* @param {Function} fn The event handler
*/
addEvent: function (el, event, fn) {
$(el).bind(event, fn);
},
/**
* Remove event added with addEvent
* @param {Object} el The object
* @param {String} eventType The event type. Leave blank to remove all events.
* @param {Function} handler The function to remove
*/
removeEvent: function (el, eventType, handler) {
// workaround for jQuery issue with unbinding custom events:
// http://forum.jQuery.com/topic/javascript-error-when-unbinding-a-custom-event-using-jQuery-1-4-2
var func = doc.removeEventListener ? 'removeEventListener' : 'detachEvent';
if (doc[func] && el && !el[func]) {
el[func] = function () {};
}
$(el).unbind(eventType, handler);
},
/**
* Fire an event on a custom object
* @param {Object} el
* @param {String} type
* @param {Object} eventArguments
* @param {Function} defaultFunction
*/
fireEvent: function (el, type, eventArguments, defaultFunction) {
var event = $.Event(type),
detachedType = 'detached' + type,
defaultPrevented;
// Remove warnings in Chrome when accessing returnValue (#2790), layerX and layerY. Although Highcharts
// never uses these properties, Chrome includes them in the default click event and
// raises the warning when they are copied over in the extend statement below.
//
// To avoid problems in IE (see #1010) where we cannot delete the properties and avoid
// testing if they are there (warning in chrome) the only option is to test if running IE.
if (!isIE && eventArguments) {
delete eventArguments.layerX;
delete eventArguments.layerY;
delete eventArguments.returnValue;
}
extend(event, eventArguments);
// Prevent jQuery from triggering the object method that is named the
// same as the event. For example, if the event is 'select', jQuery
// attempts calling el.select and it goes into a loop.
if (el[type]) {
el[detachedType] = el[type];
el[type] = null;
}
// Wrap preventDefault and stopPropagation in try/catch blocks in
// order to prevent JS errors when cancelling events on non-DOM
// objects. #615.
/*jslint unparam: true*/
$.each(['preventDefault', 'stopPropagation'], function (i, fn) {
var base = event[fn];
event[fn] = function () {
try {
base.call(event);
} catch (e) {
if (fn === 'preventDefault') {
defaultPrevented = true;
}
}
};
});
/*jslint unparam: false*/
// trigger it
$(el).trigger(event);
// attach the method
if (el[detachedType]) {
el[type] = el[detachedType];
el[detachedType] = null;
}
if (defaultFunction && !event.isDefaultPrevented() && !defaultPrevented) {
defaultFunction(event);
}
},
/**
* Extension method needed for MooTools
*/
washMouseEvent: function (e) {
var ret = e.originalEvent || e;
// computed by jQuery, needed by IE8
if (ret.pageX === UNDEFINED) { // #1236
ret.pageX = e.pageX;
ret.pageY = e.pageY;
}
return ret;
},
/**
* Animate a HTML element or SVG element wrapper
* @param {Object} el
* @param {Object} params
* @param {Object} options jQuery-like animation options: duration, easing, callback
*/
animate: function (el, params, options) {
var $el = $(el);
if (!el.style) {
el.style = {}; // #1881
}
if (params.d) {
el.toD = params.d; // keep the array form for paths, used in $.fx.step.d
params.d = 1; // because in jQuery, animating to an array has a different meaning
}
$el.stop();
if (params.opacity !== UNDEFINED && el.attr) {
params.opacity += 'px'; // force jQuery to use same logic as width and height (#2161)
}
el.hasAnim = 1; // #3342
$el.animate(params, options);
},
/**
* Stop running animation
*/
stop: function (el) {
if (el.hasAnim) { // #3342, memory leak on calling $(el) from destroy
$(el).stop();
}
}
});
}(win.jQuery));
// check for a custom HighchartsAdapter defined prior to this file
var globalAdapter = win.HighchartsAdapter,
adapter = globalAdapter || {};
// Initialize the adapter
if (globalAdapter) {
globalAdapter.init.call(globalAdapter, pathAnim);
}
// Utility functions. If the HighchartsAdapter is not defined, adapter is an empty object
// and all the utility functions will be null. In that case they are populated by the
// default adapters below.
var adapterRun = adapter.adapterRun,
getScript = adapter.getScript,
inArray = adapter.inArray,
each = Highcharts.each = adapter.each,
grep = adapter.grep,
offset = adapter.offset,
map = adapter.map,
addEvent = adapter.addEvent,
removeEvent = adapter.removeEvent,
fireEvent = adapter.fireEvent,
washMouseEvent = adapter.washMouseEvent,
animate = adapter.animate,
stop = adapter.stop;
/* ****************************************************************************
* Handle the options *
*****************************************************************************/
defaultOptions = {
colors: ['#7cb5ec', '#434348', '#90ed7d', '#f7a35c',
'#8085e9', '#f15c80', '#e4d354', '#2b908f', '#f45b5b', '#91e8e1'],
symbols: ['circle', 'diamond', 'square', 'triangle', 'triangle-down'],
lang: {
loading: 'Loading...',
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July',
'August', 'September', 'October', 'November', 'December'],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
weekdays: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
decimalPoint: '.',
numericSymbols: ['k', 'M', 'G', 'T', 'P', 'E'], // SI prefixes used in axis labels
resetZoom: 'Reset zoom',
resetZoomTitle: 'Reset zoom level 1:1',
thousandsSep: ' '
},
global: {
useUTC: true,
//timezoneOffset: 0,
canvasToolsURL: 'http://code.highcharts.com/maps/1.1.0/modules/canvas-tools.js',
VMLRadialGradientURL: 'http://code.highcharts.com/maps/1.1.0/gfx/vml-radial-gradient.png'
},
chart: {
//animation: true,
//alignTicks: false,
//reflow: true,
//className: null,
//events: { load, selection },
//margin: [null],
//marginTop: null,
//marginRight: null,
//marginBottom: null,
//marginLeft: null,
borderColor: '#4572A7',
//borderWidth: 0,
borderRadius: 0,
defaultSeriesType: 'line',
ignoreHiddenSeries: true,
//inverted: false,
//shadow: false,
spacing: [10, 10, 15, 10],
//spacingTop: 10,
//spacingRight: 10,
//spacingBottom: 15,
//spacingLeft: 10,
//style: {
// fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif', // default font
// fontSize: '12px'
//},
backgroundColor: '#FFFFFF',
//plotBackgroundColor: null,
plotBorderColor: '#C0C0C0',
//plotBorderWidth: 0,
//plotShadow: false,
//zoomType: ''
resetZoomButton: {
theme: {
zIndex: 20
},
position: {
align: 'right',
x: -10,
//verticalAlign: 'top',
y: 10
}
// relativeTo: 'plot'
}
},
title: {
text: 'Chart title',
align: 'center',
// floating: false,
margin: 15,
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#333333',
fontSize: '18px'
}
},
subtitle: {
text: '',
align: 'center',
// floating: false
// x: 0,
// verticalAlign: 'top',
// y: null,
style: {
color: '#555555'
}
},
plotOptions: {
line: { // base series options
allowPointSelect: false,
showCheckbox: false,
animation: {
duration: 1000
},
//connectNulls: false,
//cursor: 'default',
//clip: true,
//dashStyle: null,
//enableMouseTracking: true,
events: {},
//legendIndex: 0,
//linecap: 'round',
lineWidth: 2,
//shadow: false,
// stacking: null,
marker: {
//enabled: true,
//symbol: null,
lineWidth: 0,
radius: 4,
lineColor: '#FFFFFF',
//fillColor: null,
states: { // states for a single point
hover: {
enabled: true,
lineWidthPlus: 1,
radiusPlus: 2
},
select: {
fillColor: '#FFFFFF',
lineColor: '#000000',
lineWidth: 2
}
}
},
point: {
events: {}
},
dataLabels: {
align: 'center',
// defer: true,
// enabled: false,
formatter: function () {
return this.y === null ? '' : Highcharts.numberFormat(this.y, -1);
},
style: {
color: 'contrast',
fontSize: '11px',
fontWeight: 'bold',
textShadow: '0 0 6px contrast, 0 0 3px contrast'
},
verticalAlign: 'bottom', // above singular point
x: 0,
y: 0,
// backgroundColor: undefined,
// borderColor: undefined,
// borderRadius: undefined,
// borderWidth: undefined,
padding: 5
// shadow: false
},
cropThreshold: 300, // draw points outside the plot area when the number of points is less than this
pointRange: 0,
//pointStart: 0,
//pointInterval: 1,
//showInLegend: null, // auto: true for standalone series, false for linked series
states: { // states for the entire series
hover: {
//enabled: false,
lineWidthPlus: 1,
marker: {
// lineWidth: base + 1,
// radius: base + 1
},
halo: {
size: 10,
opacity: 0.25
}
},
select: {
marker: {}
}
},
stickyTracking: true,
//tooltip: {
//pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b>'
//valueDecimals: null,
//xDateFormat: '%A, %b %e, %Y',
//valuePrefix: '',
//ySuffix: ''
//}
turboThreshold: 1000
// zIndex: null
}
},
labels: {
//items: [],
style: {
//font: defaultFont,
position: ABSOLUTE,
color: '#3E576F'
}
},
legend: {
enabled: true,
align: 'center',
//floating: false,
layout: 'horizontal',
labelFormatter: function () {
return this.name;
},
//borderWidth: 0,
borderColor: '#909090',
borderRadius: 0,
navigation: {
// animation: true,
activeColor: '#274b6d',
// arrowSize: 12
inactiveColor: '#CCC'
// style: {} // text styles
},
// margin: 20,
// reversed: false,
shadow: false,
// backgroundColor: null,
/*style: {
padding: '5px'
},*/
itemStyle: {
color: '#333333',
fontSize: '12px',
fontWeight: 'bold'
},
itemHoverStyle: {
//cursor: 'pointer', removed as of #601
color: '#000'
},
itemHiddenStyle: {
color: '#CCC'
},
itemCheckboxStyle: {
position: ABSOLUTE,
width: '13px', // for IE precision
height: '13px'
},
// itemWidth: undefined,
// symbolRadius: 0,
// symbolWidth: 16,
symbolPadding: 5,
verticalAlign: 'bottom',
// width: undefined,
x: 0,
y: 0,
title: {
//text: null,
style: {
fontWeight: 'bold'
}
}
},
loading: {
// hideDuration: 100,
labelStyle: {
fontWeight: 'bold',
position: RELATIVE,
top: '45%'
},
// showDuration: 0,
style: {
position: ABSOLUTE,
backgroundColor: 'white',
opacity: 0.5,
textAlign: 'center'
}
},
tooltip: {
enabled: true,
animation: hasSVG,
//crosshairs: null,
backgroundColor: 'rgba(249, 249, 249, .85)',
borderWidth: 1,
borderRadius: 3,
dateTimeLabelFormats: {
millisecond: '%A, %b %e, %H:%M:%S.%L',
second: '%A, %b %e, %H:%M:%S',
minute: '%A, %b %e, %H:%M',
hour: '%A, %b %e, %H:%M',
day: '%A, %b %e, %Y',
week: 'Week from %A, %b %e, %Y',
month: '%B %Y',
year: '%Y'
},
footerFormat: '',
//formatter: defaultFormatter,
headerFormat: '<span style="font-size: 10px">{point.key}</span><br/>',
pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}</b><br/>',
shadow: true,
//shape: 'callout',
//shared: false,
snap: isTouchDevice ? 25 : 10,
style: {
color: '#333333',
cursor: 'default',
fontSize: '12px',
padding: '8px',
whiteSpace: 'nowrap'
}
//xDateFormat: '%A, %b %e, %Y',
//valueDecimals: null,
//valuePrefix: '',
//valueSuffix: ''
},
credits: {
enabled: true,
text: 'Highcharts.com',
href: 'http://www.highcharts.com',
position: {
align: 'right',
x: -10,
verticalAlign: 'bottom',
y: -5
},
style: {
cursor: 'pointer',
color: '#909090',
fontSize: '9px'
}
}
};
// Series defaults
var defaultPlotOptions = defaultOptions.plotOptions,
defaultSeriesOptions = defaultPlotOptions.line;
// set the default time methods
setTimeMethods();
/**
* Set the time methods globally based on the useUTC option. Time method can be either
* local time or UTC (default).
*/
function setTimeMethods() {
var globalOptions = defaultOptions.global,
useUTC = globalOptions.useUTC,
GET = useUTC ? 'getUTC' : 'get',
SET = useUTC ? 'setUTC' : 'set';
Date = globalOptions.Date || window.Date;
timezoneOffset = useUTC && globalOptions.timezoneOffset;
getTimezoneOffset = useUTC && globalOptions.getTimezoneOffset;
makeTime = function (year, month, date, hours, minutes, seconds) {
var d;
if (useUTC) {
d = Date.UTC.apply(0, arguments);
d += getTZOffset(d);
} else {
d = new Date(
year,
month,
pick(date, 1),
pick(hours, 0),
pick(minutes, 0),
pick(seconds, 0)
).getTime();
}
return d;
};
getMinutes = GET + 'Minutes';
getHours = GET + 'Hours';
getDay = GET + 'Day';
getDate = GET + 'Date';
getMonth = GET + 'Month';
getFullYear = GET + 'FullYear';
setMinutes = SET + 'Minutes';
setHours = SET + 'Hours';
setDate = SET + 'Date';
setMonth = SET + 'Month';
setFullYear = SET + 'FullYear';
}
/**
* Merge the default options with custom options and return the new options structure
* @param {Object} options The new custom options
*/
function setOptions(options) {
// Copy in the default options
defaultOptions = merge(true, defaultOptions, options);
// Apply UTC
setTimeMethods();
return defaultOptions;
}
/**
* Get the updated default options. Until 3.0.7, merely exposing defaultOptions for outside modules
* wasn't enough because the setOptions method created a new object.
*/
function getOptions() {
return defaultOptions;
}
/**
* Handle color operations. The object methods are chainable.
* @param {String} input The input color in either rbga or hex format
*/
var rgbaRegEx = /rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/,
hexRegEx = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/,
rgbRegEx = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/;
var Color = function (input) {
// declare variables
var rgba = [], result, stops;
/**
* Parse the input color to rgba array
* @param {String} input
*/
function init(input) {
// Gradients
if (input && input.stops) {
stops = map(input.stops, function (stop) {
return Color(stop[1]);
});
// Solid colors
} else {
// rgba
result = rgbaRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), parseFloat(result[4], 10)];
} else {
// hex
result = hexRegEx.exec(input);
if (result) {
rgba = [pInt(result[1], 16), pInt(result[2], 16), pInt(result[3], 16), 1];
} else {
// rgb
result = rgbRegEx.exec(input);
if (result) {
rgba = [pInt(result[1]), pInt(result[2]), pInt(result[3]), 1];
}
}
}
}
}
/**
* Return the color a specified format
* @param {String} format
*/
function get(format) {
var ret;
if (stops) {
ret = merge(input);
ret.stops = [].concat(ret.stops);
each(stops, function (stop, i) {
ret.stops[i] = [ret.stops[i][0], stop.get(format)];
});
// it's NaN if gradient colors on a column chart
} else if (rgba && !isNaN(rgba[0])) {
if (format === 'rgb') {
ret = 'rgb(' + rgba[0] + ',' + rgba[1] + ',' + rgba[2] + ')';
} else if (format === 'a') {
ret = rgba[3];
} else {
ret = 'rgba(' + rgba.join(',') + ')';
}
} else {
ret = input;
}
return ret;
}
/**
* Brighten the color
* @param {Number} alpha
*/
function brighten(alpha) {
if (stops) {
each(stops, function (stop) {
stop.brighten(alpha);
});
} else if (isNumber(alpha) && alpha !== 0) {
var i;
for (i = 0; i < 3; i++) {
rgba[i] += pInt(alpha * 255);
if (rgba[i] < 0) {
rgba[i] = 0;
}
if (rgba[i] > 255) {
rgba[i] = 255;
}
}
}
return this;
}
/**
* Set the color's opacity to a given alpha value
* @param {Number} alpha
*/
function setOpacity(alpha) {
rgba[3] = alpha;
return this;
}
// initialize: parse the input
init(input);
// public methods
return {
get: get,
brighten: brighten,
rgba: rgba,
setOpacity: setOpacity
};
};
/**
* A wrapper object for SVG elements
*/
function SVGElement() {}
SVGElement.prototype = {
// Default base for animation
opacity: 1,
// For labels, these CSS properties are applied to the <text> node directly
textProps: ['fontSize', 'fontWeight', 'fontFamily', 'color',
'lineHeight', 'width', 'textDecoration', 'textShadow'],
/**
* Initialize the SVG renderer
* @param {Object} renderer
* @param {String} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this;
wrapper.element = nodeName === 'span' ?
createElement(nodeName) :
doc.createElementNS(SVG_NS, nodeName);
wrapper.renderer = renderer;
},
/**
* Animate a given attribute
* @param {Object} params
* @param {Number} options The same options as in jQuery animation
* @param {Function} complete Function to perform at the end of animation
*/
animate: function (params, options, complete) {
var animOptions = pick(options, globalAnimation, true);
stop(this); // stop regardless of animation actually running, or reverting to .attr (#607)
if (animOptions) {
animOptions = merge(animOptions, {}); //#2625
if (complete) { // allows using a callback with the global animation without overwriting it
animOptions.complete = complete;
}
animate(this, params, animOptions);
} else {
this.attr(params);
if (complete) {
complete();
}
}
return this;
},
/**
* Build an SVG gradient out of a common JavaScript configuration object
*/
colorGradient: function (color, prop, elem) {
var renderer = this.renderer,
colorObject,
gradName,
gradAttr,
gradients,
gradientObject,
stops,
stopColor,
stopOpacity,
radialReference,
n,
id,
key = [];
// Apply linear or radial gradients
if (color.linearGradient) {
gradName = 'linearGradient';
} else if (color.radialGradient) {
gradName = 'radialGradient';
}
if (gradName) {
gradAttr = color[gradName];
gradients = renderer.gradients;
stops = color.stops;
radialReference = elem.radialReference;
// Keep < 2.2 kompatibility
if (isArray(gradAttr)) {
color[gradName] = gradAttr = {
x1: gradAttr[0],
y1: gradAttr[1],
x2: gradAttr[2],
y2: gradAttr[3],
gradientUnits: 'userSpaceOnUse'
};
}
// Correct the radial gradient for the radial reference system
if (gradName === 'radialGradient' && radialReference && !defined(gradAttr.gradientUnits)) {
gradAttr = merge(gradAttr, {
cx: (radialReference[0] - radialReference[2] / 2) + gradAttr.cx * radialReference[2],
cy: (radialReference[1] - radialReference[2] / 2) + gradAttr.cy * radialReference[2],
r: gradAttr.r * radialReference[2],
gradientUnits: 'userSpaceOnUse'
});
}
// Build the unique key to detect whether we need to create a new element (#1282)
for (n in gradAttr) {
if (n !== 'id') {
key.push(n, gradAttr[n]);
}
}
for (n in stops) {
key.push(stops[n]);
}
key = key.join(',');
// Check if a gradient object with the same config object is created within this renderer
if (gradients[key]) {
id = gradients[key].attr('id');
} else {
// Set the id and create the element
gradAttr.id = id = PREFIX + idCounter++;
gradients[key] = gradientObject = renderer.createElement(gradName)
.attr(gradAttr)
.add(renderer.defs);
// The gradient needs to keep a list of stops to be able to destroy them
gradientObject.stops = [];
each(stops, function (stop) {
var stopObject;
if (stop[1].indexOf('rgba') === 0) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
stopObject = renderer.createElement('stop').attr({
offset: stop[0],
'stop-color': stopColor,
'stop-opacity': stopOpacity
}).add(gradientObject);
// Add the stop element to the gradient
gradientObject.stops.push(stopObject);
});
}
// Set the reference to the gradient object
elem.setAttribute(prop, 'url(' + renderer.url + '#' + id + ')');
}
},
/**
* Apply a polyfill to the text-stroke CSS property, by copying the text element
* and apply strokes to the copy.
*
* docs: update default, document the polyfill and the limitations on hex colors and pixel values, document contrast pseudo-color
* TODO:
* - update defaults
*/
applyTextShadow: function (textShadow) {
var elem = this.element,
tspans,
hasContrast = textShadow.indexOf('contrast') !== -1,
// Safari suffers from the double display bug (#3649)
isSafari = userAgent.indexOf('Safari') > 0 && userAgent.indexOf('Chrome') === -1,
// IE10 and IE11 report textShadow in elem.style even though it doesn't work. Check
// this again with new IE release.
supports = elem.style.textShadow !== UNDEFINED && !isIE && !isSafari;
// When the text shadow is set to contrast, use dark stroke for light text and vice versa
if (hasContrast) {
textShadow = textShadow.replace(/contrast/g, this.renderer.getContrast(elem.style.fill));
}
/* Selective side-by-side testing in supported browser (http://jsfiddle.net/highcharts/73L1ptrh/)
if (elem.textContent.indexOf('2.') === 0) {
elem.style['text-shadow'] = 'none';
supports = false;
}
// */
// No reason to polyfill, we've got native support
if (supports) {
if (hasContrast) { // Apply the altered style
css(elem, {
textShadow: textShadow
});
}
} else {
// In order to get the right y position of the clones,
// copy over the y setter
this.ySetter = this.xSetter;
tspans = [].slice.call(elem.getElementsByTagName('tspan'));
each(textShadow.split(/\s?,\s?/g), function (textShadow) {
var firstChild = elem.firstChild,
color,
strokeWidth;
textShadow = textShadow.split(' ');
color = textShadow[textShadow.length - 1];
// Approximately tune the settings to the text-shadow behaviour
strokeWidth = textShadow[textShadow.length - 2];
if (strokeWidth) {
each(tspans, function (tspan, y) {
var clone;
// Let the first line start at the correct X position
if (y === 0) {
tspan.setAttribute('x', elem.getAttribute('x'));
y = elem.getAttribute('y');
tspan.setAttribute('y', y || 0);
if (y === null) {
elem.setAttribute('y', 0);
}
}
// Create the clone and apply shadow properties
clone = tspan.cloneNode(1);
attr(clone, {
'stroke': color,
'stroke-opacity': 1 / mathMax(pInt(strokeWidth), 3),
'stroke-width': strokeWidth,
'stroke-linejoin': 'round'
});
elem.insertBefore(clone, firstChild);
});
}
});
}
},
/**
* Set or get a given attribute
* @param {Object|String} hash
* @param {Mixed|Undefined} val
*/
attr: function (hash, val) {
var key,
value,
element = this.element,
hasSetSymbolSize,
ret = this,
skipAttr;
// single key-value pair
if (typeof hash === 'string' && val !== UNDEFINED) {
key = hash;
hash = {};
hash[key] = val;
}
// used as a getter: first argument is a string, second is undefined
if (typeof hash === 'string') {
ret = (this[hash + 'Getter'] || this._defaultGetter).call(this, hash, element);
// setter
} else {
for (key in hash) {
value = hash[key];
skipAttr = false;
if (this.symbolName && /^(x|y|width|height|r|start|end|innerR|anchorX|anchorY)/.test(key)) {
if (!hasSetSymbolSize) {
this.symbolAttr(hash);
hasSetSymbolSize = true;
}
skipAttr = true;
}
if (this.rotation && (key === 'x' || key === 'y')) {
this.doTransform = true;
}
if (!skipAttr) {
(this[key + 'Setter'] || this._defaultSetter).call(this, value, key, element);
}
// Let the shadow follow the main element
if (this.shadows && /^(width|height|visibility|x|y|d|transform|cx|cy|r)$/.test(key)) {
this.updateShadows(key, value);
}
}
// Update transform. Do this outside the loop to prevent redundant updating for batch setting
// of attributes.
if (this.doTransform) {
this.updateTransform();
this.doTransform = false;
}
}
return ret;
},
updateShadows: function (key, value) {
var shadows = this.shadows,
i = shadows.length;
while (i--) {
shadows[i].setAttribute(
key,
key === 'height' ?
mathMax(value - (shadows[i].cutHeight || 0), 0) :
key === 'd' ? this.d : value
);
}
},
/**
* Add a class name to an element
*/
addClass: function (className) {
var element = this.element,
currentClassName = attr(element, 'class') || '';
if (currentClassName.indexOf(className) === -1) {
attr(element, 'class', currentClassName + ' ' + className);
}
return this;
},
/* hasClass and removeClass are not (yet) needed
hasClass: function (className) {
return attr(this.element, 'class').indexOf(className) !== -1;
},
removeClass: function (className) {
attr(this.element, 'class', attr(this.element, 'class').replace(className, ''));
return this;
},
*/
/**
* If one of the symbol size affecting parameters are changed,
* check all the others only once for each call to an element's
* .attr() method
* @param {Object} hash
*/
symbolAttr: function (hash) {
var wrapper = this;
each(['x', 'y', 'r', 'start', 'end', 'width', 'height', 'innerR', 'anchorX', 'anchorY'], function (key) {
wrapper[key] = pick(hash[key], wrapper[key]);
});
wrapper.attr({
d: wrapper.renderer.symbols[wrapper.symbolName](
wrapper.x,
wrapper.y,
wrapper.width,
wrapper.height,
wrapper
)
});
},
/**
* Apply a clipping path to this object
* @param {String} id
*/
clip: function (clipRect) {
return this.attr('clip-path', clipRect ? 'url(' + this.renderer.url + '#' + clipRect.id + ')' : NONE);
},
/**
* Calculate the coordinates needed for drawing a rectangle crisply and return the
* calculated attributes
* @param {Number} strokeWidth
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
crisp: function (rect) {
var wrapper = this,
key,
attribs = {},
normalizer,
strokeWidth = rect.strokeWidth || wrapper.strokeWidth || 0;
normalizer = mathRound(strokeWidth) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors
// normalize for crisp edges
rect.x = mathFloor(rect.x || wrapper.x || 0) + normalizer;
rect.y = mathFloor(rect.y || wrapper.y || 0) + normalizer;
rect.width = mathFloor((rect.width || wrapper.width || 0) - 2 * normalizer);
rect.height = mathFloor((rect.height || wrapper.height || 0) - 2 * normalizer);
rect.strokeWidth = strokeWidth;
for (key in rect) {
if (wrapper[key] !== rect[key]) { // only set attribute if changed
wrapper[key] = attribs[key] = rect[key];
}
}
return attribs;
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: function (styles) {
var elemWrapper = this,
oldStyles = elemWrapper.styles,
newStyles = {},
elem = elemWrapper.element,
textWidth,
n,
serializedCss = '',
hyphenate,
hasNew = !oldStyles;
// convert legacy
if (styles && styles.color) {
styles.fill = styles.color;
}
// Filter out existing styles to increase performance (#2640)
if (oldStyles) {
for (n in styles) {
if (styles[n] !== oldStyles[n]) {
newStyles[n] = styles[n];
hasNew = true;
}
}
}
if (hasNew) {
textWidth = elemWrapper.textWidth =
(styles && styles.width && elem.nodeName.toLowerCase() === 'text' && pInt(styles.width)) ||
elemWrapper.textWidth; // #3501
// Merge the new styles with the old ones
if (oldStyles) {
styles = extend(
oldStyles,
newStyles
);
}
// store object
elemWrapper.styles = styles;
if (textWidth && (useCanVG || (!hasSVG && elemWrapper.renderer.forExport))) {
delete styles.width;
}
// serialize and set style attribute
if (isIE && !hasSVG) {
css(elemWrapper.element, styles);
} else {
/*jslint unparam: true*/
hyphenate = function (a, b) { return '-' + b.toLowerCase(); };
/*jslint unparam: false*/
for (n in styles) {
serializedCss += n.replace(/([A-Z])/g, hyphenate) + ':' + styles[n] + ';';
}
attr(elem, 'style', serializedCss); // #1881
}
// re-build text
if (textWidth && elemWrapper.added) {
elemWrapper.renderer.buildText(elemWrapper);
}
}
return elemWrapper;
},
/**
* Add an event listener
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
var svgElement = this,
element = svgElement.element;
// touch
if (hasTouch && eventType === 'click') {
element.ontouchstart = function (e) {
svgElement.touchEventFired = Date.now();
e.preventDefault();
handler.call(element, e);
};
element.onclick = function (e) {
if (userAgent.indexOf('Android') === -1 || Date.now() - (svgElement.touchEventFired || 0) > 1100) { // #2269
handler.call(element, e);
}
};
} else {
// simplest possible event model for internal use
element['on' + eventType] = handler;
}
return this;
},
/**
* Set the coordinates needed to draw a consistent radial gradient across
* pie slices regardless of positioning inside the chart. The format is
* [centerX, centerY, diameter] in pixels.
*/
setRadialReference: function (coordinates) {
this.element.radialReference = coordinates;
return this;
},
/**
* Move an object and its children by x and y values
* @param {Number} x
* @param {Number} y
*/
translate: function (x, y) {
return this.attr({
translateX: x,
translateY: y
});
},
/**
* Invert a group, rotate and flip
*/
invert: function () {
var wrapper = this;
wrapper.inverted = true;
wrapper.updateTransform();
return wrapper;
},
/**
* Private method to update the transform attribute based on internal
* properties
*/
updateTransform: function () {
var wrapper = this,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
scaleX = wrapper.scaleX,
scaleY = wrapper.scaleY,
inverted = wrapper.inverted,
rotation = wrapper.rotation,
element = wrapper.element,
transform;
// flipping affects translate as adjustment for flipping around the group's axis
if (inverted) {
translateX += wrapper.attr('width');
translateY += wrapper.attr('height');
}
// Apply translate. Nearly all transformed elements have translation, so instead
// of checking for translate = 0, do it always (#1767, #1846).
transform = ['translate(' + translateX + ',' + translateY + ')'];
// apply rotation
if (inverted) {
transform.push('rotate(90) scale(-1,1)');
} else if (rotation) { // text rotation
transform.push('rotate(' + rotation + ' ' + (element.getAttribute('x') || 0) + ' ' + (element.getAttribute('y') || 0) + ')');
// Delete bBox memo when the rotation changes
//delete wrapper.bBox;
}
// apply scale
if (defined(scaleX) || defined(scaleY)) {
transform.push('scale(' + pick(scaleX, 1) + ' ' + pick(scaleY, 1) + ')');
}
if (transform.length) {
element.setAttribute('transform', transform.join(' '));
}
},
/**
* Bring the element to the front
*/
toFront: function () {
var element = this.element;
element.parentNode.appendChild(element);
return this;
},
/**
* Break down alignment options like align, verticalAlign, x and y
* to x and y relative to the chart.
*
* @param {Object} alignOptions
* @param {Boolean} alignByTranslate
* @param {String[Object} box The box to align to, needs a width and height. When the
* box is a string, it refers to an object in the Renderer. For example, when
* box is 'spacingBox', it refers to Renderer.spacingBox which holds width, height
* x and y properties.
*
*/
align: function (alignOptions, alignByTranslate, box) {
var align,
vAlign,
x,
y,
attribs = {},
alignTo,
renderer = this.renderer,
alignedObjects = renderer.alignedObjects;
// First call on instanciate
if (alignOptions) {
this.alignOptions = alignOptions;
this.alignByTranslate = alignByTranslate;
if (!box || isString(box)) { // boxes other than renderer handle this internally
this.alignTo = alignTo = box || 'renderer';
erase(alignedObjects, this); // prevent duplicates, like legendGroup after resize
alignedObjects.push(this);
box = null; // reassign it below
}
// When called on resize, no arguments are supplied
} else {
alignOptions = this.alignOptions;
alignByTranslate = this.alignByTranslate;
alignTo = this.alignTo;
}
box = pick(box, renderer[alignTo], renderer);
// Assign variables
align = alignOptions.align;
vAlign = alignOptions.verticalAlign;
x = (box.x || 0) + (alignOptions.x || 0); // default: left align
y = (box.y || 0) + (alignOptions.y || 0); // default: top align
// Align
if (align === 'right' || align === 'center') {
x += (box.width - (alignOptions.width || 0)) /
{ right: 1, center: 2 }[align];
}
attribs[alignByTranslate ? 'translateX' : 'x'] = mathRound(x);
// Vertical align
if (vAlign === 'bottom' || vAlign === 'middle') {
y += (box.height - (alignOptions.height || 0)) /
({ bottom: 1, middle: 2 }[vAlign] || 1);
}
attribs[alignByTranslate ? 'translateY' : 'y'] = mathRound(y);
// Animate only if already placed
this[this.placed ? 'animate' : 'attr'](attribs);
this.placed = true;
this.alignAttr = attribs;
return this;
},
/**
* Get the bounding box (width, height, x and y) for the element
*/
getBBox: function (reload) {
var wrapper = this,
bBox,// = wrapper.bBox,
renderer = wrapper.renderer,
width,
height,
rotation = wrapper.rotation,
element = wrapper.element,
styles = wrapper.styles,
rad = rotation * deg2rad,
textStr = wrapper.textStr,
cacheKey;
if (textStr !== UNDEFINED) {
// Properties that affect bounding box
cacheKey = ['', rotation || 0, styles && styles.fontSize, element.style.width].join(',');
// Since numbers are monospaced, and numerical labels appear a lot in a chart,
// we assume that a label of n characters has the same bounding box as others
// of the same length.
if (textStr === '' || numRegex.test(textStr)) {
cacheKey = 'num:' + textStr.toString().length + cacheKey;
// Caching all strings reduces rendering time by 4-5%.
} else {
cacheKey = textStr + cacheKey;
}
}
if (cacheKey && !reload) {
bBox = renderer.cache[cacheKey];
}
// No cache found
if (!bBox) {
// SVG elements
if (element.namespaceURI === SVG_NS || renderer.forExport) {
try { // Fails in Firefox if the container has display: none.
bBox = element.getBBox ?
// SVG: use extend because IE9 is not allowed to change width and height in case
// of rotation (below)
extend({}, element.getBBox()) :
// Canvas renderer and legacy IE in export mode
{
width: element.offsetWidth,
height: element.offsetHeight
};
} catch (e) {}
// If the bBox is not set, the try-catch block above failed. The other condition
// is for Opera that returns a width of -Infinity on hidden elements.
if (!bBox || bBox.width < 0) {
bBox = { width: 0, height: 0 };
}
// VML Renderer or useHTML within SVG
} else {
bBox = wrapper.htmlGetBBox();
}
// True SVG elements as well as HTML elements in modern browsers using the .useHTML option
// need to compensated for rotation
if (renderer.isSVG) {
width = bBox.width;
height = bBox.height;
// Workaround for wrong bounding box in IE9 and IE10 (#1101, #1505, #1669, #2568)
if (isIE && styles && styles.fontSize === '11px' && height.toPrecision(3) === '16.9') {
bBox.height = height = 14;
}
// Adjust for rotated text
if (rotation) {
bBox.width = mathAbs(height * mathSin(rad)) + mathAbs(width * mathCos(rad));
bBox.height = mathAbs(height * mathCos(rad)) + mathAbs(width * mathSin(rad));
}
}
// Cache it
renderer.cache[cacheKey] = bBox;
}
return bBox;
},
/**
* Show the element
*/
show: function (inherit) {
// IE9-11 doesn't handle visibilty:inherit well, so we remove the attribute instead (#2881)
if (inherit && this.element.namespaceURI === SVG_NS) {
this.element.removeAttribute('visibility');
} else {
this.attr({ visibility: inherit ? 'inherit' : VISIBLE });
}
return this;
},
/**
* Hide the element
*/
hide: function () {
return this.attr({ visibility: HIDDEN });
},
fadeOut: function (duration) {
var elemWrapper = this;
elemWrapper.animate({
opacity: 0
}, {
duration: duration || 150,
complete: function () {
elemWrapper.attr({ y: -9999 }); // #3088, assuming we're only using this for tooltips
}
});
},
/**
* Add the element
* @param {Object|Undefined} parent Can be an element, an element wrapper or undefined
* to append the element to the renderer.box.
*/
add: function (parent) {
var renderer = this.renderer,
element = this.element,
inserted;
if (parent) {
this.parentGroup = parent;
}
// mark as inverted
this.parentInverted = parent && parent.inverted;
// build formatted text
if (this.textStr !== undefined) {
renderer.buildText(this);
}
// Mark as added
this.added = true;
// If we're adding to renderer root, or other elements in the group
// have a z index, we need to handle it
if (!parent || parent.handleZ || this.zIndex) {
inserted = this.zIndexSetter();
}
// If zIndex is not handled, append at the end
if (!inserted) {
(parent ? parent.element : renderer.box).appendChild(element);
}
// fire an event for internal hooks
if (this.onAdd) {
this.onAdd();
}
return this;
},
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
var parentNode = element.parentNode;
if (parentNode) {
parentNode.removeChild(element);
}
},
/**
* Destroy the element and element wrapper
*/
destroy: function () {
var wrapper = this,
element = wrapper.element || {},
shadows = wrapper.shadows,
parentToClean = wrapper.renderer.isSVG && element.nodeName === 'SPAN' && wrapper.parentGroup,
grandParent,
key,
i;
// remove events
element.onclick = element.onmouseout = element.onmouseover = element.onmousemove = element.point = null;
stop(wrapper); // stop running animations
if (wrapper.clipPath) {
wrapper.clipPath = wrapper.clipPath.destroy();
}
// Destroy stops in case this is a gradient object
if (wrapper.stops) {
for (i = 0; i < wrapper.stops.length; i++) {
wrapper.stops[i] = wrapper.stops[i].destroy();
}
wrapper.stops = null;
}
// remove element
wrapper.safeRemoveChild(element);
// destroy shadows
if (shadows) {
each(shadows, function (shadow) {
wrapper.safeRemoveChild(shadow);
});
}
// In case of useHTML, clean up empty containers emulating SVG groups (#1960, #2393, #2697).
while (parentToClean && parentToClean.div && parentToClean.div.childNodes.length === 0) {
grandParent = parentToClean.parentGroup;
wrapper.safeRemoveChild(parentToClean.div);
delete parentToClean.div;
parentToClean = grandParent;
}
// remove from alignObjects
if (wrapper.alignTo) {
erase(wrapper.renderer.alignedObjects, wrapper);
}
for (key in wrapper) {
delete wrapper[key];
}
return null;
},
/**
* Add a shadow to the element. Must be done after the element is added to the DOM
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
shadow,
element = this.element,
strokeWidth,
shadowWidth,
shadowElementOpacity,
// compensate for inverted plot area
transform;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
transform = this.parentInverted ?
'(-1,-1)' :
'(' + pick(shadowOptions.offsetX, 1) + ', ' + pick(shadowOptions.offsetY, 1) + ')';
for (i = 1; i <= shadowWidth; i++) {
shadow = element.cloneNode(0);
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
attr(shadow, {
'isShadow': 'true',
'stroke': shadowOptions.color || 'black',
'stroke-opacity': shadowElementOpacity * i,
'stroke-width': strokeWidth,
'transform': 'translate' + transform,
'fill': NONE
});
if (cutOff) {
attr(shadow, 'height', mathMax(attr(shadow, 'height') - strokeWidth, 0));
shadow.cutHeight = strokeWidth;
}
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
xGetter: function (key) {
if (this.element.nodeName === 'circle') {
key = { x: 'cx', y: 'cy' }[key] || key;
}
return this._defaultGetter(key);
},
/**
* Get the current value of an attribute or pseudo attribute, used mainly
* for animation.
*/
_defaultGetter: function (key) {
var ret = pick(this[key], this.element ? this.element.getAttribute(key) : null, 0);
if (/^[\-0-9\.]+$/.test(ret)) { // is numerical
ret = parseFloat(ret);
}
return ret;
},
dSetter: function (value, key, element) {
if (value && value.join) { // join path
value = value.join(' ');
}
if (/(NaN| {2}|^$)/.test(value)) {
value = 'M 0 0';
}
element.setAttribute(key, value);
this[key] = value;
},
dashstyleSetter: function (value) {
var i;
value = value && value.toLowerCase();
if (value) {
value = value
.replace('shortdashdotdot', '3,1,1,1,1,1,')
.replace('shortdashdot', '3,1,1,1')
.replace('shortdot', '1,1,')
.replace('shortdash', '3,1,')
.replace('longdash', '8,3,')
.replace(/dot/g, '1,3,')
.replace('dash', '4,3,')
.replace(/,$/, '')
.split(','); // ending comma
i = value.length;
while (i--) {
value[i] = pInt(value[i]) * this['stroke-width'];
}
value = value.join(',')
.replace('NaN', 'none'); // #3226
this.element.setAttribute('stroke-dasharray', value);
}
},
alignSetter: function (value) {
this.element.setAttribute('text-anchor', { left: 'start', center: 'middle', right: 'end' }[value]);
},
opacitySetter: function (value, key, element) {
this[key] = value;
element.setAttribute(key, value);
},
titleSetter: function (value) {
var titleNode = this.element.getElementsByTagName('title')[0];
if (!titleNode) {
titleNode = doc.createElementNS(SVG_NS, 'title');
this.element.appendChild(titleNode);
}
titleNode.textContent = pick(value, '').replace(/<[^>]*>/g, ''); // #3276
},
textSetter: function (value) {
if (value !== this.textStr) {
// Delete bBox memo when the text changes
delete this.bBox;
this.textStr = value;
if (this.added) {
this.renderer.buildText(this);
}
}
},
fillSetter: function (value, key, element) {
if (typeof value === 'string') {
element.setAttribute(key, value);
} else if (value) {
this.colorGradient(value, key, element);
}
},
zIndexSetter: function (value, key) {
var renderer = this.renderer,
parentGroup = this.parentGroup,
parentWrapper = parentGroup || renderer,
parentNode = parentWrapper.element || renderer.box,
childNodes,
otherElement,
otherZIndex,
element = this.element,
inserted,
i;
if (defined(value)) {
element.setAttribute(key, value); // So we can read it for other elements in the group
this[key] = +value;
}
// Insert according to this and other elements' zIndex. Before .add() is called,
// nothing is done. Then on add, or by later calls to zIndexSetter, the node
// is placed on the right place in the DOM.
if (this.added) {
value = this.zIndex;
if (value && parentGroup) {
parentGroup.handleZ = true;
}
childNodes = parentNode.childNodes;
for (i = 0; i < childNodes.length && !inserted; i++) {
otherElement = childNodes[i];
otherZIndex = attr(otherElement, 'zIndex');
if (otherElement !== element && (
// Insert before the first element with a higher zIndex
pInt(otherZIndex) > value ||
// If no zIndex given, insert before the first element with a zIndex
(!defined(value) && defined(otherZIndex))
)) {
parentNode.insertBefore(element, otherElement);
inserted = true;
}
}
if (!inserted) {
parentNode.appendChild(element);
}
}
return inserted;
},
_defaultSetter: function (value, key, element) {
element.setAttribute(key, value);
}
};
// Some shared setters and getters
SVGElement.prototype.yGetter = SVGElement.prototype.xGetter;
SVGElement.prototype.translateXSetter = SVGElement.prototype.translateYSetter =
SVGElement.prototype.rotationSetter = SVGElement.prototype.verticalAlignSetter =
SVGElement.prototype.scaleXSetter = SVGElement.prototype.scaleYSetter = function (value, key) {
this[key] = value;
this.doTransform = true;
};
// WebKit and Batik have problems with a stroke-width of zero, so in this case we remove the
// stroke attribute altogether. #1270, #1369, #3065, #3072.
SVGElement.prototype['stroke-widthSetter'] = SVGElement.prototype.strokeSetter = function (value, key, element) {
this[key] = value;
// Only apply the stroke attribute if the stroke width is defined and larger than 0
if (this.stroke && this['stroke-width']) {
this.strokeWidth = this['stroke-width'];
SVGElement.prototype.fillSetter.call(this, this.stroke, 'stroke', element); // use prototype as instance may be overridden
element.setAttribute('stroke-width', this['stroke-width']);
this.hasStroke = true;
} else if (key === 'stroke-width' && value === 0 && this.hasStroke) {
element.removeAttribute('stroke');
this.hasStroke = false;
}
};
/**
* The default SVG renderer
*/
var SVGRenderer = function () {
this.init.apply(this, arguments);
};
SVGRenderer.prototype = {
Element: SVGElement,
/**
* Initialize the SVGRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
* @param {Boolean} forExport
*/
init: function (container, width, height, style, forExport) {
var renderer = this,
loc = location,
boxWrapper,
element,
desc;
boxWrapper = renderer.createElement('svg')
.attr({
version: '1.1'
})
.css(this.getStyle(style));
element = boxWrapper.element;
container.appendChild(element);
// For browsers other than IE, add the namespace attribute (#1978)
if (container.innerHTML.indexOf('xmlns') === -1) {
attr(element, 'xmlns', SVG_NS);
}
// object properties
renderer.isSVG = true;
renderer.box = element;
renderer.boxWrapper = boxWrapper;
renderer.alignedObjects = [];
// Page url used for internal references. #24, #672, #1070
renderer.url = (isFirefox || isWebKit) && doc.getElementsByTagName('base').length ?
loc.href
.replace(/#.*?$/, '') // remove the hash
.replace(/([\('\)])/g, '\\$1') // escape parantheses and quotes
.replace(/ /g, '%20') : // replace spaces (needed for Safari only)
'';
// Add description
desc = this.createElement('desc').add();
desc.element.appendChild(doc.createTextNode('Created with ' + PRODUCT + ' ' + VERSION));
renderer.defs = this.createElement('defs').add();
renderer.forExport = forExport;
renderer.gradients = {}; // Object where gradient SvgElements are stored
renderer.cache = {}; // Cache for numerical bounding boxes
renderer.setSize(width, height, false);
// Issue 110 workaround:
// In Firefox, if a div is positioned by percentage, its pixel position may land
// between pixels. The container itself doesn't display this, but an SVG element
// inside this container will be drawn at subpixel precision. In order to draw
// sharp lines, this must be compensated for. This doesn't seem to work inside
// iframes though (like in jsFiddle).
var subPixelFix, rect;
if (isFirefox && container.getBoundingClientRect) {
renderer.subPixelFix = subPixelFix = function () {
css(container, { left: 0, top: 0 });
rect = container.getBoundingClientRect();
css(container, {
left: (mathCeil(rect.left) - rect.left) + PX,
top: (mathCeil(rect.top) - rect.top) + PX
});
};
// run the fix now
subPixelFix();
// run it on resize
addEvent(win, 'resize', subPixelFix);
}
},
getStyle: function (style) {
return (this.style = extend({
fontFamily: '"Lucida Grande", "Lucida Sans Unicode", Arial, Helvetica, sans-serif', // default font
fontSize: '12px'
}, style));
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none. #608.
*/
isHidden: function () {
return !this.boxWrapper.getBBox().width;
},
/**
* Destroys the renderer and its allocated members.
*/
destroy: function () {
var renderer = this,
rendererDefs = renderer.defs;
renderer.box = null;
renderer.boxWrapper = renderer.boxWrapper.destroy();
// Call destroy on all gradient elements
destroyObjectProperties(renderer.gradients || {});
renderer.gradients = null;
// Defs are null in VMLRenderer
// Otherwise, destroy them here.
if (rendererDefs) {
renderer.defs = rendererDefs.destroy();
}
// Remove sub pixel fix handler
// We need to check that there is a handler, otherwise all functions that are registered for event 'resize' are removed
// See issue #982
if (renderer.subPixelFix) {
removeEvent(win, 'resize', renderer.subPixelFix);
}
renderer.alignedObjects = null;
return null;
},
/**
* Create a wrapper for an SVG element
* @param {Object} nodeName
*/
createElement: function (nodeName) {
var wrapper = new this.Element();
wrapper.init(this, nodeName);
return wrapper;
},
/**
* Dummy function for use in canvas renderer
*/
draw: function () {},
/**
* Parse a simple HTML string into SVG tspans
*
* @param {Object} textNode The parent text SVG node
*/
buildText: function (wrapper) {
var textNode = wrapper.element,
renderer = this,
forExport = renderer.forExport,
textStr = pick(wrapper.textStr, '').toString(),
hasMarkup = textStr.indexOf('<') !== -1,
lines,
childNodes = textNode.childNodes,
styleRegex,
hrefRegex,
parentX = attr(textNode, 'x'),
textStyles = wrapper.styles,
width = wrapper.textWidth,
textLineHeight = textStyles && textStyles.lineHeight,
textShadow = textStyles && textStyles.textShadow,
ellipsis = textStyles && textStyles.textOverflow === 'ellipsis',
i = childNodes.length,
tempParent = width && !wrapper.added && this.box,
getLineHeight = function (tspan) {
return textLineHeight ?
pInt(textLineHeight) :
renderer.fontMetrics(
/(px|em)$/.test(tspan && tspan.style.fontSize) ?
tspan.style.fontSize :
((textStyles && textStyles.fontSize) || renderer.style.fontSize || 12),
tspan
).h;
},
unescapeAngleBrackets = function (inputStr) {
return inputStr.replace(/</g, '<').replace(/>/g, '>');
};
/// remove old text
while (i--) {
textNode.removeChild(childNodes[i]);
}
// Skip tspans, add text directly to text node. The forceTSpan is a hook
// used in text outline hack.
if (!hasMarkup && !textShadow && !ellipsis && textStr.indexOf(' ') === -1) {
textNode.appendChild(doc.createTextNode(unescapeAngleBrackets(textStr)));
return;
// Complex strings, add more logic
} else {
styleRegex = /<.*style="([^"]+)".*>/;
hrefRegex = /<.*href="(http[^"]+)".*>/;
if (tempParent) {
tempParent.appendChild(textNode); // attach it to the DOM to read offset width
}
if (hasMarkup) {
lines = textStr
.replace(/<(b|strong)>/g, '<span style="font-weight:bold">')
.replace(/<(i|em)>/g, '<span style="font-style:italic">')
.replace(/<a/g, '<span')
.replace(/<\/(b|strong|i|em|a)>/g, '</span>')
.split(/<br.*?>/g);
} else {
lines = [textStr];
}
// remove empty line at end
if (lines[lines.length - 1] === '') {
lines.pop();
}
// build the lines
each(lines, function (line, lineNo) {
var spans, spanNo = 0;
line = line.replace(/<span/g, '|||<span').replace(/<\/span>/g, '</span>|||');
spans = line.split('|||');
each(spans, function (span) {
if (span !== '' || spans.length === 1) {
var attributes = {},
tspan = doc.createElementNS(SVG_NS, 'tspan'),
spanStyle; // #390
if (styleRegex.test(span)) {
spanStyle = span.match(styleRegex)[1].replace(/(;| |^)color([ :])/, '$1fill$2');
attr(tspan, 'style', spanStyle);
}
if (hrefRegex.test(span) && !forExport) { // Not for export - #1529
attr(tspan, 'onclick', 'location.href=\"' + span.match(hrefRegex)[1] + '\"');
css(tspan, { cursor: 'pointer' });
}
span = unescapeAngleBrackets(span.replace(/<(.|\n)*?>/g, '') || ' ');
// Nested tags aren't supported, and cause crash in Safari (#1596)
if (span !== ' ') {
// add the text node
tspan.appendChild(doc.createTextNode(span));
if (!spanNo) { // first span in a line, align it to the left
if (lineNo && parentX !== null) {
attributes.x = parentX;
}
} else {
attributes.dx = 0; // #16
}
// add attributes
attr(tspan, attributes);
// Append it
textNode.appendChild(tspan);
// first span on subsequent line, add the line height
if (!spanNo && lineNo) {
// allow getting the right offset height in exporting in IE
if (!hasSVG && forExport) {
css(tspan, { display: 'block' });
}
// Set the line height based on the font size of either
// the text element or the tspan element
attr(
tspan,
'dy',
getLineHeight(tspan)
);
}
/*if (width) {
renderer.breakText(wrapper, width);
}*/
// Check width and apply soft breaks or ellipsis
if (width) {
var words = span.replace(/([^\^])-/g, '$1- ').split(' '), // #1273
hasWhiteSpace = spans.length > 1 || lineNo || (words.length > 1 && textStyles.whiteSpace !== 'nowrap'),
tooLong,
wasTooLong,
actualWidth,
rest = [],
dy = getLineHeight(tspan),
softLineNo = 1,
rotation = wrapper.rotation,
wordStr = span, // for ellipsis
cursor = wordStr.length, // binary search cursor
bBox;
while ((hasWhiteSpace || ellipsis) && (words.length || rest.length)) {
wrapper.rotation = 0; // discard rotation when computing box
bBox = wrapper.getBBox(true);
actualWidth = bBox.width;
// Old IE cannot measure the actualWidth for SVG elements (#2314)
if (!hasSVG && renderer.forExport) {
actualWidth = renderer.measureSpanWidth(tspan.firstChild.data, wrapper.styles);
}
tooLong = actualWidth > width;
// For ellipsis, do a binary search for the correct string length
if (wasTooLong === undefined) {
wasTooLong = tooLong; // First time
}
if (ellipsis && wasTooLong) {
cursor /= 2;
if (wordStr === '' || (!tooLong && cursor < 0.5)) {
words = []; // All ok, break out
} else {
if (tooLong) {
wasTooLong = true;
}
wordStr = span.substring(0, wordStr.length + (tooLong ? -1 : 1) * mathCeil(cursor));
words = [wordStr + '\u2026'];
tspan.removeChild(tspan.firstChild);
}
// Looping down, this is the first word sequence that is not too long,
// so we can move on to build the next line.
} else if (!tooLong || words.length === 1) {
words = rest;
rest = [];
if (words.length) {
softLineNo++;
tspan = doc.createElementNS(SVG_NS, 'tspan');
attr(tspan, {
dy: dy,
x: parentX
});
if (spanStyle) { // #390
attr(tspan, 'style', spanStyle);
}
textNode.appendChild(tspan);
}
if (actualWidth > width) { // a single word is pressing it out
width = actualWidth;
}
} else { // append to existing line tspan
tspan.removeChild(tspan.firstChild);
rest.unshift(words.pop());
}
if (words.length) {
tspan.appendChild(doc.createTextNode(words.join(' ').replace(/- /g, '-')));
}
}
if (wasTooLong) {
wrapper.attr('title', wrapper.textStr);
}
wrapper.rotation = rotation;
}
spanNo++;
}
}
});
});
if (tempParent) {
tempParent.removeChild(textNode); // attach it to the DOM to read offset width
}
// Apply the text shadow
if (textShadow && wrapper.applyTextShadow) {
wrapper.applyTextShadow(textShadow);
}
}
},
/*
breakText: function (wrapper, width) {
var bBox = wrapper.getBBox(),
node = wrapper.element,
textLength = node.textContent.length,
pos = mathRound(width * textLength / bBox.width), // try this position first, based on average character width
increment = 0,
finalPos;
if (bBox.width > width) {
while (finalPos === undefined) {
textLength = node.getSubStringLength(0, pos);
if (textLength <= width) {
if (increment === -1) {
finalPos = pos;
} else {
increment = 1;
}
} else {
if (increment === 1) {
finalPos = pos - 1;
} else {
increment = -1;
}
}
pos += increment;
}
}
console.log(finalPos, node.getSubStringLength(0, finalPos))
},
*/
/**
* Returns white for dark colors and black for bright colors
*/
getContrast: function (color) {
color = Color(color).rgba;
return color[0] + color[1] + color[2] > 384 ? '#000' : '#FFF';
},
/**
* Create a button with preset states
* @param {String} text
* @param {Number} x
* @param {Number} y
* @param {Function} callback
* @param {Object} normalState
* @param {Object} hoverState
* @param {Object} pressedState
*/
button: function (text, x, y, callback, normalState, hoverState, pressedState, disabledState, shape) {
var label = this.label(text, x, y, shape, null, null, null, null, 'button'),
curState = 0,
stateOptions,
stateStyle,
normalStyle,
hoverStyle,
pressedStyle,
disabledStyle,
verticalGradient = { x1: 0, y1: 0, x2: 0, y2: 1 };
// Normal state - prepare the attributes
normalState = merge({
'stroke-width': 1,
stroke: '#CCCCCC',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FEFEFE'],
[1, '#F6F6F6']
]
},
r: 2,
padding: 5,
style: {
color: 'black'
}
}, normalState);
normalStyle = normalState.style;
delete normalState.style;
// Hover state
hoverState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#FFF'],
[1, '#ACF']
]
}
}, hoverState);
hoverStyle = hoverState.style;
delete hoverState.style;
// Pressed state
pressedState = merge(normalState, {
stroke: '#68A',
fill: {
linearGradient: verticalGradient,
stops: [
[0, '#9BD'],
[1, '#CDF']
]
}
}, pressedState);
pressedStyle = pressedState.style;
delete pressedState.style;
// Disabled state
disabledState = merge(normalState, {
style: {
color: '#CCC'
}
}, disabledState);
disabledStyle = disabledState.style;
delete disabledState.style;
// Add the events. IE9 and IE10 need mouseover and mouseout to funciton (#667).
addEvent(label.element, isIE ? 'mouseover' : 'mouseenter', function () {
if (curState !== 3) {
label.attr(hoverState)
.css(hoverStyle);
}
});
addEvent(label.element, isIE ? 'mouseout' : 'mouseleave', function () {
if (curState !== 3) {
stateOptions = [normalState, hoverState, pressedState][curState];
stateStyle = [normalStyle, hoverStyle, pressedStyle][curState];
label.attr(stateOptions)
.css(stateStyle);
}
});
label.setState = function (state) {
label.state = curState = state;
if (!state) {
label.attr(normalState)
.css(normalStyle);
} else if (state === 2) {
label.attr(pressedState)
.css(pressedStyle);
} else if (state === 3) {
label.attr(disabledState)
.css(disabledStyle);
}
};
return label
.on('click', function () {
if (curState !== 3) {
callback.call(label);
}
})
.attr(normalState)
.css(extend({ cursor: 'default' }, normalStyle));
},
/**
* Make a straight line crisper by not spilling out to neighbour pixels
* @param {Array} points
* @param {Number} width
*/
crispLine: function (points, width) {
// points format: [M, 0, 0, L, 100, 0]
// normalize to a crisp line
if (points[1] === points[4]) {
// Substract due to #1129. Now bottom and left axis gridlines behave the same.
points[1] = points[4] = mathRound(points[1]) - (width % 2 / 2);
}
if (points[2] === points[5]) {
points[2] = points[5] = mathRound(points[2]) + (width % 2 / 2);
}
return points;
},
/**
* Draw a path
* @param {Array} path An SVG path in array form
*/
path: function (path) {
var attr = {
fill: NONE
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
return this.createElement('path').attr(attr);
},
/**
* Draw and return an SVG circle
* @param {Number} x The x position
* @param {Number} y The y position
* @param {Number} r The radius
*/
circle: function (x, y, r) {
var attr = isObject(x) ?
x :
{
x: x,
y: y,
r: r
},
wrapper = this.createElement('circle');
wrapper.xSetter = function (value) {
this.element.setAttribute('cx', value);
};
wrapper.ySetter = function (value) {
this.element.setAttribute('cy', value);
};
return wrapper.attr(attr);
},
/**
* Draw and return an arc
* @param {Number} x X position
* @param {Number} y Y position
* @param {Number} r Radius
* @param {Number} innerR Inner radius like used in donut charts
* @param {Number} start Starting angle
* @param {Number} end Ending angle
*/
arc: function (x, y, r, innerR, start, end) {
var arc;
if (isObject(x)) {
y = x.y;
r = x.r;
innerR = x.innerR;
start = x.start;
end = x.end;
x = x.x;
}
// Arcs are defined as symbols for the ability to set
// attributes in attr and animate
arc = this.symbol('arc', x || 0, y || 0, r || 0, r || 0, {
innerR: innerR || 0,
start: start || 0,
end: end || 0
});
arc.r = r; // #959
return arc;
},
/**
* Draw and return a rectangle
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Number} width
* @param {Number} height
* @param {Number} r Border corner radius
* @param {Number} strokeWidth A stroke width can be supplied to allow crisp drawing
*/
rect: function (x, y, width, height, r, strokeWidth) {
r = isObject(x) ? x.r : r;
var wrapper = this.createElement('rect'),
attribs = isObject(x) ? x : x === UNDEFINED ? {} : {
x: x,
y: y,
width: mathMax(width, 0),
height: mathMax(height, 0)
};
if (strokeWidth !== UNDEFINED) {
attribs.strokeWidth = strokeWidth;
attribs = wrapper.crisp(attribs);
}
if (r) {
attribs.r = r;
}
wrapper.rSetter = function (value) {
attr(this.element, {
rx: value,
ry: value
});
};
return wrapper.attr(attribs);
},
/**
* Resize the box and re-align all aligned elements
* @param {Object} width
* @param {Object} height
* @param {Boolean} animate
*
*/
setSize: function (width, height, animate) {
var renderer = this,
alignedObjects = renderer.alignedObjects,
i = alignedObjects.length;
renderer.width = width;
renderer.height = height;
renderer.boxWrapper[pick(animate, true) ? 'animate' : 'attr']({
width: width,
height: height
});
while (i--) {
alignedObjects[i].align();
}
},
/**
* Create a group
* @param {String} name The group will be given a class name of 'highcharts-{name}'.
* This can be used for styling and scripting.
*/
g: function (name) {
var elem = this.createElement('g');
return defined(name) ? elem.attr({ 'class': PREFIX + name }) : elem;
},
/**
* Display an image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var attribs = {
preserveAspectRatio: NONE
},
elemWrapper;
// optional properties
if (arguments.length > 1) {
extend(attribs, {
x: x,
y: y,
width: width,
height: height
});
}
elemWrapper = this.createElement('image').attr(attribs);
// set the href in the xlink namespace
if (elemWrapper.element.setAttributeNS) {
elemWrapper.element.setAttributeNS('http://www.w3.org/1999/xlink',
'href', src);
} else {
// could be exporting in IE
// using href throws "not supported" in ie7 and under, requries regex shim to fix later
elemWrapper.element.setAttribute('hc-svg-href', src);
}
return elemWrapper;
},
/**
* Draw a symbol out of pre-defined shape paths from the namespace 'symbol' object.
*
* @param {Object} symbol
* @param {Object} x
* @param {Object} y
* @param {Object} radius
* @param {Object} options
*/
symbol: function (symbol, x, y, width, height, options) {
var obj,
// get the symbol definition function
symbolFn = this.symbols[symbol],
// check if there's a path defined for this symbol
path = symbolFn && symbolFn(
mathRound(x),
mathRound(y),
width,
height,
options
),
imageElement,
imageRegex = /^url\((.*?)\)$/,
imageSrc,
imageSize,
centerImage;
if (path) {
obj = this.path(path);
// expando properties for use in animate and attr
extend(obj, {
symbolName: symbol,
x: x,
y: y,
width: width,
height: height
});
if (options) {
extend(obj, options);
}
// image symbols
} else if (imageRegex.test(symbol)) {
// On image load, set the size and position
centerImage = function (img, size) {
if (img.element) { // it may be destroyed in the meantime (#1390)
img.attr({
width: size[0],
height: size[1]
});
if (!img.alignByTranslate) { // #185
img.translate(
mathRound((width - size[0]) / 2), // #1378
mathRound((height - size[1]) / 2)
);
}
}
};
imageSrc = symbol.match(imageRegex)[1];
imageSize = symbolSizes[imageSrc] || (options && options.width && options.height && [options.width, options.height]);
// Ireate the image synchronously, add attribs async
obj = this.image(imageSrc)
.attr({
x: x,
y: y
});
obj.isImg = true;
if (imageSize) {
centerImage(obj, imageSize);
} else {
// Initialize image to be 0 size so export will still function if there's no cached sizes.
obj.attr({ width: 0, height: 0 });
// Create a dummy JavaScript image to get the width and height. Due to a bug in IE < 8,
// the created element must be assigned to a variable in order to load (#292).
imageElement = createElement('img', {
onload: function () {
centerImage(obj, symbolSizes[imageSrc] = [this.width, this.height]);
},
src: imageSrc
});
}
}
return obj;
},
/**
* An extendable collection of functions for defining symbol paths.
*/
symbols: {
'circle': function (x, y, w, h) {
var cpw = 0.166 * w;
return [
M, x + w / 2, y,
'C', x + w + cpw, y, x + w + cpw, y + h, x + w / 2, y + h,
'C', x - cpw, y + h, x - cpw, y, x + w / 2, y,
'Z'
];
},
'square': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w, y + h,
x, y + h,
'Z'
];
},
'triangle': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h,
x, y + h,
'Z'
];
},
'triangle-down': function (x, y, w, h) {
return [
M, x, y,
L, x + w, y,
x + w / 2, y + h,
'Z'
];
},
'diamond': function (x, y, w, h) {
return [
M, x + w / 2, y,
L, x + w, y + h / 2,
x + w / 2, y + h,
x, y + h / 2,
'Z'
];
},
'arc': function (x, y, w, h, options) {
var start = options.start,
radius = options.r || w || h,
end = options.end - 0.001, // to prevent cos and sin of start and end from becoming equal on 360 arcs (related: #1561)
innerRadius = options.innerR,
open = options.open,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
longArc = options.end - start < mathPI ? 0 : 1;
return [
M,
x + radius * cosStart,
y + radius * sinStart,
'A', // arcTo
radius, // x radius
radius, // y radius
0, // slanting
longArc, // long or short arc
1, // clockwise
x + radius * cosEnd,
y + radius * sinEnd,
open ? M : L,
x + innerRadius * cosEnd,
y + innerRadius * sinEnd,
'A', // arcTo
innerRadius, // x radius
innerRadius, // y radius
0, // slanting
longArc, // long or short arc
0, // clockwise
x + innerRadius * cosStart,
y + innerRadius * sinStart,
open ? '' : 'Z' // close
];
},
/**
* Callout shape used for default tooltips, also used for rounded rectangles in VML
*/
callout: function (x, y, w, h, options) {
var arrowLength = 6,
halfDistance = 6,
r = mathMin((options && options.r) || 0, w, h),
safeDistance = r + halfDistance,
anchorX = options && options.anchorX,
anchorY = options && options.anchorY,
path,
normalizer = mathRound(options.strokeWidth || 0) % 2 / 2; // mathRound because strokeWidth can sometimes have roundoff errors;
x += normalizer;
y += normalizer;
path = [
'M', x + r, y,
'L', x + w - r, y, // top side
'C', x + w, y, x + w, y, x + w, y + r, // top-right corner
'L', x + w, y + h - r, // right side
'C', x + w, y + h, x + w, y + h, x + w - r, y + h, // bottom-right corner
'L', x + r, y + h, // bottom side
'C', x, y + h, x, y + h, x, y + h - r, // bottom-left corner
'L', x, y + r, // left side
'C', x, y, x, y, x + r, y // top-right corner
];
if (anchorX && anchorX > w && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace right side
path.splice(13, 3,
'L', x + w, anchorY - halfDistance,
x + w + arrowLength, anchorY,
x + w, anchorY + halfDistance,
x + w, y + h - r
);
} else if (anchorX && anchorX < 0 && anchorY > y + safeDistance && anchorY < y + h - safeDistance) { // replace left side
path.splice(33, 3,
'L', x, anchorY + halfDistance,
x - arrowLength, anchorY,
x, anchorY - halfDistance,
x, y + r
);
} else if (anchorY && anchorY > h && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace bottom
path.splice(23, 3,
'L', anchorX + halfDistance, y + h,
anchorX, y + h + arrowLength,
anchorX - halfDistance, y + h,
x + r, y + h
);
} else if (anchorY && anchorY < 0 && anchorX > x + safeDistance && anchorX < x + w - safeDistance) { // replace top
path.splice(3, 3,
'L', anchorX - halfDistance, y,
anchorX, y - arrowLength,
anchorX + halfDistance, y,
w - r, y
);
}
return path;
}
},
/**
* Define a clipping rectangle
* @param {String} id
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
var wrapper,
id = PREFIX + idCounter++,
clipPath = this.createElement('clipPath').attr({
id: id
}).add(this.defs);
wrapper = this.rect(x, y, width, height, 0).add(clipPath);
wrapper.id = id;
wrapper.clipPath = clipPath;
wrapper.count = 0;
return wrapper;
},
/**
* Add text to the SVG object
* @param {String} str
* @param {Number} x Left position
* @param {Number} y Top position
* @param {Boolean} useHTML Use HTML to render the text
*/
text: function (str, x, y, useHTML) {
// declare variables
var renderer = this,
fakeSVG = useCanVG || (!hasSVG && renderer.forExport),
wrapper,
attr = {};
if (useHTML && !renderer.forExport) {
return renderer.html(str, x, y);
}
attr.x = Math.round(x || 0); // X is always needed for line-wrap logic
if (y) {
attr.y = Math.round(y);
}
if (str || str === 0) {
attr.text = str;
}
wrapper = renderer.createElement('text')
.attr(attr);
// Prevent wrapping from creating false offsetWidths in export in legacy IE (#1079, #1063)
if (fakeSVG) {
wrapper.css({
position: ABSOLUTE
});
}
if (!useHTML) {
wrapper.xSetter = function (value, key, element) {
var tspans = element.getElementsByTagName('tspan'),
tspan,
parentVal = element.getAttribute(key),
i;
for (i = 0; i < tspans.length; i++) {
tspan = tspans[i];
// If the x values are equal, the tspan represents a linebreak
if (tspan.getAttribute(key) === parentVal) {
tspan.setAttribute(key, value);
}
}
element.setAttribute(key, value);
};
}
return wrapper;
},
/**
* Utility to return the baseline offset and total line height from the font size
*/
fontMetrics: function (fontSize, elem) {
fontSize = fontSize || this.style.fontSize;
if (elem && win.getComputedStyle) {
elem = elem.element || elem; // SVGElement
fontSize = win.getComputedStyle(elem, "").fontSize;
}
fontSize = /px/.test(fontSize) ? pInt(fontSize) : /em/.test(fontSize) ? parseFloat(fontSize) * 12 : 12;
// Empirical values found by comparing font size and bounding box height.
// Applies to the default font family. http://jsfiddle.net/highcharts/7xvn7/
var lineHeight = fontSize < 24 ? fontSize + 3 : mathRound(fontSize * 1.2),
baseline = mathRound(lineHeight * 0.8);
return {
h: lineHeight,
b: baseline,
f: fontSize
};
},
/**
* Correct X and Y positioning of a label for rotation (#1764)
*/
rotCorr: function (baseline, rotation, alterY) {
var y = baseline;
if (rotation && alterY) {
y = mathMax(y * mathCos(rotation * deg2rad), 4);
}
return {
x: (-baseline / 3) * mathSin(rotation * deg2rad),
y: y
};
},
/**
* Add a label, a text item that can hold a colored or gradient background
* as well as a border and shadow.
* @param {string} str
* @param {Number} x
* @param {Number} y
* @param {String} shape
* @param {Number} anchorX In case the shape has a pointer, like a flag, this is the
* coordinates it should be pinned to
* @param {Number} anchorY
* @param {Boolean} baseline Whether to position the label relative to the text baseline,
* like renderer.text, or to the upper border of the rectangle.
* @param {String} className Class name for the group
*/
label: function (str, x, y, shape, anchorX, anchorY, useHTML, baseline, className) {
var renderer = this,
wrapper = renderer.g(className),
text = renderer.text('', 0, 0, useHTML)
.attr({
zIndex: 1
}),
//.add(wrapper),
box,
bBox,
alignFactor = 0,
padding = 3,
paddingLeft = 0,
width,
height,
wrapperX,
wrapperY,
crispAdjust = 0,
deferredAttr = {},
baselineOffset,
needsBox;
/**
* This function runs after the label is added to the DOM (when the bounding box is
* available), and after the text of the label is updated to detect the new bounding
* box and reflect it in the border box.
*/
function updateBoxSize() {
var boxX,
boxY,
style = text.element.style;
bBox = (width === undefined || height === undefined || wrapper.styles.textAlign) && defined(text.textStr) &&
text.getBBox(); //#3295 && 3514 box failure when string equals 0
wrapper.width = (width || bBox.width || 0) + 2 * padding + paddingLeft;
wrapper.height = (height || bBox.height || 0) + 2 * padding;
// update the label-scoped y offset
baselineOffset = padding + renderer.fontMetrics(style && style.fontSize, text).b;
if (needsBox) {
// create the border box if it is not already present
if (!box) {
boxX = mathRound(-alignFactor * padding);
boxY = baseline ? -baselineOffset : 0;
wrapper.box = box = shape ?
renderer.symbol(shape, boxX, boxY, wrapper.width, wrapper.height, deferredAttr) :
renderer.rect(boxX, boxY, wrapper.width, wrapper.height, 0, deferredAttr[STROKE_WIDTH]);
box.attr('fill', NONE).add(wrapper);
}
// apply the box attributes
if (!box.isImg) { // #1630
box.attr(extend({
width: mathRound(wrapper.width),
height: mathRound(wrapper.height)
}, deferredAttr));
}
deferredAttr = null;
}
}
/**
* This function runs after setting text or padding, but only if padding is changed
*/
function updateTextPadding() {
var styles = wrapper.styles,
textAlign = styles && styles.textAlign,
x = paddingLeft + padding * (1 - alignFactor),
y;
// determin y based on the baseline
y = baseline ? 0 : baselineOffset;
// compensate for alignment
if (defined(width) && bBox && (textAlign === 'center' || textAlign === 'right')) {
x += { center: 0.5, right: 1 }[textAlign] * (width - bBox.width);
}
// update if anything changed
if (x !== text.x || y !== text.y) {
text.attr('x', x);
if (y !== UNDEFINED) {
text.attr('y', y);
}
}
// record current values
text.x = x;
text.y = y;
}
/**
* Set a box attribute, or defer it if the box is not yet created
* @param {Object} key
* @param {Object} value
*/
function boxAttr(key, value) {
if (box) {
box.attr(key, value);
} else {
deferredAttr[key] = value;
}
}
/**
* After the text element is added, get the desired size of the border box
* and add it before the text in the DOM.
*/
wrapper.onAdd = function () {
text.add(wrapper);
wrapper.attr({
text: (str || str === 0) ? str : '', // alignment is available now // #3295: 0 not rendered if given as a value
x: x,
y: y
});
if (box && defined(anchorX)) {
wrapper.attr({
anchorX: anchorX,
anchorY: anchorY
});
}
};
/*
* Add specific attribute setters.
*/
// only change local variables
wrapper.widthSetter = function (value) {
width = value;
};
wrapper.heightSetter = function (value) {
height = value;
};
wrapper.paddingSetter = function (value) {
if (defined(value) && value !== padding) {
padding = wrapper.padding = value;
updateTextPadding();
}
};
wrapper.paddingLeftSetter = function (value) {
if (defined(value) && value !== paddingLeft) {
paddingLeft = value;
updateTextPadding();
}
};
// change local variable and prevent setting attribute on the group
wrapper.alignSetter = function (value) {
alignFactor = { left: 0, center: 0.5, right: 1 }[value];
};
// apply these to the box and the text alike
wrapper.textSetter = function (value) {
if (value !== UNDEFINED) {
text.textSetter(value);
}
updateBoxSize();
updateTextPadding();
};
// apply these to the box but not to the text
wrapper['stroke-widthSetter'] = function (value, key) {
if (value) {
needsBox = true;
}
crispAdjust = value % 2 / 2;
boxAttr(key, value);
};
wrapper.strokeSetter = wrapper.fillSetter = wrapper.rSetter = function (value, key) {
if (key === 'fill' && value) {
needsBox = true;
}
boxAttr(key, value);
};
wrapper.anchorXSetter = function (value, key) {
anchorX = value;
boxAttr(key, value + crispAdjust - wrapperX);
};
wrapper.anchorYSetter = function (value, key) {
anchorY = value;
boxAttr(key, value - wrapperY);
};
// rename attributes
wrapper.xSetter = function (value) {
wrapper.x = value; // for animation getter
if (alignFactor) {
value -= alignFactor * ((width || bBox.width) + padding);
}
wrapperX = mathRound(value);
wrapper.attr('translateX', wrapperX);
};
wrapper.ySetter = function (value) {
wrapperY = wrapper.y = mathRound(value);
wrapper.attr('translateY', wrapperY);
};
// Redirect certain methods to either the box or the text
var baseCss = wrapper.css;
return extend(wrapper, {
/**
* Pick up some properties and apply them to the text instead of the wrapper
*/
css: function (styles) {
if (styles) {
var textStyles = {};
styles = merge(styles); // create a copy to avoid altering the original object (#537)
each(wrapper.textProps, function (prop) {
if (styles[prop] !== UNDEFINED) {
textStyles[prop] = styles[prop];
delete styles[prop];
}
});
text.css(textStyles);
}
return baseCss.call(wrapper, styles);
},
/**
* Return the bounding box of the box, not the group
*/
getBBox: function () {
return {
width: bBox.width + 2 * padding,
height: bBox.height + 2 * padding,
x: bBox.x - padding,
y: bBox.y - padding
};
},
/**
* Apply the shadow to the box
*/
shadow: function (b) {
if (box) {
box.shadow(b);
}
return wrapper;
},
/**
* Destroy and release memory.
*/
destroy: function () {
// Added by button implementation
removeEvent(wrapper.element, 'mouseenter');
removeEvent(wrapper.element, 'mouseleave');
if (text) {
text = text.destroy();
}
if (box) {
box = box.destroy();
}
// Call base implementation to destroy the rest
SVGElement.prototype.destroy.call(wrapper);
// Release local pointers (#1298)
wrapper = renderer = updateBoxSize = updateTextPadding = boxAttr = null;
}
});
}
}; // end SVGRenderer
// general renderer
Renderer = SVGRenderer;
// extend SvgElement for useHTML option
extend(SVGElement.prototype, {
/**
* Apply CSS to HTML elements. This is used in text within SVG rendering and
* by the VML renderer
*/
htmlCss: function (styles) {
var wrapper = this,
element = wrapper.element,
textWidth = styles && element.tagName === 'SPAN' && styles.width;
if (textWidth) {
delete styles.width;
wrapper.textWidth = textWidth;
wrapper.updateTransform();
}
if (styles && styles.textOverflow === 'ellipsis') {
styles.whiteSpace = 'nowrap';
styles.overflow = 'hidden';
}
wrapper.styles = extend(wrapper.styles, styles);
css(wrapper.element, styles);
return wrapper;
},
/**
* VML and useHTML method for calculating the bounding box based on offsets
* @param {Boolean} refresh Whether to force a fresh value from the DOM or to
* use the cached value
*
* @return {Object} A hash containing values for x, y, width and height
*/
htmlGetBBox: function () {
var wrapper = this,
element = wrapper.element;
// faking getBBox in exported SVG in legacy IE
// faking getBBox in exported SVG in legacy IE (is this a duplicate of the fix for #1079?)
if (element.nodeName === 'text') {
element.style.position = ABSOLUTE;
}
return {
x: element.offsetLeft,
y: element.offsetTop,
width: element.offsetWidth,
height: element.offsetHeight
};
},
/**
* VML override private method to update elements based on internal
* properties based on SVG transform
*/
htmlUpdateTransform: function () {
// aligning non added elements is expensive
if (!this.added) {
this.alignOnAdd = true;
return;
}
var wrapper = this,
renderer = wrapper.renderer,
elem = wrapper.element,
translateX = wrapper.translateX || 0,
translateY = wrapper.translateY || 0,
x = wrapper.x || 0,
y = wrapper.y || 0,
align = wrapper.textAlign || 'left',
alignCorrection = { left: 0, center: 0.5, right: 1 }[align],
shadows = wrapper.shadows,
styles = wrapper.styles;
// apply translate
css(elem, {
marginLeft: translateX,
marginTop: translateY
});
if (shadows) { // used in labels/tooltip
each(shadows, function (shadow) {
css(shadow, {
marginLeft: translateX + 1,
marginTop: translateY + 1
});
});
}
// apply inversion
if (wrapper.inverted) { // wrapper is a group
each(elem.childNodes, function (child) {
renderer.invertChild(child, elem);
});
}
if (elem.tagName === 'SPAN') {
var width,
rotation = wrapper.rotation,
baseline,
textWidth = pInt(wrapper.textWidth),
currentTextTransform = [rotation, align, elem.innerHTML, wrapper.textWidth].join(',');
if (currentTextTransform !== wrapper.cTT) { // do the calculations and DOM access only if properties changed
baseline = renderer.fontMetrics(elem.style.fontSize).b;
// Renderer specific handling of span rotation
if (defined(rotation)) {
wrapper.setSpanRotation(rotation, alignCorrection, baseline);
}
width = pick(wrapper.elemWidth, elem.offsetWidth);
// Update textWidth
if (width > textWidth && /[ \-]/.test(elem.textContent || elem.innerText)) { // #983, #1254
css(elem, {
width: textWidth + PX,
display: 'block',
whiteSpace: (styles && styles.whiteSpace) || 'normal' // #3331
});
width = textWidth;
}
wrapper.getSpanCorrection(width, baseline, alignCorrection, rotation, align);
}
// apply position with correction
css(elem, {
left: (x + (wrapper.xCorr || 0)) + PX,
top: (y + (wrapper.yCorr || 0)) + PX
});
// force reflow in webkit to apply the left and top on useHTML element (#1249)
if (isWebKit) {
baseline = elem.offsetHeight; // assigned to baseline for JSLint purpose
}
// record current text transform
wrapper.cTT = currentTextTransform;
}
},
/**
* Set the rotation of an individual HTML span
*/
setSpanRotation: function (rotation, alignCorrection, baseline) {
var rotationStyle = {},
cssTransformKey = isIE ? '-ms-transform' : isWebKit ? '-webkit-transform' : isFirefox ? 'MozTransform' : isOpera ? '-o-transform' : '';
rotationStyle[cssTransformKey] = rotationStyle.transform = 'rotate(' + rotation + 'deg)';
rotationStyle[cssTransformKey + (isFirefox ? 'Origin' : '-origin')] = rotationStyle.transformOrigin = (alignCorrection * 100) + '% ' + baseline + 'px';
css(this.element, rotationStyle);
},
/**
* Get the correction in X and Y positioning as the element is rotated.
*/
getSpanCorrection: function (width, baseline, alignCorrection) {
this.xCorr = -width * alignCorrection;
this.yCorr = -baseline;
}
});
// Extend SvgRenderer for useHTML option.
extend(SVGRenderer.prototype, {
/**
* Create HTML text node. This is used by the VML renderer as well as the SVG
* renderer through the useHTML option.
*
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
html: function (str, x, y) {
var wrapper = this.createElement('span'),
element = wrapper.element,
renderer = wrapper.renderer;
// Text setter
wrapper.textSetter = function (value) {
if (value !== element.innerHTML) {
delete this.bBox;
}
element.innerHTML = this.textStr = value;
};
// Various setters which rely on update transform
wrapper.xSetter = wrapper.ySetter = wrapper.alignSetter = wrapper.rotationSetter = function (value, key) {
if (key === 'align') {
key = 'textAlign'; // Do not overwrite the SVGElement.align method. Same as VML.
}
wrapper[key] = value;
wrapper.htmlUpdateTransform();
};
// Set the default attributes
wrapper.attr({
text: str,
x: mathRound(x),
y: mathRound(y)
})
.css({
position: ABSOLUTE,
fontFamily: this.style.fontFamily,
fontSize: this.style.fontSize
});
// Keep the whiteSpace style outside the wrapper.styles collection
element.style.whiteSpace = 'nowrap';
// Use the HTML specific .css method
wrapper.css = wrapper.htmlCss;
// This is specific for HTML within SVG
if (renderer.isSVG) {
wrapper.add = function (svgGroupWrapper) {
var htmlGroup,
container = renderer.box.parentNode,
parentGroup,
parents = [];
this.parentGroup = svgGroupWrapper;
// Create a mock group to hold the HTML elements
if (svgGroupWrapper) {
htmlGroup = svgGroupWrapper.div;
if (!htmlGroup) {
// Read the parent chain into an array and read from top down
parentGroup = svgGroupWrapper;
while (parentGroup) {
parents.push(parentGroup);
// Move up to the next parent group
parentGroup = parentGroup.parentGroup;
}
// Ensure dynamically updating position when any parent is translated
each(parents.reverse(), function (parentGroup) {
var htmlGroupStyle;
// Create a HTML div and append it to the parent div to emulate
// the SVG group structure
htmlGroup = parentGroup.div = parentGroup.div || createElement(DIV, {
className: attr(parentGroup.element, 'class')
}, {
position: ABSOLUTE,
left: (parentGroup.translateX || 0) + PX,
top: (parentGroup.translateY || 0) + PX
}, htmlGroup || container); // the top group is appended to container
// Shortcut
htmlGroupStyle = htmlGroup.style;
// Set listeners to update the HTML div's position whenever the SVG group
// position is changed
extend(parentGroup, {
translateXSetter: function (value, key) {
htmlGroupStyle.left = value + PX;
parentGroup[key] = value;
parentGroup.doTransform = true;
},
translateYSetter: function (value, key) {
htmlGroupStyle.top = value + PX;
parentGroup[key] = value;
parentGroup.doTransform = true;
},
visibilitySetter: function (value, key) {
htmlGroupStyle[key] = value;
}
});
});
}
} else {
htmlGroup = container;
}
htmlGroup.appendChild(element);
// Shared with VML:
wrapper.added = true;
if (wrapper.alignOnAdd) {
wrapper.htmlUpdateTransform();
}
return wrapper;
};
}
return wrapper;
}
});
/* ****************************************************************************
* *
* START OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
* For applications and websites that don't need IE support, like platform *
* targeted mobile apps and web apps, this code can be removed. *
* *
*****************************************************************************/
/**
* @constructor
*/
var VMLRenderer, VMLElement;
if (!hasSVG && !useCanVG) {
/**
* The VML element wrapper.
*/
VMLElement = {
/**
* Initialize a new VML element wrapper. It builds the markup as a string
* to minimize DOM traffic.
* @param {Object} renderer
* @param {Object} nodeName
*/
init: function (renderer, nodeName) {
var wrapper = this,
markup = ['<', nodeName, ' filled="f" stroked="f"'],
style = ['position: ', ABSOLUTE, ';'],
isDiv = nodeName === DIV;
// divs and shapes need size
if (nodeName === 'shape' || isDiv) {
style.push('left:0;top:0;width:1px;height:1px;');
}
style.push('visibility: ', isDiv ? HIDDEN : VISIBLE);
markup.push(' style="', style.join(''), '"/>');
// create element with default attributes and style
if (nodeName) {
markup = isDiv || nodeName === 'span' || nodeName === 'img' ?
markup.join('')
: renderer.prepVML(markup);
wrapper.element = createElement(markup);
}
wrapper.renderer = renderer;
},
/**
* Add the node to the given parent
* @param {Object} parent
*/
add: function (parent) {
var wrapper = this,
renderer = wrapper.renderer,
element = wrapper.element,
box = renderer.box,
inverted = parent && parent.inverted,
// get the parent node
parentNode = parent ?
parent.element || parent :
box;
// if the parent group is inverted, apply inversion on all children
if (inverted) { // only on groups
renderer.invertChild(element, parentNode);
}
// append it
parentNode.appendChild(element);
// align text after adding to be able to read offset
wrapper.added = true;
if (wrapper.alignOnAdd && !wrapper.deferUpdateTransform) {
wrapper.updateTransform();
}
// fire an event for internal hooks
if (wrapper.onAdd) {
wrapper.onAdd();
}
return wrapper;
},
/**
* VML always uses htmlUpdateTransform
*/
updateTransform: SVGElement.prototype.htmlUpdateTransform,
/**
* Set the rotation of a span with oldIE's filter
*/
setSpanRotation: function () {
// Adjust for alignment and rotation. Rotation of useHTML content is not yet implemented
// but it can probably be implemented for Firefox 3.5+ on user request. FF3.5+
// has support for CSS3 transform. The getBBox method also needs to be updated
// to compensate for the rotation, like it currently does for SVG.
// Test case: http://jsfiddle.net/highcharts/Ybt44/
var rotation = this.rotation,
costheta = mathCos(rotation * deg2rad),
sintheta = mathSin(rotation * deg2rad);
css(this.element, {
filter: rotation ? ['progid:DXImageTransform.Microsoft.Matrix(M11=', costheta,
', M12=', -sintheta, ', M21=', sintheta, ', M22=', costheta,
', sizingMethod=\'auto expand\')'].join('') : NONE
});
},
/**
* Get the positioning correction for the span after rotating.
*/
getSpanCorrection: function (width, baseline, alignCorrection, rotation, align) {
var costheta = rotation ? mathCos(rotation * deg2rad) : 1,
sintheta = rotation ? mathSin(rotation * deg2rad) : 0,
height = pick(this.elemHeight, this.element.offsetHeight),
quad,
nonLeft = align && align !== 'left';
// correct x and y
this.xCorr = costheta < 0 && -width;
this.yCorr = sintheta < 0 && -height;
// correct for baseline and corners spilling out after rotation
quad = costheta * sintheta < 0;
this.xCorr += sintheta * baseline * (quad ? 1 - alignCorrection : alignCorrection);
this.yCorr -= costheta * baseline * (rotation ? (quad ? alignCorrection : 1 - alignCorrection) : 1);
// correct for the length/height of the text
if (nonLeft) {
this.xCorr -= width * alignCorrection * (costheta < 0 ? -1 : 1);
if (rotation) {
this.yCorr -= height * alignCorrection * (sintheta < 0 ? -1 : 1);
}
css(this.element, {
textAlign: align
});
}
},
/**
* Converts a subset of an SVG path definition to its VML counterpart. Takes an array
* as the parameter and returns a string.
*/
pathToVML: function (value) {
// convert paths
var i = value.length,
path = [];
while (i--) {
// Multiply by 10 to allow subpixel precision.
// Substracting half a pixel seems to make the coordinates
// align with SVG, but this hasn't been tested thoroughly
if (isNumber(value[i])) {
path[i] = mathRound(value[i] * 10) - 5;
} else if (value[i] === 'Z') { // close the path
path[i] = 'x';
} else {
path[i] = value[i];
// When the start X and end X coordinates of an arc are too close,
// they are rounded to the same value above. In this case, substract or
// add 1 from the end X and Y positions. #186, #760, #1371, #1410.
if (value.isArc && (value[i] === 'wa' || value[i] === 'at')) {
// Start and end X
if (path[i + 5] === path[i + 7]) {
path[i + 7] += value[i + 7] > value[i + 5] ? 1 : -1;
}
// Start and end Y
if (path[i + 6] === path[i + 8]) {
path[i + 8] += value[i + 8] > value[i + 6] ? 1 : -1;
}
}
}
}
// Loop up again to handle path shortcuts (#2132)
/*while (i++ < path.length) {
if (path[i] === 'H') { // horizontal line to
path[i] = 'L';
path.splice(i + 2, 0, path[i - 1]);
} else if (path[i] === 'V') { // vertical line to
path[i] = 'L';
path.splice(i + 1, 0, path[i - 2]);
}
}*/
return path.join(' ') || 'x';
},
/**
* Set the element's clipping to a predefined rectangle
*
* @param {String} id The id of the clip rectangle
*/
clip: function (clipRect) {
var wrapper = this,
clipMembers,
cssRet;
if (clipRect) {
clipMembers = clipRect.members;
erase(clipMembers, wrapper); // Ensure unique list of elements (#1258)
clipMembers.push(wrapper);
wrapper.destroyClip = function () {
erase(clipMembers, wrapper);
};
cssRet = clipRect.getCSS(wrapper);
} else {
if (wrapper.destroyClip) {
wrapper.destroyClip();
}
cssRet = { clip: docMode8 ? 'inherit' : 'rect(auto)' }; // #1214
}
return wrapper.css(cssRet);
},
/**
* Set styles for the element
* @param {Object} styles
*/
css: SVGElement.prototype.htmlCss,
/**
* Removes a child either by removeChild or move to garbageBin.
* Issue 490; in VML removeChild results in Orphaned nodes according to sIEve, discardElement does not.
*/
safeRemoveChild: function (element) {
// discardElement will detach the node from its parent before attaching it
// to the garbage bin. Therefore it is important that the node is attached and have parent.
if (element.parentNode) {
discardElement(element);
}
},
/**
* Extend element.destroy by removing it from the clip members array
*/
destroy: function () {
if (this.destroyClip) {
this.destroyClip();
}
return SVGElement.prototype.destroy.apply(this);
},
/**
* Add an event listener. VML override for normalizing event parameters.
* @param {String} eventType
* @param {Function} handler
*/
on: function (eventType, handler) {
// simplest possible event model for internal use
this.element['on' + eventType] = function () {
var evt = win.event;
evt.target = evt.srcElement;
handler(evt);
};
return this;
},
/**
* In stacked columns, cut off the shadows so that they don't overlap
*/
cutOffPath: function (path, length) {
var len;
path = path.split(/[ ,]/);
len = path.length;
if (len === 9 || len === 11) {
path[len - 4] = path[len - 2] = pInt(path[len - 2]) - 10 * length;
}
return path.join(' ');
},
/**
* Apply a drop shadow by copying elements and giving them different strokes
* @param {Boolean|Object} shadowOptions
*/
shadow: function (shadowOptions, group, cutOff) {
var shadows = [],
i,
element = this.element,
renderer = this.renderer,
shadow,
elemStyle = element.style,
markup,
path = element.path,
strokeWidth,
modifiedPath,
shadowWidth,
shadowElementOpacity;
// some times empty paths are not strings
if (path && typeof path.value !== 'string') {
path = 'x';
}
modifiedPath = path;
if (shadowOptions) {
shadowWidth = pick(shadowOptions.width, 3);
shadowElementOpacity = (shadowOptions.opacity || 0.15) / shadowWidth;
for (i = 1; i <= 3; i++) {
strokeWidth = (shadowWidth * 2) + 1 - (2 * i);
// Cut off shadows for stacked column items
if (cutOff) {
modifiedPath = this.cutOffPath(path.value, strokeWidth + 0.5);
}
markup = ['<shape isShadow="true" strokeweight="', strokeWidth,
'" filled="false" path="', modifiedPath,
'" coordsize="10 10" style="', element.style.cssText, '" />'];
shadow = createElement(renderer.prepVML(markup),
null, {
left: pInt(elemStyle.left) + pick(shadowOptions.offsetX, 1),
top: pInt(elemStyle.top) + pick(shadowOptions.offsetY, 1)
}
);
if (cutOff) {
shadow.cutOff = strokeWidth + 1;
}
// apply the opacity
markup = ['<stroke color="', shadowOptions.color || 'black', '" opacity="', shadowElementOpacity * i, '"/>'];
createElement(renderer.prepVML(markup), null, null, shadow);
// insert it
if (group) {
group.element.appendChild(shadow);
} else {
element.parentNode.insertBefore(shadow, element);
}
// record it
shadows.push(shadow);
}
this.shadows = shadows;
}
return this;
},
updateShadows: noop, // Used in SVG only
setAttr: function (key, value) {
if (docMode8) { // IE8 setAttribute bug
this.element[key] = value;
} else {
this.element.setAttribute(key, value);
}
},
classSetter: function (value) {
// IE8 Standards mode has problems retrieving the className unless set like this
this.element.className = value;
},
dashstyleSetter: function (value, key, element) {
var strokeElem = element.getElementsByTagName('stroke')[0] ||
createElement(this.renderer.prepVML(['<stroke/>']), null, null, element);
strokeElem[key] = value || 'solid';
this[key] = value; /* because changing stroke-width will change the dash length
and cause an epileptic effect */
},
dSetter: function (value, key, element) {
var i,
shadows = this.shadows;
value = value || [];
this.d = value.join && value.join(' '); // used in getter for animation
element.path = value = this.pathToVML(value);
// update shadows
if (shadows) {
i = shadows.length;
while (i--) {
shadows[i].path = shadows[i].cutOff ? this.cutOffPath(value, shadows[i].cutOff) : value;
}
}
this.setAttr(key, value);
},
fillSetter: function (value, key, element) {
var nodeName = element.nodeName;
if (nodeName === 'SPAN') { // text color
element.style.color = value;
} else if (nodeName !== 'IMG') { // #1336
element.filled = value !== NONE;
this.setAttr('fillcolor', this.renderer.color(value, element, key, this));
}
},
opacitySetter: noop, // Don't bother - animation is too slow and filters introduce artifacts
rotationSetter: function (value, key, element) {
var style = element.style;
this[key] = style[key] = value; // style is for #1873
// Correction for the 1x1 size of the shape container. Used in gauge needles.
style.left = -mathRound(mathSin(value * deg2rad) + 1) + PX;
style.top = mathRound(mathCos(value * deg2rad)) + PX;
},
strokeSetter: function (value, key, element) {
this.setAttr('strokecolor', this.renderer.color(value, element, key));
},
'stroke-widthSetter': function (value, key, element) {
element.stroked = !!value; // VML "stroked" attribute
this[key] = value; // used in getter, issue #113
if (isNumber(value)) {
value += PX;
}
this.setAttr('strokeweight', value);
},
titleSetter: function (value, key) {
this.setAttr(key, value);
},
visibilitySetter: function (value, key, element) {
// Handle inherited visibility
if (value === 'inherit') {
value = VISIBLE;
}
// Let the shadow follow the main element
if (this.shadows) {
each(this.shadows, function (shadow) {
shadow.style[key] = value;
});
}
// Instead of toggling the visibility CSS property, move the div out of the viewport.
// This works around #61 and #586
if (element.nodeName === 'DIV') {
value = value === HIDDEN ? '-999em' : 0;
// In order to redraw, IE7 needs the div to be visible when tucked away
// outside the viewport. So the visibility is actually opposite of
// the expected value. This applies to the tooltip only.
if (!docMode8) {
element.style[key] = value ? VISIBLE : HIDDEN;
}
key = 'top';
}
element.style[key] = value;
},
xSetter: function (value, key, element) {
this[key] = value; // used in getter
if (key === 'x') {
key = 'left';
} else if (key === 'y') {
key = 'top';
}/* else {
value = mathMax(0, value); // don't set width or height below zero (#311)
}*/
// clipping rectangle special
if (this.updateClipping) {
this[key] = value; // the key is now 'left' or 'top' for 'x' and 'y'
this.updateClipping();
} else {
// normal
element.style[key] = value;
}
},
zIndexSetter: function (value, key, element) {
element.style[key] = value;
}
};
Highcharts.VMLElement = VMLElement = extendClass(SVGElement, VMLElement);
// Some shared setters
VMLElement.prototype.ySetter =
VMLElement.prototype.widthSetter =
VMLElement.prototype.heightSetter =
VMLElement.prototype.xSetter;
/**
* The VML renderer
*/
var VMLRendererExtension = { // inherit SVGRenderer
Element: VMLElement,
isIE8: userAgent.indexOf('MSIE 8.0') > -1,
/**
* Initialize the VMLRenderer
* @param {Object} container
* @param {Number} width
* @param {Number} height
*/
init: function (container, width, height, style) {
var renderer = this,
boxWrapper,
box,
css;
renderer.alignedObjects = [];
boxWrapper = renderer.createElement(DIV)
.css(extend(this.getStyle(style), { position: RELATIVE}));
box = boxWrapper.element;
container.appendChild(boxWrapper.element);
// generate the containing box
renderer.isVML = true;
renderer.box = box;
renderer.boxWrapper = boxWrapper;
renderer.cache = {};
renderer.setSize(width, height, false);
// The only way to make IE6 and IE7 print is to use a global namespace. However,
// with IE8 the only way to make the dynamic shapes visible in screen and print mode
// seems to be to add the xmlns attribute and the behaviour style inline.
if (!doc.namespaces.hcv) {
doc.namespaces.add('hcv', 'urn:schemas-microsoft-com:vml');
// Setup default CSS (#2153, #2368, #2384)
css = 'hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke' +
'{ behavior:url(#default#VML); display: inline-block; } ';
try {
doc.createStyleSheet().cssText = css;
} catch (e) {
doc.styleSheets[0].cssText += css;
}
}
},
/**
* Detect whether the renderer is hidden. This happens when one of the parent elements
* has display: none
*/
isHidden: function () {
return !this.box.offsetWidth;
},
/**
* Define a clipping rectangle. In VML it is accomplished by storing the values
* for setting the CSS style to all associated members.
*
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
clipRect: function (x, y, width, height) {
// create a dummy element
var clipRect = this.createElement(),
isObj = isObject(x);
// mimic a rectangle with its style object for automatic updating in attr
return extend(clipRect, {
members: [],
count: 0,
left: (isObj ? x.x : x) + 1,
top: (isObj ? x.y : y) + 1,
width: (isObj ? x.width : width) - 1,
height: (isObj ? x.height : height) - 1,
getCSS: function (wrapper) {
var element = wrapper.element,
nodeName = element.nodeName,
isShape = nodeName === 'shape',
inverted = wrapper.inverted,
rect = this,
top = rect.top - (isShape ? element.offsetTop : 0),
left = rect.left,
right = left + rect.width,
bottom = top + rect.height,
ret = {
clip: 'rect(' +
mathRound(inverted ? left : top) + 'px,' +
mathRound(inverted ? bottom : right) + 'px,' +
mathRound(inverted ? right : bottom) + 'px,' +
mathRound(inverted ? top : left) + 'px)'
};
// issue 74 workaround
if (!inverted && docMode8 && nodeName === 'DIV') {
extend(ret, {
width: right + PX,
height: bottom + PX
});
}
return ret;
},
// used in attr and animation to update the clipping of all members
updateClipping: function () {
each(clipRect.members, function (member) {
if (member.element) { // Deleted series, like in stock/members/series-remove demo. Should be removed from members, but this will do.
member.css(clipRect.getCSS(member));
}
});
}
});
},
/**
* Take a color and return it if it's a string, make it a gradient if it's a
* gradient configuration object, and apply opacity.
*
* @param {Object} color The color or config object
*/
color: function (color, elem, prop, wrapper) {
var renderer = this,
colorObject,
regexRgba = /^rgba/,
markup,
fillType,
ret = NONE;
// Check for linear or radial gradient
if (color && color.linearGradient) {
fillType = 'gradient';
} else if (color && color.radialGradient) {
fillType = 'pattern';
}
if (fillType) {
var stopColor,
stopOpacity,
gradient = color.linearGradient || color.radialGradient,
x1,
y1,
x2,
y2,
opacity1,
opacity2,
color1,
color2,
fillAttr = '',
stops = color.stops,
firstStop,
lastStop,
colors = [],
addFillNode = function () {
// Add the fill subnode. When colors attribute is used, the meanings of opacity and o:opacity2
// are reversed.
markup = ['<fill colors="' + colors.join(',') + '" opacity="', opacity2, '" o:opacity2="', opacity1,
'" type="', fillType, '" ', fillAttr, 'focus="100%" method="any" />'];
createElement(renderer.prepVML(markup), null, null, elem);
};
// Extend from 0 to 1
firstStop = stops[0];
lastStop = stops[stops.length - 1];
if (firstStop[0] > 0) {
stops.unshift([
0,
firstStop[1]
]);
}
if (lastStop[0] < 1) {
stops.push([
1,
lastStop[1]
]);
}
// Compute the stops
each(stops, function (stop, i) {
if (regexRgba.test(stop[1])) {
colorObject = Color(stop[1]);
stopColor = colorObject.get('rgb');
stopOpacity = colorObject.get('a');
} else {
stopColor = stop[1];
stopOpacity = 1;
}
// Build the color attribute
colors.push((stop[0] * 100) + '% ' + stopColor);
// Only start and end opacities are allowed, so we use the first and the last
if (!i) {
opacity1 = stopOpacity;
color2 = stopColor;
} else {
opacity2 = stopOpacity;
color1 = stopColor;
}
});
// Apply the gradient to fills only.
if (prop === 'fill') {
// Handle linear gradient angle
if (fillType === 'gradient') {
x1 = gradient.x1 || gradient[0] || 0;
y1 = gradient.y1 || gradient[1] || 0;
x2 = gradient.x2 || gradient[2] || 0;
y2 = gradient.y2 || gradient[3] || 0;
fillAttr = 'angle="' + (90 - math.atan(
(y2 - y1) / // y vector
(x2 - x1) // x vector
) * 180 / mathPI) + '"';
addFillNode();
// Radial (circular) gradient
} else {
var r = gradient.r,
sizex = r * 2,
sizey = r * 2,
cx = gradient.cx,
cy = gradient.cy,
radialReference = elem.radialReference,
bBox,
applyRadialGradient = function () {
if (radialReference) {
bBox = wrapper.getBBox();
cx += (radialReference[0] - bBox.x) / bBox.width - 0.5;
cy += (radialReference[1] - bBox.y) / bBox.height - 0.5;
sizex *= radialReference[2] / bBox.width;
sizey *= radialReference[2] / bBox.height;
}
fillAttr = 'src="' + defaultOptions.global.VMLRadialGradientURL + '" ' +
'size="' + sizex + ',' + sizey + '" ' +
'origin="0.5,0.5" ' +
'position="' + cx + ',' + cy + '" ' +
'color2="' + color2 + '" ';
addFillNode();
};
// Apply radial gradient
if (wrapper.added) {
applyRadialGradient();
} else {
// We need to know the bounding box to get the size and position right
wrapper.onAdd = applyRadialGradient;
}
// The fill element's color attribute is broken in IE8 standards mode, so we
// need to set the parent shape's fillcolor attribute instead.
ret = color1;
}
// Gradients are not supported for VML stroke, return the first color. #722.
} else {
ret = stopColor;
}
// if the color is an rgba color, split it and add a fill node
// to hold the opacity component
} else if (regexRgba.test(color) && elem.tagName !== 'IMG') {
colorObject = Color(color);
markup = ['<', prop, ' opacity="', colorObject.get('a'), '"/>'];
createElement(this.prepVML(markup), null, null, elem);
ret = colorObject.get('rgb');
} else {
var propNodes = elem.getElementsByTagName(prop); // 'stroke' or 'fill' node
if (propNodes.length) {
propNodes[0].opacity = 1;
propNodes[0].type = 'solid';
}
ret = color;
}
return ret;
},
/**
* Take a VML string and prepare it for either IE8 or IE6/IE7.
* @param {Array} markup A string array of the VML markup to prepare
*/
prepVML: function (markup) {
var vmlStyle = 'display:inline-block;behavior:url(#default#VML);',
isIE8 = this.isIE8;
markup = markup.join('');
if (isIE8) { // add xmlns and style inline
markup = markup.replace('/>', ' xmlns="urn:schemas-microsoft-com:vml" />');
if (markup.indexOf('style="') === -1) {
markup = markup.replace('/>', ' style="' + vmlStyle + '" />');
} else {
markup = markup.replace('style="', 'style="' + vmlStyle);
}
} else { // add namespace
markup = markup.replace('<', '<hcv:');
}
return markup;
},
/**
* Create rotated and aligned text
* @param {String} str
* @param {Number} x
* @param {Number} y
*/
text: SVGRenderer.prototype.html,
/**
* Create and return a path element
* @param {Array} path
*/
path: function (path) {
var attr = {
// subpixel precision down to 0.1 (width and height = 1px)
coordsize: '10 10'
};
if (isArray(path)) {
attr.d = path;
} else if (isObject(path)) { // attributes
extend(attr, path);
}
// create the shape
return this.createElement('shape').attr(attr);
},
/**
* Create and return a circle element. In VML circles are implemented as
* shapes, which is faster than v:oval
* @param {Number} x
* @param {Number} y
* @param {Number} r
*/
circle: function (x, y, r) {
var circle = this.symbol('circle');
if (isObject(x)) {
r = x.r;
y = x.y;
x = x.x;
}
circle.isCircle = true; // Causes x and y to mean center (#1682)
circle.r = r;
return circle.attr({ x: x, y: y });
},
/**
* Create a group using an outer div and an inner v:group to allow rotating
* and flipping. A simple v:group would have problems with positioning
* child HTML elements and CSS clip.
*
* @param {String} name The name of the group
*/
g: function (name) {
var wrapper,
attribs;
// set the class name
if (name) {
attribs = { 'className': PREFIX + name, 'class': PREFIX + name };
}
// the div to hold HTML and clipping
wrapper = this.createElement(DIV).attr(attribs);
return wrapper;
},
/**
* VML override to create a regular HTML image
* @param {String} src
* @param {Number} x
* @param {Number} y
* @param {Number} width
* @param {Number} height
*/
image: function (src, x, y, width, height) {
var obj = this.createElement('img')
.attr({ src: src });
if (arguments.length > 1) {
obj.attr({
x: x,
y: y,
width: width,
height: height
});
}
return obj;
},
/**
* For rectangles, VML uses a shape for rect to overcome bugs and rotation problems
*/
createElement: function (nodeName) {
return nodeName === 'rect' ? this.symbol(nodeName) : SVGRenderer.prototype.createElement.call(this, nodeName);
},
/**
* In the VML renderer, each child of an inverted div (group) is inverted
* @param {Object} element
* @param {Object} parentNode
*/
invertChild: function (element, parentNode) {
var ren = this,
parentStyle = parentNode.style,
imgStyle = element.tagName === 'IMG' && element.style; // #1111
css(element, {
flip: 'x',
left: pInt(parentStyle.width) - (imgStyle ? pInt(imgStyle.top) : 1),
top: pInt(parentStyle.height) - (imgStyle ? pInt(imgStyle.left) : 1),
rotation: -90
});
// Recursively invert child elements, needed for nested composite shapes like box plots and error bars. #1680, #1806.
each(element.childNodes, function (child) {
ren.invertChild(child, element);
});
},
/**
* Symbol definitions that override the parent SVG renderer's symbols
*
*/
symbols: {
// VML specific arc function
arc: function (x, y, w, h, options) {
var start = options.start,
end = options.end,
radius = options.r || w || h,
innerRadius = options.innerR,
cosStart = mathCos(start),
sinStart = mathSin(start),
cosEnd = mathCos(end),
sinEnd = mathSin(end),
ret;
if (end - start === 0) { // no angle, don't show it.
return ['x'];
}
ret = [
'wa', // clockwise arc to
x - radius, // left
y - radius, // top
x + radius, // right
y + radius, // bottom
x + radius * cosStart, // start x
y + radius * sinStart, // start y
x + radius * cosEnd, // end x
y + radius * sinEnd // end y
];
if (options.open && !innerRadius) {
ret.push(
'e',
M,
x,// - innerRadius,
y// - innerRadius
);
}
ret.push(
'at', // anti clockwise arc to
x - innerRadius, // left
y - innerRadius, // top
x + innerRadius, // right
y + innerRadius, // bottom
x + innerRadius * cosEnd, // start x
y + innerRadius * sinEnd, // start y
x + innerRadius * cosStart, // end x
y + innerRadius * sinStart, // end y
'x', // finish path
'e' // close
);
ret.isArc = true;
return ret;
},
// Add circle symbol path. This performs significantly faster than v:oval.
circle: function (x, y, w, h, wrapper) {
if (wrapper) {
w = h = 2 * wrapper.r;
}
// Center correction, #1682
if (wrapper && wrapper.isCircle) {
x -= w / 2;
y -= h / 2;
}
// Return the path
return [
'wa', // clockwisearcto
x, // left
y, // top
x + w, // right
y + h, // bottom
x + w, // start x
y + h / 2, // start y
x + w, // end x
y + h / 2, // end y
//'x', // finish path
'e' // close
];
},
/**
* Add rectangle symbol path which eases rotation and omits arcsize problems
* compared to the built-in VML roundrect shape. When borders are not rounded,
* use the simpler square path, else use the callout path without the arrow.
*/
rect: function (x, y, w, h, options) {
return SVGRenderer.prototype.symbols[
!defined(options) || !options.r ? 'square' : 'callout'
].call(0, x, y, w, h, options);
}
}
};
Highcharts.VMLRenderer = VMLRenderer = function () {
this.init.apply(this, arguments);
};
VMLRenderer.prototype = merge(SVGRenderer.prototype, VMLRendererExtension);
// general renderer
Renderer = VMLRenderer;
}
// This method is used with exporting in old IE, when emulating SVG (see #2314)
SVGRenderer.prototype.measureSpanWidth = function (text, styles) {
var measuringSpan = doc.createElement('span'),
offsetWidth,
textNode = doc.createTextNode(text);
measuringSpan.appendChild(textNode);
css(measuringSpan, styles);
this.box.appendChild(measuringSpan);
offsetWidth = measuringSpan.offsetWidth;
discardElement(measuringSpan); // #2463
return offsetWidth;
};
/* ****************************************************************************
* *
* END OF INTERNET EXPLORER <= 8 SPECIFIC CODE *
* *
*****************************************************************************/
/* ****************************************************************************
* *
* START OF ANDROID < 3 SPECIFIC CODE. THIS CAN BE REMOVED IF YOU'RE NOT *
* TARGETING THAT SYSTEM. *
* *
*****************************************************************************/
var CanVGRenderer,
CanVGController;
if (useCanVG) {
/**
* The CanVGRenderer is empty from start to keep the source footprint small.
* When requested, the CanVGController downloads the rest of the source packaged
* together with the canvg library.
*/
Highcharts.CanVGRenderer = CanVGRenderer = function () {
// Override the global SVG namespace to fake SVG/HTML that accepts CSS
SVG_NS = 'http://www.w3.org/1999/xhtml';
};
/**
* Start with an empty symbols object. This is needed when exporting is used (exporting.src.js will add a few symbols), but
* the implementation from SvgRenderer will not be merged in until first render.
*/
CanVGRenderer.prototype.symbols = {};
/**
* Handles on demand download of canvg rendering support.
*/
CanVGController = (function () {
// List of renderering calls
var deferredRenderCalls = [];
/**
* When downloaded, we are ready to draw deferred charts.
*/
function drawDeferred() {
var callLength = deferredRenderCalls.length,
callIndex;
// Draw all pending render calls
for (callIndex = 0; callIndex < callLength; callIndex++) {
deferredRenderCalls[callIndex]();
}
// Clear the list
deferredRenderCalls = [];
}
return {
push: function (func, scriptLocation) {
// Only get the script once
if (deferredRenderCalls.length === 0) {
getScript(scriptLocation, drawDeferred);
}
// Register render call
deferredRenderCalls.push(func);
}
};
}());
Renderer = CanVGRenderer;
} // end CanVGRenderer
/* ****************************************************************************
* *
* END OF ANDROID < 3 SPECIFIC CODE *
* *
*****************************************************************************/
/**
* The Tick class
*/
function Tick(axis, pos, type, noLabel) {
this.axis = axis;
this.pos = pos;
this.type = type || '';
this.isNew = true;
if (!type && !noLabel) {
this.addLabel();
}
}
Tick.prototype = {
/**
* Write the tick label
*/
addLabel: function () {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
categories = axis.categories,
names = axis.names,
pos = tick.pos,
labelOptions = options.labels,
str,
tickPositions = axis.tickPositions,
isFirst = pos === tickPositions[0],
isLast = pos === tickPositions[tickPositions.length - 1],
value = categories ?
pick(categories[pos], names[pos], pos) :
pos,
label = tick.label,
tickPositionInfo = tickPositions.info,
dateTimeLabelFormat;
// Set the datetime label format. If a higher rank is set for this position, use that. If not,
// use the general format.
if (axis.isDatetimeAxis && tickPositionInfo) {
dateTimeLabelFormat = options.dateTimeLabelFormats[tickPositionInfo.higherRanks[pos] || tickPositionInfo.unitName];
}
// set properties for access in render method
tick.isFirst = isFirst;
tick.isLast = isLast;
// get the string
str = axis.labelFormatter.call({
axis: axis,
chart: chart,
isFirst: isFirst,
isLast: isLast,
dateTimeLabelFormat: dateTimeLabelFormat,
value: axis.isLog ? correctFloat(lin2log(value)) : value
});
// prepare CSS
//css = width && { width: mathMax(1, mathRound(width - 2 * (labelOptions.padding || 10))) + PX };
// first call
if (!defined(label)) {
tick.label = label =
defined(str) && labelOptions.enabled ?
chart.renderer.text(
str,
0,
0,
labelOptions.useHTML
)
//.attr(attr)
// without position absolute, IE export sometimes is wrong
.css(merge(labelOptions.style))
.add(axis.labelGroup) :
null;
tick.labelLength = label && label.getBBox().width; // Un-rotated length
tick.rotation = 0; // Base value to detect change for new calls to getBBox
// update
} else if (label) {
label.attr({ text: str });
}
},
/**
* Get the offset height or width of the label
*/
getLabelSize: function () {
return this.label ?
this.label.getBBox()[this.axis.horiz ? 'height' : 'width'] :
0;
},
/**
* Handle the label overflow by adjusting the labels to the left and right edge, or
* hide them if they collide into the neighbour label.
*/
handleOverflow: function (xy) {
var axis = this.axis,
pxPos = xy.x,
chartWidth = axis.chart.chartWidth,
spacing = axis.chart.spacing,
leftBound = pick(axis.labelLeft, spacing[3]),
rightBound = pick(axis.labelRight, chartWidth - spacing[1]),
label = this.label,
rotation = this.rotation,
factor = { left: 0, center: 0.5, right: 1 }[axis.labelAlign],
labelWidth = label.getBBox().width,
slotWidth = axis.slotWidth,
leftPos,
rightPos,
textWidth;
// Check if the label overshoots the chart spacing box. If it does, move it.
// If it now overshoots the slotWidth, add ellipsis.
if (!rotation) {
leftPos = pxPos - factor * labelWidth;
rightPos = pxPos + factor * labelWidth;
if (leftPos < leftBound) {
slotWidth -= leftBound - leftPos;
xy.x = leftBound;
label.attr({ align: 'left' });
} else if (rightPos > rightBound) {
slotWidth -= rightPos - rightBound;
xy.x = rightBound;
label.attr({ align: 'right' });
}
if (labelWidth > slotWidth) {
textWidth = slotWidth;
}
// Add ellipsis to prevent rotated labels to be clipped against the edge of the chart
} else if (rotation < 0 && pxPos - factor * labelWidth < leftBound) {
textWidth = mathRound(pxPos / mathCos(rotation * deg2rad) - leftBound);
} else if (rotation > 0 && pxPos + factor * labelWidth > rightBound) {
textWidth = mathRound((chartWidth - pxPos) / mathCos(rotation * deg2rad));
}
if (textWidth) {
label.css({
width: textWidth,
textOverflow: 'ellipsis'
});
}
},
/**
* Get the x and y position for ticks and labels
*/
getPosition: function (horiz, pos, tickmarkOffset, old) {
var axis = this.axis,
chart = axis.chart,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight;
return {
x: horiz ?
axis.translate(pos + tickmarkOffset, null, null, old) + axis.transB :
axis.left + axis.offset + (axis.opposite ? ((old && chart.oldChartWidth) || chart.chartWidth) - axis.right - axis.left : 0),
y: horiz ?
cHeight - axis.bottom + axis.offset - (axis.opposite ? axis.height : 0) :
cHeight - axis.translate(pos + tickmarkOffset, null, null, old) - axis.transB
};
},
/**
* Get the x, y position of the tick label
*/
getLabelPosition: function (x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
var axis = this.axis,
transA = axis.transA,
reversed = axis.reversed,
staggerLines = axis.staggerLines,
rotCorr = axis.tickRotCorr || { x: 0, y: 0 },
yOffset = pick(labelOptions.y, rotCorr.y + (axis.side === 2 ? 8 : -(label.getBBox().height / 2))),
line;
x = x + labelOptions.x + rotCorr.x - (tickmarkOffset && horiz ?
tickmarkOffset * transA * (reversed ? -1 : 1) : 0);
y = y + yOffset - (tickmarkOffset && !horiz ?
tickmarkOffset * transA * (reversed ? 1 : -1) : 0);
// Correct for staggered labels
if (staggerLines) {
line = (index / (step || 1) % staggerLines);
y += line * (axis.labelOffset / staggerLines);
}
return {
x: x,
y: mathRound(y)
};
},
/**
* Extendible method to return the path of the marker
*/
getMarkPath: function (x, y, tickLength, tickWidth, horiz, renderer) {
return renderer.crispLine([
M,
x,
y,
L,
x + (horiz ? 0 : -tickLength),
y + (horiz ? tickLength : 0)
], tickWidth);
},
/**
* Put everything in place
*
* @param index {Number}
* @param old {Boolean} Use old coordinates to prepare an animation into new position
*/
render: function (index, old, opacity) {
var tick = this,
axis = tick.axis,
options = axis.options,
chart = axis.chart,
renderer = chart.renderer,
horiz = axis.horiz,
type = tick.type,
label = tick.label,
pos = tick.pos,
labelOptions = options.labels,
gridLine = tick.gridLine,
gridPrefix = type ? type + 'Grid' : 'grid',
tickPrefix = type ? type + 'Tick' : 'tick',
gridLineWidth = options[gridPrefix + 'LineWidth'],
gridLineColor = options[gridPrefix + 'LineColor'],
dashStyle = options[gridPrefix + 'LineDashStyle'],
tickLength = options[tickPrefix + 'Length'],
tickWidth = options[tickPrefix + 'Width'] || 0,
tickColor = options[tickPrefix + 'Color'],
tickPosition = options[tickPrefix + 'Position'],
gridLinePath,
mark = tick.mark,
markPath,
step = /*axis.labelStep || */labelOptions.step,
attribs,
show = true,
tickmarkOffset = axis.tickmarkOffset,
xy = tick.getPosition(horiz, pos, tickmarkOffset, old),
x = xy.x,
y = xy.y,
reverseCrisp = ((horiz && x === axis.pos + axis.len) || (!horiz && y === axis.pos)) ? -1 : 1; // #1480, #1687
opacity = pick(opacity, 1);
this.isActive = true;
// create the grid line
if (gridLineWidth) {
gridLinePath = axis.getPlotLinePath(pos + tickmarkOffset, gridLineWidth * reverseCrisp, old, true);
if (gridLine === UNDEFINED) {
attribs = {
stroke: gridLineColor,
'stroke-width': gridLineWidth
};
if (dashStyle) {
attribs.dashstyle = dashStyle;
}
if (!type) {
attribs.zIndex = 1;
}
if (old) {
attribs.opacity = 0;
}
tick.gridLine = gridLine =
gridLineWidth ?
renderer.path(gridLinePath)
.attr(attribs).add(axis.gridGroup) :
null;
}
// If the parameter 'old' is set, the current call will be followed
// by another call, therefore do not do any animations this time
if (!old && gridLine && gridLinePath) {
gridLine[tick.isNew ? 'attr' : 'animate']({
d: gridLinePath,
opacity: opacity
});
}
}
// create the tick mark
if (tickWidth && tickLength) {
// negate the length
if (tickPosition === 'inside') {
tickLength = -tickLength;
}
if (axis.opposite) {
tickLength = -tickLength;
}
markPath = tick.getMarkPath(x, y, tickLength, tickWidth * reverseCrisp, horiz, renderer);
if (mark) { // updating
mark.animate({
d: markPath,
opacity: opacity
});
} else { // first time
tick.mark = renderer.path(
markPath
).attr({
stroke: tickColor,
'stroke-width': tickWidth,
opacity: opacity
}).add(axis.axisGroup);
}
}
// the label is created on init - now move it into place
if (label && !isNaN(x)) {
label.xy = xy = tick.getLabelPosition(x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
// Apply show first and show last. If the tick is both first and last, it is
// a single centered tick, in which case we show the label anyway (#2100).
if ((tick.isFirst && !tick.isLast && !pick(options.showFirstLabel, 1)) ||
(tick.isLast && !tick.isFirst && !pick(options.showLastLabel, 1))) {
show = false;
// Handle label overflow and show or hide accordingly
} else if (horiz && !axis.isRadial && !labelOptions.step && !labelOptions.rotation && !old && opacity !== 0) {
tick.handleOverflow(xy);
}
// apply step
if (step && index % step) {
// show those indices dividable by step
show = false;
}
// Set the new position, and show or hide
if (show && !isNaN(xy.y)) {
xy.opacity = opacity;
label[tick.isNew ? 'attr' : 'animate'](xy);
tick.isNew = false;
} else {
label.attr('y', -9999); // #1338
}
}
},
/**
* Destructor for the tick prototype
*/
destroy: function () {
destroyObjectProperties(this, this.axis);
}
};
/**
* Create a new axis object
* @param {Object} chart
* @param {Object} options
*/
var Axis = Highcharts.Axis = function () {
this.init.apply(this, arguments);
};
Axis.prototype = {
/**
* Default options for the X axis - the Y axis has extended defaults
*/
defaultOptions: {
// allowDecimals: null,
// alternateGridColor: null,
// categories: [],
dateTimeLabelFormats: {
millisecond: '%H:%M:%S.%L',
second: '%H:%M:%S',
minute: '%H:%M',
hour: '%H:%M',
day: '%e. %b',
week: '%e. %b',
month: '%b \'%y',
year: '%Y'
},
endOnTick: false,
gridLineColor: '#D8D8D8',
// gridLineDashStyle: 'solid',
// gridLineWidth: 0,
// reversed: false,
labels: {
enabled: true,
// rotation: 0,
// align: 'center',
// step: null,
style: {
color: '#606060',
cursor: 'default',
fontSize: '11px'
},
x: 0,
y: 15
/*formatter: function () {
return this.value;
},*/
},
lineColor: '#C0D0E0',
lineWidth: 1,
//linkedTo: null,
//max: undefined,
//min: undefined,
minPadding: 0.01,
maxPadding: 0.01,
//minRange: null,
minorGridLineColor: '#E0E0E0',
// minorGridLineDashStyle: null,
minorGridLineWidth: 1,
minorTickColor: '#A0A0A0',
//minorTickInterval: null,
minorTickLength: 2,
minorTickPosition: 'outside', // inside or outside
//minorTickWidth: 0,
//opposite: false,
//offset: 0,
//plotBands: [{
// events: {},
// zIndex: 1,
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//plotLines: [{
// events: {}
// dashStyle: {}
// zIndex:
// labels: { align, x, verticalAlign, y, style, rotation, textAlign }
//}],
//reversed: false,
// showFirstLabel: true,
// showLastLabel: true,
startOfWeek: 1,
startOnTick: false,
tickColor: '#C0D0E0',
//tickInterval: null,
tickLength: 10,
tickmarkPlacement: 'between', // on or between
tickPixelInterval: 100,
tickPosition: 'outside',
tickWidth: 1,
title: {
//text: null,
align: 'middle', // low, middle or high
//margin: 0 for horizontal, 10 for vertical axes,
//rotation: 0,
//side: 'outside',
style: {
color: '#707070'
}
//x: 0,
//y: 0
},
type: 'linear' // linear, logarithmic or datetime
},
/**
* This options set extends the defaultOptions for Y axes
*/
defaultYAxisOptions: {
endOnTick: true,
gridLineWidth: 1,
tickPixelInterval: 72,
showLastLabel: true,
labels: {
x: -8,
y: 3
},
lineWidth: 0,
maxPadding: 0.05,
minPadding: 0.05,
startOnTick: true,
tickWidth: 0,
title: {
rotation: 270,
text: 'Values'
},
stackLabels: {
enabled: false,
//align: dynamic,
//y: dynamic,
//x: dynamic,
//verticalAlign: dynamic,
//textAlign: dynamic,
//rotation: 0,
formatter: function () {
return Highcharts.numberFormat(this.total, -1);
},
style: defaultPlotOptions.line.dataLabels.style
}
},
/**
* These options extend the defaultOptions for left axes
*/
defaultLeftAxisOptions: {
labels: {
x: -15,
y: null
},
title: {
rotation: 270
}
},
/**
* These options extend the defaultOptions for right axes
*/
defaultRightAxisOptions: {
labels: {
x: 15,
y: null
},
title: {
rotation: 90
}
},
/**
* These options extend the defaultOptions for bottom axes
*/
defaultBottomAxisOptions: {
labels: {
autoRotation: [-45],
x: 0,
y: null // based on font size
// overflow: undefined,
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* These options extend the defaultOptions for top axes
*/
defaultTopAxisOptions: {
labels: {
autoRotation: [-45],
x: 0,
y: -15
// overflow: undefined
// staggerLines: null
},
title: {
rotation: 0
}
},
/**
* Initialize the axis
*/
init: function (chart, userOptions) {
var isXAxis = userOptions.isX,
axis = this;
// Flag, is the axis horizontal
axis.horiz = chart.inverted ? !isXAxis : isXAxis;
// Flag, isXAxis
axis.isXAxis = isXAxis;
axis.coll = isXAxis ? 'xAxis' : 'yAxis';
axis.opposite = userOptions.opposite; // needed in setOptions
axis.side = userOptions.side || (axis.horiz ?
(axis.opposite ? 0 : 2) : // top : bottom
(axis.opposite ? 1 : 3)); // right : left
axis.setOptions(userOptions);
var options = this.options,
type = options.type,
isDatetimeAxis = type === 'datetime';
axis.labelFormatter = options.labels.formatter || axis.defaultLabelFormatter; // can be overwritten by dynamic format
// Flag, stagger lines or not
axis.userOptions = userOptions;
//axis.axisTitleMargin = UNDEFINED,// = options.title.margin,
axis.minPixelPadding = 0;
//axis.ignoreMinPadding = UNDEFINED; // can be set to true by a column or bar series
//axis.ignoreMaxPadding = UNDEFINED;
axis.chart = chart;
axis.reversed = options.reversed;
axis.zoomEnabled = options.zoomEnabled !== false;
// Initial categories
axis.categories = options.categories || type === 'category';
axis.names = [];
// Elements
//axis.axisGroup = UNDEFINED;
//axis.gridGroup = UNDEFINED;
//axis.axisTitle = UNDEFINED;
//axis.axisLine = UNDEFINED;
// Shorthand types
axis.isLog = type === 'logarithmic';
axis.isDatetimeAxis = isDatetimeAxis;
// Flag, if axis is linked to another axis
axis.isLinked = defined(options.linkedTo);
// Linked axis.
//axis.linkedParent = UNDEFINED;
// Tick positions
//axis.tickPositions = UNDEFINED; // array containing predefined positions
// Tick intervals
//axis.tickInterval = UNDEFINED;
//axis.minorTickInterval = UNDEFINED;
// Major ticks
axis.ticks = {};
axis.labelEdge = [];
// Minor ticks
axis.minorTicks = {};
// List of plotLines/Bands
axis.plotLinesAndBands = [];
// Alternate bands
axis.alternateBands = {};
// Axis metrics
//axis.left = UNDEFINED;
//axis.top = UNDEFINED;
//axis.width = UNDEFINED;
//axis.height = UNDEFINED;
//axis.bottom = UNDEFINED;
//axis.right = UNDEFINED;
//axis.transA = UNDEFINED;
//axis.transB = UNDEFINED;
//axis.oldTransA = UNDEFINED;
axis.len = 0;
//axis.oldMin = UNDEFINED;
//axis.oldMax = UNDEFINED;
//axis.oldUserMin = UNDEFINED;
//axis.oldUserMax = UNDEFINED;
//axis.oldAxisLength = UNDEFINED;
axis.minRange = axis.userMinRange = options.minRange || options.maxZoom;
axis.range = options.range;
axis.offset = options.offset || 0;
// Dictionary for stacks
axis.stacks = {};
axis.oldStacks = {};
// Min and max in the data
//axis.dataMin = UNDEFINED,
//axis.dataMax = UNDEFINED,
// The axis range
axis.max = null;
axis.min = null;
// User set min and max
//axis.userMin = UNDEFINED,
//axis.userMax = UNDEFINED,
// Crosshair options
axis.crosshair = pick(options.crosshair, splat(chart.options.tooltip.crosshairs)[isXAxis ? 0 : 1], false);
// Run Axis
var eventType,
events = axis.options.events;
// Register
if (inArray(axis, chart.axes) === -1) { // don't add it again on Axis.update()
if (isXAxis && !this.isColorAxis) { // #2713
chart.axes.splice(chart.xAxis.length, 0, axis);
} else {
chart.axes.push(axis);
}
chart[axis.coll].push(axis);
}
axis.series = axis.series || []; // populated by Series
// inverted charts have reversed xAxes as default
if (chart.inverted && isXAxis && axis.reversed === UNDEFINED) {
axis.reversed = true;
}
axis.removePlotBand = axis.removePlotBandOrLine;
axis.removePlotLine = axis.removePlotBandOrLine;
// register event listeners
for (eventType in events) {
addEvent(axis, eventType, events[eventType]);
}
// extend logarithmic axis
if (axis.isLog) {
axis.val2lin = log2lin;
axis.lin2val = lin2log;
}
},
/**
* Merge and set options
*/
setOptions: function (userOptions) {
this.options = merge(
this.defaultOptions,
this.isXAxis ? {} : this.defaultYAxisOptions,
[this.defaultTopAxisOptions, this.defaultRightAxisOptions,
this.defaultBottomAxisOptions, this.defaultLeftAxisOptions][this.side],
merge(
defaultOptions[this.coll], // if set in setOptions (#1053)
userOptions
)
);
},
/**
* The default label formatter. The context is a special config object for the label.
*/
defaultLabelFormatter: function () {
var axis = this.axis,
value = this.value,
categories = axis.categories,
dateTimeLabelFormat = this.dateTimeLabelFormat,
numericSymbols = defaultOptions.lang.numericSymbols,
i = numericSymbols && numericSymbols.length,
multi,
ret,
formatOption = axis.options.labels.format,
// make sure the same symbol is added for all labels on a linear axis
numericSymbolDetector = axis.isLog ? value : axis.tickInterval;
if (formatOption) {
ret = format(formatOption, this);
} else if (categories) {
ret = value;
} else if (dateTimeLabelFormat) { // datetime axis
ret = dateFormat(dateTimeLabelFormat, value);
} else if (i && numericSymbolDetector >= 1000) {
// Decide whether we should add a numeric symbol like k (thousands) or M (millions).
// If we are to enable this in tooltip or other places as well, we can move this
// logic to the numberFormatter and enable it by a parameter.
while (i-- && ret === UNDEFINED) {
multi = Math.pow(1000, i + 1);
if (numericSymbolDetector >= multi && numericSymbols[i] !== null) {
ret = Highcharts.numberFormat(value / multi, -1) + numericSymbols[i];
}
}
}
if (ret === UNDEFINED) {
if (mathAbs(value) >= 10000) { // add thousands separators
ret = Highcharts.numberFormat(value, 0);
} else { // small numbers
ret = Highcharts.numberFormat(value, -1, UNDEFINED, ''); // #2466
}
}
return ret;
},
/**
* Get the minimum and maximum for the series of each axis
*/
getSeriesExtremes: function () {
var axis = this,
chart = axis.chart;
axis.hasVisibleSeries = false;
// Reset properties in case we're redrawing (#3353)
axis.dataMin = axis.dataMax = axis.ignoreMinPadding = axis.ignoreMaxPadding = null;
if (axis.buildStacks) {
axis.buildStacks();
}
// loop through this axis' series
each(axis.series, function (series) {
if (series.visible || !chart.options.chart.ignoreHiddenSeries) {
var seriesOptions = series.options,
xData,
threshold = seriesOptions.threshold,
seriesDataMin,
seriesDataMax;
axis.hasVisibleSeries = true;
// Validate threshold in logarithmic axes
if (axis.isLog && threshold <= 0) {
threshold = null;
}
// Get dataMin and dataMax for X axes
if (axis.isXAxis) {
xData = series.xData;
if (xData.length) {
axis.dataMin = mathMin(pick(axis.dataMin, xData[0]), arrayMin(xData));
axis.dataMax = mathMax(pick(axis.dataMax, xData[0]), arrayMax(xData));
}
// Get dataMin and dataMax for Y axes, as well as handle stacking and processed data
} else {
// Get this particular series extremes
series.getExtremes();
seriesDataMax = series.dataMax;
seriesDataMin = series.dataMin;
// Get the dataMin and dataMax so far. If percentage is used, the min and max are
// always 0 and 100. If seriesDataMin and seriesDataMax is null, then series
// doesn't have active y data, we continue with nulls
if (defined(seriesDataMin) && defined(seriesDataMax)) {
axis.dataMin = mathMin(pick(axis.dataMin, seriesDataMin), seriesDataMin);
axis.dataMax = mathMax(pick(axis.dataMax, seriesDataMax), seriesDataMax);
}
// Adjust to threshold
if (defined(threshold)) {
if (axis.dataMin >= threshold) {
axis.dataMin = threshold;
axis.ignoreMinPadding = true;
} else if (axis.dataMax < threshold) {
axis.dataMax = threshold;
axis.ignoreMaxPadding = true;
}
}
}
}
});
},
/**
* Translate from axis value to pixel position on the chart, or back
*
*/
translate: function (val, backwards, cvsCoord, old, handleLog, pointPlacement) {
var axis = this,
sign = 1,
cvsOffset = 0,
localA = old ? axis.oldTransA : axis.transA,
localMin = old ? axis.oldMin : axis.min,
returnValue,
minPixelPadding = axis.minPixelPadding,
postTranslate = (axis.postTranslate || (axis.isLog && handleLog)) && axis.lin2val;
if (!localA) {
localA = axis.transA;
}
// In vertical axes, the canvas coordinates start from 0 at the top like in
// SVG.
if (cvsCoord) {
sign *= -1; // canvas coordinates inverts the value
cvsOffset = axis.len;
}
// Handle reversed axis
if (axis.reversed) {
sign *= -1;
cvsOffset -= sign * (axis.sector || axis.len);
}
// From pixels to value
if (backwards) { // reverse translation
val = val * sign + cvsOffset;
val -= minPixelPadding;
returnValue = val / localA + localMin; // from chart pixel to value
if (postTranslate) { // log and ordinal axes
returnValue = axis.lin2val(returnValue);
}
// From value to pixels
} else {
if (postTranslate) { // log and ordinal axes
val = axis.val2lin(val);
}
if (pointPlacement === 'between') {
pointPlacement = 0.5;
}
returnValue = sign * (val - localMin) * localA + cvsOffset + (sign * minPixelPadding) +
(isNumber(pointPlacement) ? localA * pointPlacement * axis.pointRange : 0);
}
return returnValue;
},
/**
* Utility method to translate an axis value to pixel position.
* @param {Number} value A value in terms of axis units
* @param {Boolean} paneCoordinates Whether to return the pixel coordinate relative to the chart
* or just the axis/pane itself.
*/
toPixels: function (value, paneCoordinates) {
return this.translate(value, false, !this.horiz, null, true) + (paneCoordinates ? 0 : this.pos);
},
/*
* Utility method to translate a pixel position in to an axis value
* @param {Number} pixel The pixel value coordinate
* @param {Boolean} paneCoordiantes Whether the input pixel is relative to the chart or just the
* axis/pane itself.
*/
toValue: function (pixel, paneCoordinates) {
return this.translate(pixel - (paneCoordinates ? 0 : this.pos), true, !this.horiz, null, true);
},
/**
* Create the path for a plot line that goes from the given value on
* this axis, across the plot to the opposite side
* @param {Number} value
* @param {Number} lineWidth Used for calculation crisp line
* @param {Number] old Use old coordinates (for resizing and rescaling)
*/
getPlotLinePath: function (value, lineWidth, old, force, translatedValue) {
var axis = this,
chart = axis.chart,
axisLeft = axis.left,
axisTop = axis.top,
x1,
y1,
x2,
y2,
cHeight = (old && chart.oldChartHeight) || chart.chartHeight,
cWidth = (old && chart.oldChartWidth) || chart.chartWidth,
skip,
transB = axis.transB,
/**
* Check if x is between a and b. If not, either move to a/b or skip,
* depending on the force parameter.
*/
between = function (x, a, b) {
if (x < a || x > b) {
if (force) {
x = mathMin(mathMax(a, x), b);
} else {
skip = true;
}
}
return x;
};
translatedValue = pick(translatedValue, axis.translate(value, null, null, old));
x1 = x2 = mathRound(translatedValue + transB);
y1 = y2 = mathRound(cHeight - translatedValue - transB);
if (isNaN(translatedValue)) { // no min or max
skip = true;
} else if (axis.horiz) {
y1 = axisTop;
y2 = cHeight - axis.bottom;
x1 = x2 = between(x1, axisLeft, axisLeft + axis.width);
} else {
x1 = axisLeft;
x2 = cWidth - axis.right;
y1 = y2 = between(y1, axisTop, axisTop + axis.height);
}
return skip && !force ?
null :
chart.renderer.crispLine([M, x1, y1, L, x2, y2], lineWidth || 1);
},
/**
* Set the tick positions of a linear axis to round values like whole tens or every five.
*/
getLinearTickPositions: function (tickInterval, min, max) {
var pos,
lastPos,
roundedMin = correctFloat(mathFloor(min / tickInterval) * tickInterval),
roundedMax = correctFloat(mathCeil(max / tickInterval) * tickInterval),
tickPositions = [];
// For single points, add a tick regardless of the relative position (#2662)
if (min === max && isNumber(min)) {
return [min];
}
// Populate the intermediate values
pos = roundedMin;
while (pos <= roundedMax) {
// Place the tick on the rounded value
tickPositions.push(pos);
// Always add the raw tickInterval, not the corrected one.
pos = correctFloat(pos + tickInterval);
// If the interval is not big enough in the current min - max range to actually increase
// the loop variable, we need to break out to prevent endless loop. Issue #619
if (pos === lastPos) {
break;
}
// Record the last value
lastPos = pos;
}
return tickPositions;
},
/**
* Return the minor tick positions. For logarithmic axes, reuse the same logic
* as for major ticks.
*/
getMinorTickPositions: function () {
var axis = this,
options = axis.options,
tickPositions = axis.tickPositions,
minorTickInterval = axis.minorTickInterval,
minorTickPositions = [],
pos,
i,
min = axis.min,
max = axis.max,
len;
// If minor ticks get too dense, they are hard to read, and may cause long running script. So we don't draw them.
if ((max - min) / minorTickInterval < axis.len / 3) {
if (axis.isLog) {
len = tickPositions.length;
for (i = 1; i < len; i++) {
minorTickPositions = minorTickPositions.concat(
axis.getLogTickPositions(minorTickInterval, tickPositions[i - 1], tickPositions[i], true)
);
}
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
min,
max,
options.startOfWeek
)
);
} else if (axis.isDatetimeAxis && options.minorTickInterval === 'auto') { // #1314
minorTickPositions = minorTickPositions.concat(
axis.getTimeTicks(
axis.normalizeTimeTickInterval(minorTickInterval),
axis.min,
axis.max,
options.startOfWeek
)
);
} else {
for (pos = axis.min + (tickPositions[0] - axis.min) % minorTickInterval; pos <= axis.max; pos += minorTickInterval) {
minorTickPositions.push(pos);
}
}
}
axis.trimTicks(minorTickPositions); // #3652 #3743
return minorTickPositions;
},
/**
* Adjust the min and max for the minimum range. Keep in mind that the series data is
* not yet processed, so we don't have information on data cropping and grouping, or
* updated axis.pointRange or series.pointRange. The data can't be processed until
* we have finally established min and max.
*/
adjustForMinRange: function () {
var axis = this,
options = axis.options,
min = axis.min,
max = axis.max,
zoomOffset,
spaceAvailable = axis.dataMax - axis.dataMin >= axis.minRange,
closestDataRange,
i,
distance,
xData,
loopLength,
minArgs,
maxArgs;
// Set the automatic minimum range based on the closest point distance
if (axis.isXAxis && axis.minRange === UNDEFINED && !axis.isLog) {
if (defined(options.min) || defined(options.max)) {
axis.minRange = null; // don't do this again
} else {
// Find the closest distance between raw data points, as opposed to
// closestPointRange that applies to processed points (cropped and grouped)
each(axis.series, function (series) {
xData = series.xData;
loopLength = series.xIncrement ? 1 : xData.length - 1;
for (i = loopLength; i > 0; i--) {
distance = xData[i] - xData[i - 1];
if (closestDataRange === UNDEFINED || distance < closestDataRange) {
closestDataRange = distance;
}
}
});
axis.minRange = mathMin(closestDataRange * 5, axis.dataMax - axis.dataMin);
}
}
// if minRange is exceeded, adjust
if (max - min < axis.minRange) {
var minRange = axis.minRange;
zoomOffset = (minRange - max + min) / 2;
// if min and max options have been set, don't go beyond it
minArgs = [min - zoomOffset, pick(options.min, min - zoomOffset)];
if (spaceAvailable) { // if space is available, stay within the data range
minArgs[2] = axis.dataMin;
}
min = arrayMax(minArgs);
maxArgs = [min + minRange, pick(options.max, min + minRange)];
if (spaceAvailable) { // if space is availabe, stay within the data range
maxArgs[2] = axis.dataMax;
}
max = arrayMin(maxArgs);
// now if the max is adjusted, adjust the min back
if (max - min < minRange) {
minArgs[0] = max - minRange;
minArgs[1] = pick(options.min, max - minRange);
min = arrayMax(minArgs);
}
}
// Record modified extremes
axis.min = min;
axis.max = max;
},
/**
* Update translation information
*/
setAxisTranslation: function (saveOld) {
var axis = this,
range = axis.max - axis.min,
pointRange = axis.axisPointRange || 0,
closestPointRange,
minPointOffset = 0,
pointRangePadding = 0,
linkedParent = axis.linkedParent,
ordinalCorrection,
hasCategories = !!axis.categories,
transA = axis.transA;
// Adjust translation for padding. Y axis with categories need to go through the same (#1784).
if (axis.isXAxis || hasCategories || pointRange) {
if (linkedParent) {
minPointOffset = linkedParent.minPointOffset;
pointRangePadding = linkedParent.pointRangePadding;
} else {
each(axis.series, function (series) {
var seriesPointRange = hasCategories ? 1 : (axis.isXAxis ? series.pointRange : (axis.axisPointRange || 0)), // #2806
pointPlacement = series.options.pointPlacement,
seriesClosestPointRange = series.closestPointRange;
if (seriesPointRange > range) { // #1446
seriesPointRange = 0;
}
pointRange = mathMax(pointRange, seriesPointRange);
if (!axis.single) {
// minPointOffset is the value padding to the left of the axis in order to make
// room for points with a pointRange, typically columns. When the pointPlacement option
// is 'between' or 'on', this padding does not apply.
minPointOffset = mathMax(
minPointOffset,
isString(pointPlacement) ? 0 : seriesPointRange / 2
);
// Determine the total padding needed to the length of the axis to make room for the
// pointRange. If the series' pointPlacement is 'on', no padding is added.
pointRangePadding = mathMax(
pointRangePadding,
pointPlacement === 'on' ? 0 : seriesPointRange
);
}
// Set the closestPointRange
if (!series.noSharedTooltip && defined(seriesClosestPointRange)) {
closestPointRange = defined(closestPointRange) ?
mathMin(closestPointRange, seriesClosestPointRange) :
seriesClosestPointRange;
}
});
}
// Record minPointOffset and pointRangePadding
ordinalCorrection = axis.ordinalSlope && closestPointRange ? axis.ordinalSlope / closestPointRange : 1; // #988, #1853
axis.minPointOffset = minPointOffset = minPointOffset * ordinalCorrection;
axis.pointRangePadding = pointRangePadding = pointRangePadding * ordinalCorrection;
// pointRange means the width reserved for each point, like in a column chart
axis.pointRange = mathMin(pointRange, range);
// closestPointRange means the closest distance between points. In columns
// it is mostly equal to pointRange, but in lines pointRange is 0 while closestPointRange
// is some other value
axis.closestPointRange = closestPointRange;
}
// Secondary values
if (saveOld) {
axis.oldTransA = transA;
}
axis.translationSlope = axis.transA = transA = axis.len / ((range + pointRangePadding) || 1);
axis.transB = axis.horiz ? axis.left : axis.bottom; // translation addend
axis.minPixelPadding = transA * minPointOffset;
},
/**
* Set the tick positions to round values and optionally extend the extremes
* to the nearest tick
*/
setTickInterval: function (secondPass) {
var axis = this,
chart = axis.chart,
options = axis.options,
isLog = axis.isLog,
isDatetimeAxis = axis.isDatetimeAxis,
isXAxis = axis.isXAxis,
isLinked = axis.isLinked,
maxPadding = options.maxPadding,
minPadding = options.minPadding,
length,
linkedParentExtremes,
tickIntervalOption = options.tickInterval,
minTickInterval,
tickPixelIntervalOption = options.tickPixelInterval,
categories = axis.categories;
if (!isDatetimeAxis && !categories && !isLinked) {
this.getTickAmount();
}
// linked axis gets the extremes from the parent axis
if (isLinked) {
axis.linkedParent = chart[axis.coll][options.linkedTo];
linkedParentExtremes = axis.linkedParent.getExtremes();
axis.min = pick(linkedParentExtremes.min, linkedParentExtremes.dataMin);
axis.max = pick(linkedParentExtremes.max, linkedParentExtremes.dataMax);
if (options.type !== axis.linkedParent.options.type) {
error(11, 1); // Can't link axes of different type
}
} else { // initial min and max from the extreme data values
axis.min = pick(axis.userMin, options.min, axis.dataMin);
axis.max = pick(axis.userMax, options.max, axis.dataMax);
}
if (isLog) {
if (!secondPass && mathMin(axis.min, pick(axis.dataMin, axis.min)) <= 0) { // #978
error(10, 1); // Can't plot negative values on log axis
}
axis.min = correctFloat(log2lin(axis.min)); // correctFloat cures #934
axis.max = correctFloat(log2lin(axis.max));
}
// handle zoomed range
if (axis.range && defined(axis.max)) {
axis.userMin = axis.min = mathMax(axis.min, axis.max - axis.range); // #618
axis.userMax = axis.max;
axis.range = null; // don't use it when running setExtremes
}
// Hook for adjusting this.min and this.max. Used by bubble series.
if (axis.beforePadding) {
axis.beforePadding();
}
// adjust min and max for the minimum range
axis.adjustForMinRange();
// Pad the values to get clear of the chart's edges. To avoid tickInterval taking the padding
// into account, we do this after computing tick interval (#1337).
if (!categories && !axis.axisPointRange && !axis.usePercentage && !isLinked && defined(axis.min) && defined(axis.max)) {
length = axis.max - axis.min;
if (length) {
if (!defined(options.min) && !defined(axis.userMin) && minPadding && (axis.dataMin < 0 || !axis.ignoreMinPadding)) {
axis.min -= length * minPadding;
}
if (!defined(options.max) && !defined(axis.userMax) && maxPadding && (axis.dataMax > 0 || !axis.ignoreMaxPadding)) {
axis.max += length * maxPadding;
}
}
}
// Stay within floor and ceiling
if (isNumber(options.floor)) {
axis.min = mathMax(axis.min, options.floor);
}
if (isNumber(options.ceiling)) {
axis.max = mathMin(axis.max, options.ceiling);
}
// get tickInterval
if (axis.min === axis.max || axis.min === undefined || axis.max === undefined) {
axis.tickInterval = 1;
} else if (isLinked && !tickIntervalOption &&
tickPixelIntervalOption === axis.linkedParent.options.tickPixelInterval) {
axis.tickInterval = axis.linkedParent.tickInterval;
} else {
axis.tickInterval = pick(
tickIntervalOption,
this.tickAmount ? ((axis.max - axis.min) / mathMax(this.tickAmount - 1, 1)) : undefined,
categories ? // for categoried axis, 1 is default, for linear axis use tickPix
1 :
// don't let it be more than the data range
(axis.max - axis.min) * tickPixelIntervalOption / mathMax(axis.len, tickPixelIntervalOption)
);
}
// Now we're finished detecting min and max, crop and group series data. This
// is in turn needed in order to find tick positions in ordinal axes.
if (isXAxis && !secondPass) {
each(axis.series, function (series) {
series.processData(axis.min !== axis.oldMin || axis.max !== axis.oldMax);
});
}
// set the translation factor used in translate function
axis.setAxisTranslation(true);
// hook for ordinal axes and radial axes
if (axis.beforeSetTickPositions) {
axis.beforeSetTickPositions();
}
// hook for extensions, used in Highstock ordinal axes
if (axis.postProcessTickInterval) {
axis.tickInterval = axis.postProcessTickInterval(axis.tickInterval);
}
// In column-like charts, don't cramp in more ticks than there are points (#1943)
if (axis.pointRange) {
axis.tickInterval = mathMax(axis.pointRange, axis.tickInterval);
}
// Before normalizing the tick interval, handle minimum tick interval. This applies only if tickInterval is not defined.
minTickInterval = pick(options.minTickInterval, axis.isDatetimeAxis && axis.closestPointRange);
if (!tickIntervalOption && axis.tickInterval < minTickInterval) {
axis.tickInterval = minTickInterval;
}
// for linear axes, get magnitude and normalize the interval
if (!isDatetimeAxis && !isLog) { // linear
if (!tickIntervalOption) {
axis.tickInterval = normalizeTickInterval(
axis.tickInterval,
null,
getMagnitude(axis.tickInterval),
// If the tick interval is between 0.5 and 5 and the axis max is in the order of
// thousands, chances are we are dealing with years. Don't allow decimals. #3363.
pick(options.allowDecimals, !(axis.tickInterval > 0.5 && axis.tickInterval < 5 && axis.max > 1000 && axis.max < 9999)),
!!this.tickAmount
);
}
}
// Prevent ticks from getting so close that we can't draw the labels
if (!this.tickAmount && this.len) { // Color axis with disabled legend has no length
axis.tickInterval = axis.unsquish();
}
this.setTickPositions();
},
/**
* Now we have computed the normalized tickInterval, get the tick positions
*/
setTickPositions: function () {
var options = this.options,
tickPositions,
tickPositionsOption = options.tickPositions,
tickPositioner = options.tickPositioner,
startOnTick = options.startOnTick,
endOnTick = options.endOnTick,
single;
// Set the tickmarkOffset
this.tickmarkOffset = (this.categories && options.tickmarkPlacement === 'between' &&
this.tickInterval === 1) ? 0.5 : 0; // #3202
// get minorTickInterval
this.minorTickInterval = options.minorTickInterval === 'auto' && this.tickInterval ?
this.tickInterval / 5 : options.minorTickInterval;
// Find the tick positions
this.tickPositions = tickPositions = options.tickPositions && options.tickPositions.slice(); // Work on a copy (#1565)
if (!tickPositions) {
if (this.isDatetimeAxis) {
tickPositions = this.getTimeTicks(
this.normalizeTimeTickInterval(this.tickInterval, options.units),
this.min,
this.max,
options.startOfWeek,
this.ordinalPositions,
this.closestPointRange,
true
);
} else if (this.isLog) {
tickPositions = this.getLogTickPositions(this.tickInterval, this.min, this.max);
} else {
tickPositions = this.getLinearTickPositions(this.tickInterval, this.min, this.max);
}
this.tickPositions = tickPositions;
// Run the tick positioner callback, that allows modifying auto tick positions.
if (tickPositioner) {
tickPositioner = tickPositioner.apply(this, [this.min, this.max]);
if (tickPositioner) {
this.tickPositions = tickPositions = tickPositioner;
}
}
}
if (!this.isLinked) {
// reset min/max or remove extremes based on start/end on tick
this.trimTicks(tickPositions, startOnTick, endOnTick);
// When there is only one point, or all points have the same value on this axis, then min
// and max are equal and tickPositions.length is 0 or 1. In this case, add some padding
// in order to center the point, but leave it with one tick. #1337.
if (this.min === this.max && defined(this.min) && !this.tickAmount) {
// Substract half a unit (#2619, #2846, #2515, #3390)
single = true;
this.min -= 0.5;
this.max += 0.5;
}
this.single = single;
if (!tickPositionsOption && !tickPositioner) {
this.adjustTickAmount();
}
}
},
/**
* Handle startOnTick and endOnTick by either adapting to padding min/max or rounded min/max
*/
trimTicks: function (tickPositions, startOnTick, endOnTick) {
var roundedMin = tickPositions[0],
roundedMax = tickPositions[tickPositions.length - 1],
minPointOffset = this.minPointOffset || 0;
if (startOnTick) {
this.min = roundedMin;
} else if (this.min - minPointOffset > roundedMin) {
tickPositions.shift();
}
if (endOnTick) {
this.max = roundedMax;
} else if (this.max + minPointOffset < roundedMax) {
tickPositions.pop();
}
// If no tick are left, set one tick in the middle (#3195)
if (tickPositions.length === 0 && defined(roundedMin)) {
tickPositions.push((roundedMax + roundedMin) / 2);
}
},
/**
* Set the max ticks of either the x and y axis collection
*/
getTickAmount: function () {
var others = {}, // Whether there is another axis to pair with this one
hasOther,
options = this.options,
tickAmount = options.tickAmount,
tickPixelInterval = options.tickPixelInterval;
if (!defined(options.tickInterval) && this.len < tickPixelInterval && !this.isRadial &&
!this.isLog && options.startOnTick && options.endOnTick) {
tickAmount = 2;
}
if (!tickAmount && this.chart.options.chart.alignTicks !== false && options.alignTicks !== false) {
// Check if there are multiple axes in the same pane
each(this.chart[this.coll], function (axis) {
var options = axis.options,
horiz = axis.horiz,
key = [horiz ? options.left : options.top, horiz ? options.width : options.height, options.pane].join(',');
if (others[key]) {
hasOther = true;
} else {
others[key] = 1;
}
});
if (hasOther) {
// Add 1 because 4 tick intervals require 5 ticks (including first and last)
tickAmount = mathCeil(this.len / tickPixelInterval) + 1;
}
}
// For tick amounts of 2 and 3, compute five ticks and remove the intermediate ones. This
// prevents the axis from adding ticks that are too far away from the data extremes.
if (tickAmount < 4) {
this.finalTickAmt = tickAmount;
tickAmount = 5;
}
this.tickAmount = tickAmount;
},
/**
* When using multiple axes, adjust the number of ticks to match the highest
* number of ticks in that group
*/
adjustTickAmount: function () {
var tickInterval = this.tickInterval,
tickPositions = this.tickPositions,
tickAmount = this.tickAmount,
finalTickAmt = this.finalTickAmt,
currentTickAmount = tickPositions && tickPositions.length,
i,
len;
if (currentTickAmount < tickAmount) { // TODO: Check #3411
while (tickPositions.length < tickAmount) {
tickPositions.push(correctFloat(
tickPositions[tickPositions.length - 1] + tickInterval
));
}
this.transA *= (currentTickAmount - 1) / (tickAmount - 1);
this.max = tickPositions[tickPositions.length - 1];
// We have too many ticks, run second pass to try to reduce ticks
} else if (currentTickAmount > tickAmount) {
this.tickInterval *= 2;
this.setTickPositions();
}
// The finalTickAmt property is set in getTickAmount
if (defined(finalTickAmt)) {
i = len = tickPositions.length;
while (i--) {
if (
(finalTickAmt === 3 && i % 2 === 1) || // Remove every other tick
(finalTickAmt <= 2 && i > 0 && i < len - 1) // Remove all but first and last
) {
tickPositions.splice(i, 1);
}
}
this.finalTickAmt = UNDEFINED;
}
},
/**
* Set the scale based on data min and max, user set min and max or options
*
*/
setScale: function () {
var axis = this,
stacks = axis.stacks,
type,
i,
isDirtyData,
isDirtyAxisLength;
axis.oldMin = axis.min;
axis.oldMax = axis.max;
axis.oldAxisLength = axis.len;
// set the new axisLength
axis.setAxisSize();
//axisLength = horiz ? axisWidth : axisHeight;
isDirtyAxisLength = axis.len !== axis.oldAxisLength;
// is there new data?
each(axis.series, function (series) {
if (series.isDirtyData || series.isDirty ||
series.xAxis.isDirty) { // when x axis is dirty, we need new data extremes for y as well
isDirtyData = true;
}
});
// do we really need to go through all this?
if (isDirtyAxisLength || isDirtyData || axis.isLinked || axis.forceRedraw ||
axis.userMin !== axis.oldUserMin || axis.userMax !== axis.oldUserMax) {
// reset stacks
if (!axis.isXAxis) {
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].total = null;
stacks[type][i].cum = 0;
}
}
}
axis.forceRedraw = false;
// get data extremes if needed
axis.getSeriesExtremes();
// get fixed positions based on tickInterval
axis.setTickInterval();
// record old values to decide whether a rescale is necessary later on (#540)
axis.oldUserMin = axis.userMin;
axis.oldUserMax = axis.userMax;
// Mark as dirty if it is not already set to dirty and extremes have changed. #595.
if (!axis.isDirty) {
axis.isDirty = isDirtyAxisLength || axis.min !== axis.oldMin || axis.max !== axis.oldMax;
}
} else if (!axis.isXAxis) {
if (axis.oldStacks) {
stacks = axis.stacks = axis.oldStacks;
}
// reset stacks
for (type in stacks) {
for (i in stacks[type]) {
stacks[type][i].cum = stacks[type][i].total;
}
}
}
},
/**
* Set the extremes and optionally redraw
* @param {Number} newMin
* @param {Number} newMax
* @param {Boolean} redraw
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
* @param {Object} eventArguments
*
*/
setExtremes: function (newMin, newMax, redraw, animation, eventArguments) {
var axis = this,
chart = axis.chart;
redraw = pick(redraw, true); // defaults to true
// Extend the arguments with min and max
eventArguments = extend(eventArguments, {
min: newMin,
max: newMax
});
// Fire the event
fireEvent(axis, 'setExtremes', eventArguments, function () { // the default event handler
axis.userMin = newMin;
axis.userMax = newMax;
axis.eventArgs = eventArguments;
// Mark for running afterSetExtremes
axis.isDirtyExtremes = true;
// redraw
if (redraw) {
chart.redraw(animation);
}
});
},
/**
* Overridable method for zooming chart. Pulled out in a separate method to allow overriding
* in stock charts.
*/
zoom: function (newMin, newMax) {
var dataMin = this.dataMin,
dataMax = this.dataMax,
options = this.options;
// Prevent pinch zooming out of range. Check for defined is for #1946. #1734.
if (!this.allowZoomOutside) {
if (defined(dataMin) && newMin <= mathMin(dataMin, pick(options.min, dataMin))) {
newMin = UNDEFINED;
}
if (defined(dataMax) && newMax >= mathMax(dataMax, pick(options.max, dataMax))) {
newMax = UNDEFINED;
}
}
// In full view, displaying the reset zoom button is not required
this.displayBtn = newMin !== UNDEFINED || newMax !== UNDEFINED;
// Do it
this.setExtremes(
newMin,
newMax,
false,
UNDEFINED,
{ trigger: 'zoom' }
);
return true;
},
/**
* Update the axis metrics
*/
setAxisSize: function () {
var chart = this.chart,
options = this.options,
offsetLeft = options.offsetLeft || 0,
offsetRight = options.offsetRight || 0,
horiz = this.horiz,
width = pick(options.width, chart.plotWidth - offsetLeft + offsetRight),
height = pick(options.height, chart.plotHeight),
top = pick(options.top, chart.plotTop),
left = pick(options.left, chart.plotLeft + offsetLeft),
percentRegex = /%$/;
// Check for percentage based input values
if (percentRegex.test(height)) {
height = parseFloat(height) / 100 * chart.plotHeight;
}
if (percentRegex.test(top)) {
top = parseFloat(top) / 100 * chart.plotHeight + chart.plotTop;
}
// Expose basic values to use in Series object and navigator
this.left = left;
this.top = top;
this.width = width;
this.height = height;
this.bottom = chart.chartHeight - height - top;
this.right = chart.chartWidth - width - left;
// Direction agnostic properties
this.len = mathMax(horiz ? width : height, 0); // mathMax fixes #905
this.pos = horiz ? left : top; // distance from SVG origin
},
/**
* Get the actual axis extremes
*/
getExtremes: function () {
var axis = this,
isLog = axis.isLog;
return {
min: isLog ? correctFloat(lin2log(axis.min)) : axis.min,
max: isLog ? correctFloat(lin2log(axis.max)) : axis.max,
dataMin: axis.dataMin,
dataMax: axis.dataMax,
userMin: axis.userMin,
userMax: axis.userMax
};
},
/**
* Get the zero plane either based on zero or on the min or max value.
* Used in bar and area plots
*/
getThreshold: function (threshold) {
var axis = this,
isLog = axis.isLog;
var realMin = isLog ? lin2log(axis.min) : axis.min,
realMax = isLog ? lin2log(axis.max) : axis.max;
if (realMin > threshold || threshold === null) {
threshold = realMin;
} else if (realMax < threshold) {
threshold = realMax;
}
return axis.translate(threshold, 0, 1, 0, 1);
},
/**
* Compute auto alignment for the axis label based on which side the axis is on
* and the given rotation for the label
*/
autoLabelAlign: function (rotation) {
var ret,
angle = (pick(rotation, 0) - (this.side * 90) + 720) % 360;
if (angle > 15 && angle < 165) {
ret = 'right';
} else if (angle > 195 && angle < 345) {
ret = 'left';
} else {
ret = 'center';
}
return ret;
},
/**
* Prevent the ticks from getting so close we can't draw the labels. On a horizontal
* axis, this is handled by rotating the labels, removing ticks and adding ellipsis.
* On a vertical axis remove ticks and add ellipsis.
*/
unsquish: function () {
var chart = this.chart,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
tickInterval = this.tickInterval,
newTickInterval = tickInterval,
slotSize = this.len / (((this.categories ? 1 : 0) + this.max - this.min) / tickInterval),
rotation,
rotationOption = labelOptions.rotation,
labelMetrics = chart.renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
step,
bestScore = Number.MAX_VALUE,
autoRotation,
// Return the multiple of tickInterval that is needed to avoid collision
getStep = function (spaceNeeded) {
var step = spaceNeeded / (slotSize || 1);
step = step > 1 ? mathCeil(step) : 1;
return step * tickInterval;
};
if (horiz) {
autoRotation = defined(rotationOption) ?
[rotationOption] :
slotSize < 80 && !labelOptions.staggerLines && !labelOptions.step && labelOptions.autoRotation;
if (autoRotation) {
// Loop over the given autoRotation options, and determine which gives the best score. The
// best score is that with the lowest number of steps and a rotation closest to horizontal.
each(autoRotation, function (rot) {
var score;
if (rot && rot >= -90 && rot <= 90) {
step = getStep(mathAbs(labelMetrics.h / mathSin(deg2rad * rot)));
score = step + mathAbs(rot / 360);
if (score < bestScore) {
bestScore = score;
rotation = rot;
newTickInterval = step;
}
}
});
}
} else {
newTickInterval = getStep(labelMetrics.h);
}
this.autoRotation = autoRotation;
this.labelRotation = rotation;
return newTickInterval;
},
renderUnsquish: function () {
var chart = this.chart,
renderer = chart.renderer,
tickPositions = this.tickPositions,
ticks = this.ticks,
labelOptions = this.options.labels,
horiz = this.horiz,
margin = chart.margin,
slotWidth = this.slotWidth = (horiz && !labelOptions.step && !labelOptions.rotation &&
((this.staggerLines || 1) * chart.plotWidth) / tickPositions.length) ||
(!horiz && ((margin[3] && (margin[3] - chart.spacing[3])) || chart.chartWidth * 0.33)), // #1580, #1931,
innerWidth = mathMax(1, mathRound(slotWidth - 2 * (labelOptions.padding || 5))),
attr = {},
labelMetrics = renderer.fontMetrics(labelOptions.style.fontSize, ticks[0] && ticks[0].label),
css,
labelLength = 0,
label,
i,
pos;
// Set rotation option unless it is "auto", like in gauges
if (!isString(labelOptions.rotation)) {
attr.rotation = labelOptions.rotation;
}
// Handle auto rotation on horizontal axis
if (this.autoRotation) {
// Get the longest label length
each(tickPositions, function (tick) {
tick = ticks[tick];
if (tick && tick.labelLength > labelLength) {
labelLength = tick.labelLength;
}
});
// Apply rotation only if the label is too wide for the slot, and
// the label is wider than its height.
if (labelLength > innerWidth && labelLength > labelMetrics.h) {
attr.rotation = this.labelRotation;
} else {
this.labelRotation = 0;
}
// Handle word-wrap or ellipsis on vertical axis
} else if (slotWidth) {
// For word-wrap or ellipsis
css = { width: innerWidth + PX, textOverflow: 'clip' };
// On vertical axis, only allow word wrap if there is room for more lines.
i = tickPositions.length;
while (!horiz && i--) {
pos = tickPositions[i];
label = ticks[pos].label;
if (label) {
if (this.len / tickPositions.length - 4 < label.getBBox().height) {
label.specCss = { textOverflow: 'ellipsis' };
}
}
}
}
// Add ellipsis if the label length is significantly longer than ideal
if (attr.rotation) {
css = {
width: (labelLength > chart.chartHeight * 0.5 ? chart.chartHeight * 0.33 : chart.chartHeight) + PX,
textOverflow: 'ellipsis'
};
}
// Set the explicit or automatic label alignment
this.labelAlign = attr.align = labelOptions.align || this.autoLabelAlign(this.labelRotation);
// Apply general and specific CSS
each(tickPositions, function (pos) {
var tick = ticks[pos],
label = tick && tick.label;
if (label) {
if (css) {
label.css(merge(css, label.specCss));
}
delete label.specCss;
label.attr(attr);
tick.rotation = attr.rotation;
}
});
// TODO: Why not part of getLabelPosition?
this.tickRotCorr = renderer.rotCorr(labelMetrics.b, this.labelRotation || 0, this.side === 2);
},
/**
* Render the tick labels to a preliminary position to get their sizes
*/
getOffset: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
tickPositions = axis.tickPositions,
ticks = axis.ticks,
horiz = axis.horiz,
side = axis.side,
invertedSide = chart.inverted ? [1, 0, 3, 2][side] : side,
hasData,
showAxis,
titleOffset = 0,
titleOffsetOption,
titleMargin = 0,
axisTitleOptions = options.title,
labelOptions = options.labels,
labelOffset = 0, // reset
labelOffsetPadded,
axisOffset = chart.axisOffset,
clipOffset = chart.clipOffset,
directionFactor = [-1, 1, 1, -1][side],
n,
lineHeightCorrection;
// For reuse in Axis.render
axis.hasData = hasData = (axis.hasVisibleSeries || (defined(axis.min) && defined(axis.max) && !!tickPositions));
axis.showAxis = showAxis = hasData || pick(options.showEmpty, true);
// Set/reset staggerLines
axis.staggerLines = axis.horiz && labelOptions.staggerLines;
// Create the axisGroup and gridGroup elements on first iteration
if (!axis.axisGroup) {
axis.gridGroup = renderer.g('grid')
.attr({ zIndex: options.gridZIndex || 1 })
.add();
axis.axisGroup = renderer.g('axis')
.attr({ zIndex: options.zIndex || 2 })
.add();
axis.labelGroup = renderer.g('axis-labels')
.attr({ zIndex: labelOptions.zIndex || 7 })
.addClass(PREFIX + axis.coll.toLowerCase() + '-labels')
.add();
}
if (hasData || axis.isLinked) {
// Generate ticks
each(tickPositions, function (pos) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
} else {
ticks[pos].addLabel(); // update labels depending on tick interval
}
});
axis.renderUnsquish();
each(tickPositions, function (pos) {
// left side must be align: right and right side must have align: left for labels
if (side === 0 || side === 2 || { 1: 'left', 3: 'right' }[side] === axis.labelAlign) {
// get the highest offset
labelOffset = mathMax(
ticks[pos].getLabelSize(),
labelOffset
);
}
});
if (axis.staggerLines) {
labelOffset *= axis.staggerLines;
axis.labelOffset = labelOffset;
}
} else { // doesn't have data
for (n in ticks) {
ticks[n].destroy();
delete ticks[n];
}
}
if (axisTitleOptions && axisTitleOptions.text && axisTitleOptions.enabled !== false) {
if (!axis.axisTitle) {
axis.axisTitle = renderer.text(
axisTitleOptions.text,
0,
0,
axisTitleOptions.useHTML
)
.attr({
zIndex: 7,
rotation: axisTitleOptions.rotation || 0,
align:
axisTitleOptions.textAlign ||
{ low: 'left', middle: 'center', high: 'right' }[axisTitleOptions.align]
})
.addClass(PREFIX + this.coll.toLowerCase() + '-title')
.css(axisTitleOptions.style)
.add(axis.axisGroup);
axis.axisTitle.isNew = true;
}
if (showAxis) {
titleOffset = axis.axisTitle.getBBox()[horiz ? 'height' : 'width'];
titleOffsetOption = axisTitleOptions.offset;
titleMargin = defined(titleOffsetOption) ? 0 : pick(axisTitleOptions.margin, horiz ? 5 : 10);
}
// hide or show the title depending on whether showEmpty is set
axis.axisTitle[showAxis ? 'show' : 'hide']();
}
// handle automatic or user set offset
axis.offset = directionFactor * pick(options.offset, axisOffset[side]);
axis.tickRotCorr = axis.tickRotCorr || { x: 0, y: 0 }; // polar
lineHeightCorrection = side === 2 ? axis.tickRotCorr.y : 0;
labelOffsetPadded = labelOffset + titleMargin +
(labelOffset && (directionFactor * (horiz ? pick(labelOptions.y, axis.tickRotCorr.y + 8) : labelOptions.x) - lineHeightCorrection));
axis.axisTitleMargin = pick(titleOffsetOption, labelOffsetPadded);
axisOffset[side] = mathMax(
axisOffset[side],
axis.axisTitleMargin + titleOffset + directionFactor * axis.offset,
labelOffsetPadded // #3027
);
clipOffset[invertedSide] = mathMax(clipOffset[invertedSide], mathFloor(options.lineWidth / 2) * 2);
},
/**
* Get the path for the axis line
*/
getLinePath: function (lineWidth) {
var chart = this.chart,
opposite = this.opposite,
offset = this.offset,
horiz = this.horiz,
lineLeft = this.left + (opposite ? this.width : 0) + offset,
lineTop = chart.chartHeight - this.bottom - (opposite ? this.height : 0) + offset;
if (opposite) {
lineWidth *= -1; // crispify the other way - #1480, #1687
}
return chart.renderer.crispLine([
M,
horiz ?
this.left :
lineLeft,
horiz ?
lineTop :
this.top,
L,
horiz ?
chart.chartWidth - this.right :
lineLeft,
horiz ?
lineTop :
chart.chartHeight - this.bottom
], lineWidth);
},
/**
* Position the title
*/
getTitlePosition: function () {
// compute anchor points for each of the title align options
var horiz = this.horiz,
axisLeft = this.left,
axisTop = this.top,
axisLength = this.len,
axisTitleOptions = this.options.title,
margin = horiz ? axisLeft : axisTop,
opposite = this.opposite,
offset = this.offset,
fontSize = pInt(axisTitleOptions.style.fontSize || 12),
// the position in the length direction of the axis
alongAxis = {
low: margin + (horiz ? 0 : axisLength),
middle: margin + axisLength / 2,
high: margin + (horiz ? axisLength : 0)
}[axisTitleOptions.align],
// the position in the perpendicular direction of the axis
offAxis = (horiz ? axisTop + this.height : axisLeft) +
(horiz ? 1 : -1) * // horizontal axis reverses the margin
(opposite ? -1 : 1) * // so does opposite axes
this.axisTitleMargin +
(this.side === 2 ? fontSize : 0);
return {
x: horiz ?
alongAxis :
offAxis + (opposite ? this.width : 0) + offset +
(axisTitleOptions.x || 0), // x
y: horiz ?
offAxis - (opposite ? this.height : 0) + offset :
alongAxis + (axisTitleOptions.y || 0) // y
};
},
/**
* Render the axis
*/
render: function () {
var axis = this,
chart = axis.chart,
renderer = chart.renderer,
options = axis.options,
isLog = axis.isLog,
isLinked = axis.isLinked,
tickPositions = axis.tickPositions,
axisTitle = axis.axisTitle,
ticks = axis.ticks,
minorTicks = axis.minorTicks,
alternateBands = axis.alternateBands,
stackLabelOptions = options.stackLabels,
alternateGridColor = options.alternateGridColor,
tickmarkOffset = axis.tickmarkOffset,
lineWidth = options.lineWidth,
linePath,
hasRendered = chart.hasRendered,
slideInTicks = hasRendered && defined(axis.oldMin) && !isNaN(axis.oldMin),
hasData = axis.hasData,
showAxis = axis.showAxis,
from,
to;
// Reset
axis.labelEdge.length = 0;
//axis.justifyToPlot = overflow === 'justify';
axis.overlap = false;
// Mark all elements inActive before we go over and mark the active ones
each([ticks, minorTicks, alternateBands], function (coll) {
var pos;
for (pos in coll) {
coll[pos].isActive = false;
}
});
// If the series has data draw the ticks. Else only the line and title
if (hasData || isLinked) {
// minor ticks
if (axis.minorTickInterval && !axis.categories) {
each(axis.getMinorTickPositions(), function (pos) {
if (!minorTicks[pos]) {
minorTicks[pos] = new Tick(axis, pos, 'minor');
}
// render new ticks in old position
if (slideInTicks && minorTicks[pos].isNew) {
minorTicks[pos].render(null, true);
}
minorTicks[pos].render(null, false, 1);
});
}
// Major ticks. Pull out the first item and render it last so that
// we can get the position of the neighbour label. #808.
if (tickPositions.length) { // #1300
each(tickPositions, function (pos, i) {
// linked axes need an extra check to find out if
if (!isLinked || (pos >= axis.min && pos <= axis.max)) {
if (!ticks[pos]) {
ticks[pos] = new Tick(axis, pos);
}
// render new ticks in old position
if (slideInTicks && ticks[pos].isNew) {
ticks[pos].render(i, true, 0.1);
}
ticks[pos].render(i);
}
});
// In a categorized axis, the tick marks are displayed between labels. So
// we need to add a tick mark and grid line at the left edge of the X axis.
if (tickmarkOffset && (axis.min === 0 || axis.single)) {
if (!ticks[-1]) {
ticks[-1] = new Tick(axis, -1, null, true);
}
ticks[-1].render(-1);
}
}
// alternate grid color
if (alternateGridColor) {
each(tickPositions, function (pos, i) {
if (i % 2 === 0 && pos < axis.max) {
if (!alternateBands[pos]) {
alternateBands[pos] = new Highcharts.PlotLineOrBand(axis);
}
from = pos + tickmarkOffset; // #949
to = tickPositions[i + 1] !== UNDEFINED ? tickPositions[i + 1] + tickmarkOffset : axis.max;
alternateBands[pos].options = {
from: isLog ? lin2log(from) : from,
to: isLog ? lin2log(to) : to,
color: alternateGridColor
};
alternateBands[pos].render();
alternateBands[pos].isActive = true;
}
});
}
// custom plot lines and bands
if (!axis._addedPlotLB) { // only first time
each((options.plotLines || []).concat(options.plotBands || []), function (plotLineOptions) {
axis.addPlotBandOrLine(plotLineOptions);
});
axis._addedPlotLB = true;
}
} // end if hasData
// Remove inactive ticks
each([ticks, minorTicks, alternateBands], function (coll) {
var pos,
i,
forDestruction = [],
delay = globalAnimation ? globalAnimation.duration || 500 : 0,
destroyInactiveItems = function () {
i = forDestruction.length;
while (i--) {
// When resizing rapidly, the same items may be destroyed in different timeouts,
// or the may be reactivated
if (coll[forDestruction[i]] && !coll[forDestruction[i]].isActive) {
coll[forDestruction[i]].destroy();
delete coll[forDestruction[i]];
}
}
};
for (pos in coll) {
if (!coll[pos].isActive) {
// Render to zero opacity
coll[pos].render(pos, false, 0);
coll[pos].isActive = false;
forDestruction.push(pos);
}
}
// When the objects are finished fading out, destroy them
if (coll === alternateBands || !chart.hasRendered || !delay) {
destroyInactiveItems();
} else if (delay) {
setTimeout(destroyInactiveItems, delay);
}
});
// Static items. As the axis group is cleared on subsequent calls
// to render, these items are added outside the group.
// axis line
if (lineWidth) {
linePath = axis.getLinePath(lineWidth);
if (!axis.axisLine) {
axis.axisLine = renderer.path(linePath)
.attr({
stroke: options.lineColor,
'stroke-width': lineWidth,
zIndex: 7
})
.add(axis.axisGroup);
} else {
axis.axisLine.animate({ d: linePath });
}
// show or hide the line depending on options.showEmpty
axis.axisLine[showAxis ? 'show' : 'hide']();
}
if (axisTitle && showAxis) {
axisTitle[axisTitle.isNew ? 'attr' : 'animate'](
axis.getTitlePosition()
);
axisTitle.isNew = false;
}
// Stacked totals:
if (stackLabelOptions && stackLabelOptions.enabled) {
axis.renderStackTotals();
}
// End stacked totals
axis.isDirty = false;
},
/**
* Redraw the axis to reflect changes in the data or axis extremes
*/
redraw: function () {
// render the axis
this.render();
// move plot lines and bands
each(this.plotLinesAndBands, function (plotLine) {
plotLine.render();
});
// mark associated series as dirty and ready for redraw
each(this.series, function (series) {
series.isDirty = true;
});
},
/**
* Destroys an Axis instance.
*/
destroy: function (keepEvents) {
var axis = this,
stacks = axis.stacks,
stackKey,
plotLinesAndBands = axis.plotLinesAndBands,
i;
// Remove the events
if (!keepEvents) {
removeEvent(axis);
}
// Destroy each stack total
for (stackKey in stacks) {
destroyObjectProperties(stacks[stackKey]);
stacks[stackKey] = null;
}
// Destroy collections
each([axis.ticks, axis.minorTicks, axis.alternateBands], function (coll) {
destroyObjectProperties(coll);
});
i = plotLinesAndBands.length;
while (i--) { // #1975
plotLinesAndBands[i].destroy();
}
// Destroy local variables
each(['stackTotalGroup', 'axisLine', 'axisTitle', 'axisGroup', 'cross', 'gridGroup', 'labelGroup'], function (prop) {
if (axis[prop]) {
axis[prop] = axis[prop].destroy();
}
});
// Destroy crosshair
if (this.cross) {
this.cross.destroy();
}
},
/**
* Draw the crosshair
*/
drawCrosshair: function (e, point) { // docs: Missing docs for Axis.crosshair. Also for properties.
var path,
options = this.crosshair,
animation = options.animation,
pos,
attribs,
categorized;
if (
// Disabled in options
!this.crosshair ||
// snap
((defined(point) || !pick(this.crosshair.snap, true)) === false) ||
// Do not draw the crosshair if this axis is not part of the point
(defined(point) && pick(this.crosshair.snap, true) && (!point.series || point.series[this.isXAxis ? 'xAxis' : 'yAxis'] !== this))
) {
this.hideCrosshair();
} else {
// Get the path
if (!pick(options.snap, true)) {
pos = (this.horiz ? e.chartX - this.pos : this.len - e.chartY + this.pos);
} else if (defined(point)) {
/*jslint eqeq: true*/
pos = (this.chart.inverted != this.horiz) ? point.plotX : this.len - point.plotY;
/*jslint eqeq: false*/
}
if (this.isRadial) {
path = this.getPlotLinePath(this.isXAxis ? point.x : pick(point.stackY, point.y)) || null; // #3189
} else {
path = this.getPlotLinePath(null, null, null, null, pos) || null; // #3189
}
if (path === null) {
this.hideCrosshair();
return;
}
// Draw the cross
if (this.cross) {
this.cross
.attr({ visibility: VISIBLE })[animation ? 'animate' : 'attr']({ d: path }, animation);
} else {
categorized = this.categories && !this.isRadial;
attribs = {
'stroke-width': options.width || (categorized ? this.transA : 1),
stroke: options.color || (categorized ? 'rgba(155,200,255,0.2)' : '#C0C0C0'),
zIndex: options.zIndex || 2
};
if (options.dashStyle) {
attribs.dashstyle = options.dashStyle;
}
this.cross = this.chart.renderer.path(path).attr(attribs).add();
}
}
},
/**
* Hide the crosshair.
*/
hideCrosshair: function () {
if (this.cross) {
this.cross.hide();
}
}
}; // end Axis
extend(Axis.prototype, AxisPlotLineOrBandExtension);
/**
* Methods defined on the Axis prototype
*/
/**
* Set the tick positions of a logarithmic axis
*/
Axis.prototype.getLogTickPositions = function (interval, min, max, minor) {
var axis = this,
options = axis.options,
axisLength = axis.len,
// Since we use this method for both major and minor ticks,
// use a local variable and return the result
positions = [];
// Reset
if (!minor) {
axis._minorAutoInterval = null;
}
// First case: All ticks fall on whole logarithms: 1, 10, 100 etc.
if (interval >= 0.5) {
interval = mathRound(interval);
positions = axis.getLinearTickPositions(interval, min, max);
// Second case: We need intermediary ticks. For example
// 1, 2, 4, 6, 8, 10, 20, 40 etc.
} else if (interval >= 0.08) {
var roundedMin = mathFloor(min),
intermediate,
i,
j,
len,
pos,
lastPos,
break2;
if (interval > 0.3) {
intermediate = [1, 2, 4];
} else if (interval > 0.15) { // 0.2 equals five minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 4, 6, 8];
} else { // 0.1 equals ten minor ticks per 1, 10, 100 etc
intermediate = [1, 2, 3, 4, 5, 6, 7, 8, 9];
}
for (i = roundedMin; i < max + 1 && !break2; i++) {
len = intermediate.length;
for (j = 0; j < len && !break2; j++) {
pos = log2lin(lin2log(i) * intermediate[j]);
if (pos > min && (!minor || lastPos <= max) && lastPos !== UNDEFINED) { // #1670, lastPos is #3113
positions.push(lastPos);
}
if (lastPos > max) {
break2 = true;
}
lastPos = pos;
}
}
// Third case: We are so deep in between whole logarithmic values that
// we might as well handle the tick positions like a linear axis. For
// example 1.01, 1.02, 1.03, 1.04.
} else {
var realMin = lin2log(min),
realMax = lin2log(max),
tickIntervalOption = options[minor ? 'minorTickInterval' : 'tickInterval'],
filteredTickIntervalOption = tickIntervalOption === 'auto' ? null : tickIntervalOption,
tickPixelIntervalOption = options.tickPixelInterval / (minor ? 5 : 1),
totalPixelLength = minor ? axisLength / axis.tickPositions.length : axisLength;
interval = pick(
filteredTickIntervalOption,
axis._minorAutoInterval,
(realMax - realMin) * tickPixelIntervalOption / (totalPixelLength || 1)
);
interval = normalizeTickInterval(
interval,
null,
getMagnitude(interval)
);
positions = map(axis.getLinearTickPositions(
interval,
realMin,
realMax
), log2lin);
if (!minor) {
axis._minorAutoInterval = interval / 5;
}
}
// Set the axis-level tickInterval variable
if (!minor) {
axis.tickInterval = interval;
}
return positions;
};/**
* The tooltip object
* @param {Object} chart The chart instance
* @param {Object} options Tooltip options
*/
var Tooltip = Highcharts.Tooltip = function () {
this.init.apply(this, arguments);
};
Tooltip.prototype = {
init: function (chart, options) {
var borderWidth = options.borderWidth,
style = options.style,
padding = pInt(style.padding);
// Save the chart and options
this.chart = chart;
this.options = options;
// Keep track of the current series
//this.currentSeries = UNDEFINED;
// List of crosshairs
this.crosshairs = [];
// Current values of x and y when animating
this.now = { x: 0, y: 0 };
// The tooltip is initially hidden
this.isHidden = true;
// create the label
this.label = chart.renderer.label('', 0, 0, options.shape || 'callout', null, null, options.useHTML, null, 'tooltip')
.attr({
padding: padding,
fill: options.backgroundColor,
'stroke-width': borderWidth,
r: options.borderRadius,
zIndex: 8
})
.css(style)
.css({ padding: 0 }) // Remove it from VML, the padding is applied as an attribute instead (#1117)
.add()
.attr({ y: -9999 }); // #2301, #2657
// When using canVG the shadow shows up as a gray circle
// even if the tooltip is hidden.
if (!useCanVG) {
this.label.shadow(options.shadow);
}
// Public property for getting the shared state.
this.shared = options.shared;
},
/**
* Destroy the tooltip and its elements.
*/
destroy: function () {
// Destroy and clear local variables
if (this.label) {
this.label = this.label.destroy();
}
clearTimeout(this.hideTimer);
clearTimeout(this.tooltipTimeout);
},
/**
* Provide a soft movement for the tooltip
*
* @param {Number} x
* @param {Number} y
* @private
*/
move: function (x, y, anchorX, anchorY) {
var tooltip = this,
now = tooltip.now,
animate = tooltip.options.animation !== false && !tooltip.isHidden &&
// When we get close to the target position, abort animation and land on the right place (#3056)
(mathAbs(x - now.x) > 1 || mathAbs(y - now.y) > 1),
skipAnchor = tooltip.followPointer || tooltip.len > 1;
// Get intermediate values for animation
extend(now, {
x: animate ? (2 * now.x + x) / 3 : x,
y: animate ? (now.y + y) / 2 : y,
anchorX: skipAnchor ? UNDEFINED : animate ? (2 * now.anchorX + anchorX) / 3 : anchorX,
anchorY: skipAnchor ? UNDEFINED : animate ? (now.anchorY + anchorY) / 2 : anchorY
});
// Move to the intermediate value
tooltip.label.attr(now);
// Run on next tick of the mouse tracker
if (animate) {
// Never allow two timeouts
clearTimeout(this.tooltipTimeout);
// Set the fixed interval ticking for the smooth tooltip
this.tooltipTimeout = setTimeout(function () {
// The interval function may still be running during destroy, so check that the chart is really there before calling.
if (tooltip) {
tooltip.move(x, y, anchorX, anchorY);
}
}, 32);
}
},
/**
* Hide the tooltip
*/
hide: function (delay) {
var tooltip = this,
hoverPoints;
clearTimeout(this.hideTimer); // disallow duplicate timers (#1728, #1766)
if (!this.isHidden) {
hoverPoints = this.chart.hoverPoints;
this.hideTimer = setTimeout(function () {
tooltip.label.fadeOut();
tooltip.isHidden = true;
}, pick(delay, this.options.hideDelay, 500));
// hide previous hoverPoints and set new
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
this.chart.hoverPoints = null;
this.chart.hoverSeries = null;
}
},
/**
* Extendable method to get the anchor position of the tooltip
* from a point or set of points
*/
getAnchor: function (points, mouseEvent) {
var ret,
chart = this.chart,
inverted = chart.inverted,
plotTop = chart.plotTop,
plotLeft = chart.plotLeft,
plotX = 0,
plotY = 0,
yAxis,
xAxis;
points = splat(points);
// Pie uses a special tooltipPos
ret = points[0].tooltipPos;
// When tooltip follows mouse, relate the position to the mouse
if (this.followPointer && mouseEvent) {
if (mouseEvent.chartX === UNDEFINED) {
mouseEvent = chart.pointer.normalize(mouseEvent);
}
ret = [
mouseEvent.chartX - chart.plotLeft,
mouseEvent.chartY - plotTop
];
}
// When shared, use the average position
if (!ret) {
each(points, function (point) {
yAxis = point.series.yAxis;
xAxis = point.series.xAxis;
plotX += point.plotX + (!inverted && xAxis ? xAxis.left - plotLeft : 0);
plotY += (point.plotLow ? (point.plotLow + point.plotHigh) / 2 : point.plotY) +
(!inverted && yAxis ? yAxis.top - plotTop : 0); // #1151
});
plotX /= points.length;
plotY /= points.length;
ret = [
inverted ? chart.plotWidth - plotY : plotX,
this.shared && !inverted && points.length > 1 && mouseEvent ?
mouseEvent.chartY - plotTop : // place shared tooltip next to the mouse (#424)
inverted ? chart.plotHeight - plotX : plotY
];
}
return map(ret, mathRound);
},
/**
* Place the tooltip in a chart without spilling over
* and not covering the point it self.
*/
getPosition: function (boxWidth, boxHeight, point) {
var chart = this.chart,
distance = this.distance,
ret = {},
swapped,
first = ['y', chart.chartHeight, boxHeight, point.plotY + chart.plotTop],
second = ['x', chart.chartWidth, boxWidth, point.plotX + chart.plotLeft],
// The far side is right or bottom
preferFarSide = pick(point.ttBelow, (chart.inverted && !point.negative) || (!chart.inverted && point.negative)),
/**
* Handle the preferred dimension. When the preferred dimension is tooltip
* on top or bottom of the point, it will look for space there.
*/
firstDimension = function (dim, outerSize, innerSize, point) {
var roomLeft = innerSize < point - distance,
roomRight = point + distance + innerSize < outerSize,
alignedLeft = point - distance - innerSize,
alignedRight = point + distance;
if (preferFarSide && roomRight) {
ret[dim] = alignedRight;
} else if (!preferFarSide && roomLeft) {
ret[dim] = alignedLeft;
} else if (roomLeft) {
ret[dim] = alignedLeft;
} else if (roomRight) {
ret[dim] = alignedRight;
} else {
return false;
}
},
/**
* Handle the secondary dimension. If the preferred dimension is tooltip
* on top or bottom of the point, the second dimension is to align the tooltip
* above the point, trying to align center but allowing left or right
* align within the chart box.
*/
secondDimension = function (dim, outerSize, innerSize, point) {
// Too close to the edge, return false and swap dimensions
if (point < distance || point > outerSize - distance) {
return false;
// Align left/top
} else if (point < innerSize / 2) {
ret[dim] = 1;
// Align right/bottom
} else if (point > outerSize - innerSize / 2) {
ret[dim] = outerSize - innerSize - 2;
// Align center
} else {
ret[dim] = point - innerSize / 2;
}
},
/**
* Swap the dimensions
*/
swap = function (count) {
var temp = first;
first = second;
second = temp;
swapped = count;
},
run = function () {
if (firstDimension.apply(0, first) !== false) {
if (secondDimension.apply(0, second) === false && !swapped) {
swap(true);
run();
}
} else if (!swapped) {
swap(true);
run();
} else {
ret.x = ret.y = 0;
}
};
// Under these conditions, prefer the tooltip on the side of the point
if (chart.inverted || this.len > 1) {
swap();
}
run();
return ret;
},
/**
* In case no user defined formatter is given, this will be used. Note that the context
* here is an object holding point, series, x, y etc.
*/
defaultFormatter: function (tooltip) {
var items = this.points || splat(this),
s;
// build the header
s = [tooltip.tooltipFooterHeaderFormatter(items[0])]; //#3397: abstraction to enable formatting of footer and header
// build the values
s = s.concat(tooltip.bodyFormatter(items));
// footer
s.push(tooltip.tooltipFooterHeaderFormatter(items[0], true)); //#3397: abstraction to enable formatting of footer and header
return s.join('');
},
/**
* Refresh the tooltip's text and position.
* @param {Object} point
*/
refresh: function (point, mouseEvent) {
var tooltip = this,
chart = tooltip.chart,
label = tooltip.label,
options = tooltip.options,
x,
y,
anchor,
textConfig = {},
text,
pointConfig = [],
formatter = options.formatter || tooltip.defaultFormatter,
hoverPoints = chart.hoverPoints,
borderColor,
shared = tooltip.shared,
currentSeries;
clearTimeout(this.hideTimer);
// get the reference point coordinates (pie charts use tooltipPos)
tooltip.followPointer = splat(point)[0].series.tooltipOptions.followPointer;
anchor = tooltip.getAnchor(point, mouseEvent);
x = anchor[0];
y = anchor[1];
// shared tooltip, array is sent over
if (shared && !(point.series && point.series.noSharedTooltip)) {
// hide previous hoverPoints and set new
chart.hoverPoints = point;
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(point, function (item) {
item.setState(HOVER_STATE);
pointConfig.push(item.getLabelConfig());
});
textConfig = {
x: point[0].category,
y: point[0].y
};
textConfig.points = pointConfig;
this.len = pointConfig.length;
point = point[0];
// single point tooltip
} else {
textConfig = point.getLabelConfig();
}
text = formatter.call(textConfig, tooltip);
// register the current series
currentSeries = point.series;
this.distance = pick(currentSeries.tooltipOptions.distance, 16);
// update the inner HTML
if (text === false) {
this.hide();
} else {
// show it
if (tooltip.isHidden) {
stop(label);
label.attr('opacity', 1).show();
}
// update text
label.attr({
text: text
});
// set the stroke color of the box
borderColor = options.borderColor || point.color || currentSeries.color || '#606060';
label.attr({
stroke: borderColor
});
tooltip.updatePosition({ plotX: x, plotY: y, negative: point.negative, ttBelow: point.ttBelow });
this.isHidden = false;
}
fireEvent(chart, 'tooltipRefresh', {
text: text,
x: x + chart.plotLeft,
y: y + chart.plotTop,
borderColor: borderColor
});
},
/**
* Find the new position and perform the move
*/
updatePosition: function (point) {
var chart = this.chart,
label = this.label,
pos = (this.options.positioner || this.getPosition).call(
this,
label.width,
label.height,
point
);
// do the move
this.move(
mathRound(pos.x),
mathRound(pos.y),
point.plotX + chart.plotLeft,
point.plotY + chart.plotTop
);
},
/**
* Get the best X date format based on the closest point range on the axis.
*/
getXDateFormat: function (point, options, xAxis) {
var xDateFormat,
dateTimeLabelFormats = options.dateTimeLabelFormats,
closestPointRange = xAxis && xAxis.closestPointRange,
n,
blank = '01-01 00:00:00.000',
strpos = {
millisecond: 15,
second: 12,
minute: 9,
hour: 6,
day: 3
},
date,
lastN;
if (closestPointRange) {
date = dateFormat('%m-%d %H:%M:%S.%L', point.x);
for (n in timeUnits) {
// If the range is exactly one week and we're looking at a Sunday/Monday, go for the week format
if (closestPointRange === timeUnits.week && +dateFormat('%w', point.x) === xAxis.options.startOfWeek &&
date.substr(6) === blank.substr(6)) {
n = 'week';
break;
// The first format that is too great for the range
} else if (timeUnits[n] > closestPointRange) {
n = lastN;
break;
// If the point is placed every day at 23:59, we need to show
// the minutes as well. #2637.
} else if (strpos[n] && date.substr(strpos[n]) !== blank.substr(strpos[n])) {
break;
}
// Weeks are outside the hierarchy, only apply them on Mondays/Sundays like in the first condition
if (n !== 'week') {
lastN = n;
}
}
if (n) {
xDateFormat = dateTimeLabelFormats[n];
}
} else {
xDateFormat = dateTimeLabelFormats.day;
}
return xDateFormat || dateTimeLabelFormats.year; // #2546, 2581
},
/**
* Format the footer/header of the tooltip
* #3397: abstraction to enable formatting of footer and header
*/
tooltipFooterHeaderFormatter: function (point, isFooter) {
var footOrHead = isFooter ? 'footer' : 'header',
series = point.series,
tooltipOptions = series.tooltipOptions,
xDateFormat = tooltipOptions.xDateFormat,
xAxis = series.xAxis,
isDateTime = xAxis && xAxis.options.type === 'datetime' && isNumber(point.key),
formatString = tooltipOptions[footOrHead+'Format'];
// Guess the best date format based on the closest point distance (#568, #3418)
if (isDateTime && !xDateFormat) {
xDateFormat = this.getXDateFormat(point, tooltipOptions, xAxis);
}
// Insert the footer date format if any
if (isDateTime && xDateFormat) {
formatString = formatString.replace('{point.key}', '{point.key:' + xDateFormat + '}');
}
return format(formatString, {
point: point,
series: series
});
},
/**
* Build the body (lines) of the tooltip by iterating over the items and returning one entry for each item,
* abstracting this functionality allows to easily overwrite and extend it.
*/
bodyFormatter: function (items) {
return map(items, function (item) {
var tooltipOptions = item.series.tooltipOptions;
return (tooltipOptions.pointFormatter || item.point.tooltipFormatter).call(item.point, tooltipOptions.pointFormat);
});
}
};
var hoverChartIndex;
// Global flag for touch support
hasTouch = doc.documentElement.ontouchstart !== UNDEFINED;
/**
* The mouse tracker object. All methods starting with "on" are primary DOM event handlers.
* Subsequent methods should be named differently from what they are doing.
* @param {Object} chart The Chart instance
* @param {Object} options The root options object
*/
var Pointer = Highcharts.Pointer = function (chart, options) {
this.init(chart, options);
};
Pointer.prototype = {
/**
* Initialize Pointer
*/
init: function (chart, options) {
var chartOptions = options.chart,
chartEvents = chartOptions.events,
zoomType = useCanVG ? '' : chartOptions.zoomType,
inverted = chart.inverted,
zoomX,
zoomY;
// Store references
this.options = options;
this.chart = chart;
// Zoom status
this.zoomX = zoomX = /x/.test(zoomType);
this.zoomY = zoomY = /y/.test(zoomType);
this.zoomHor = (zoomX && !inverted) || (zoomY && inverted);
this.zoomVert = (zoomY && !inverted) || (zoomX && inverted);
this.hasZoom = zoomX || zoomY;
// Do we need to handle click on a touch device?
this.runChartClick = chartEvents && !!chartEvents.click;
this.pinchDown = [];
this.lastValidTouch = {};
if (Highcharts.Tooltip && options.tooltip.enabled) {
chart.tooltip = new Tooltip(chart, options.tooltip);
this.followTouchMove = pick(options.tooltip.followTouchMove, true);
}
this.setDOMEvents();
},
/**
* Add crossbrowser support for chartX and chartY
* @param {Object} e The event object in standard browsers
*/
normalize: function (e, chartPosition) {
var chartX,
chartY,
ePos;
// common IE normalizing
e = e || window.event;
// Framework specific normalizing (#1165)
e = washMouseEvent(e);
// More IE normalizing, needs to go after washMouseEvent
if (!e.target) {
e.target = e.srcElement;
}
// iOS (#2757)
ePos = e.touches ? (e.touches.length ? e.touches.item(0) : e.changedTouches[0]) : e;
// Get mouse position
if (!chartPosition) {
this.chartPosition = chartPosition = offset(this.chart.container);
}
// chartX and chartY
if (ePos.pageX === UNDEFINED) { // IE < 9. #886.
chartX = mathMax(e.x, e.clientX - chartPosition.left); // #2005, #2129: the second case is
// for IE10 quirks mode within framesets
chartY = e.y;
} else {
chartX = ePos.pageX - chartPosition.left;
chartY = ePos.pageY - chartPosition.top;
}
return extend(e, {
chartX: mathRound(chartX),
chartY: mathRound(chartY)
});
},
/**
* Get the click position in terms of axis values.
*
* @param {Object} e A pointer event
*/
getCoordinates: function (e) {
var coordinates = {
xAxis: [],
yAxis: []
};
each(this.chart.axes, function (axis) {
coordinates[axis.isXAxis ? 'xAxis' : 'yAxis'].push({
axis: axis,
value: axis.toValue(e[axis.horiz ? 'chartX' : 'chartY'])
});
});
return coordinates;
},
/**
* With line type charts with a single tracker, get the point closest to the mouse.
* Run Point.onMouseOver and display tooltip for the point or points.
*/
runPointActions: function (e) {
var pointer = this,
chart = pointer.chart,
series = chart.series,
tooltip = chart.tooltip,
shared = tooltip ? tooltip.shared : false,
followPointer,
//point,
//points,
hoverPoint = chart.hoverPoint,
hoverSeries = chart.hoverSeries,
i,
trueXkd,
trueX,
//j,
distance = chart.chartWidth,
rdistance = chart.chartWidth,
anchor,
kdpoints = [],
kdpoint;
// For hovering over the empty parts of the plot area (hoverSeries is undefined).
// If there is one series with point tracking (combo chart), don't go to nearest neighbour.
if (!shared && !hoverSeries) {
for (i = 0; i < series.length; i++) {
if (series[i].directTouch || !series[i].options.stickyTracking) {
series = [];
}
}
}
if (shared || !hoverSeries) {
// Find nearest points on all series
each(series, function (s) {
// Skip hidden series
if (s.visible && pick(s.options.enableMouseTracking, true)) {
kdpoints.push(s.searchPoint(e));
}
});
// Find absolute nearest point
each(kdpoints, function (p) {
if (p && defined(p.plotX) && defined(p.plotY)) {
if ((p.dist.distX < distance) || ((p.dist.distX === distance || p.series.kdDimensions > 1) && p.dist.distR < rdistance)) {
distance = p.dist.distX;
rdistance = p.dist.distR;
kdpoint = p;
}
}
//point = kdpoints[0];
});
} else {
kdpoint = hoverSeries ? hoverSeries.searchPoint(e) : UNDEFINED;
}
// Refresh tooltip for kdpoint
if (kdpoint && tooltip && kdpoint !== hoverPoint) {
// Draw tooltip if necessary
if (shared && !kdpoint.series.noSharedTooltip) {
i = kdpoints.length;
trueXkd = kdpoint.plotX + kdpoint.series.xAxis.left;
while (i--) {
trueX = kdpoints[i].plotX + kdpoints[i].series.xAxis.left;
if (kdpoints[i].x !== kdpoint.x || trueX !== trueXkd || !defined(kdpoints[i].y) || (kdpoints[i].series.noSharedTooltip || false)) {
kdpoints.splice(i, 1);
}
}
tooltip.refresh(kdpoints, e);
each(kdpoints, function (point) {
point.onMouseOver(e);
});
} else {
tooltip.refresh(kdpoint, e);
kdpoint.onMouseOver(e);
}
// Update positions (regardless of kdpoint or hoverPoint)
} else {
followPointer = hoverSeries && hoverSeries.tooltipOptions.followPointer;
if (tooltip && followPointer && !tooltip.isHidden) {
anchor = tooltip.getAnchor([{}], e);
tooltip.updatePosition({ plotX: anchor[0], plotY: anchor[1] });
}
}
// Crosshair
each(chart.axes, function (axis) {
axis.drawCrosshair(e, pick(kdpoint, hoverPoint));
});
},
/**
* Reset the tracking by hiding the tooltip, the hover series state and the hover point
*
* @param allowMove {Boolean} Instead of destroying the tooltip altogether, allow moving it if possible
*/
reset: function (allowMove, delay) {
var pointer = this,
chart = pointer.chart,
hoverSeries = chart.hoverSeries,
hoverPoint = chart.hoverPoint,
tooltip = chart.tooltip,
tooltipPoints = tooltip && tooltip.shared ? chart.hoverPoints : hoverPoint;
// Narrow in allowMove
allowMove = allowMove && tooltip && tooltipPoints;
// Check if the points have moved outside the plot area, #1003
if (allowMove && splat(tooltipPoints)[0].plotX === UNDEFINED) {
allowMove = false;
}
// Just move the tooltip, #349
if (allowMove) {
tooltip.refresh(tooltipPoints);
if (hoverPoint) { // #2500
hoverPoint.setState(hoverPoint.state, true);
each(chart.axes, function (axis) {
if (pick(axis.options.crosshair && axis.options.crosshair.snap, true)) {
axis.drawCrosshair(null, allowMove);
} else {
axis.hideCrosshair();
}
});
}
// Full reset
} else {
if (hoverPoint) {
hoverPoint.onMouseOut();
}
if (hoverSeries) {
hoverSeries.onMouseOut();
}
if (tooltip) {
tooltip.hide(delay);
}
if (pointer._onDocumentMouseMove) {
removeEvent(doc, 'mousemove', pointer._onDocumentMouseMove);
pointer._onDocumentMouseMove = null;
}
// Remove crosshairs
each(chart.axes, function (axis) {
axis.hideCrosshair();
});
pointer.hoverX = null;
}
},
/**
* Scale series groups to a certain scale and translation
*/
scaleGroups: function (attribs, clip) {
var chart = this.chart,
seriesAttribs;
// Scale each series
each(chart.series, function (series) {
seriesAttribs = attribs || series.getPlotBox(); // #1701
if (series.xAxis && series.xAxis.zoomEnabled) {
series.group.attr(seriesAttribs);
if (series.markerGroup) {
series.markerGroup.attr(seriesAttribs);
series.markerGroup.clip(clip ? chart.clipRect : null);
}
if (series.dataLabelsGroup) {
series.dataLabelsGroup.attr(seriesAttribs);
}
}
});
// Clip
chart.clipRect.attr(clip || chart.clipBox);
},
/**
* Start a drag operation
*/
dragStart: function (e) {
var chart = this.chart;
// Record the start position
chart.mouseIsDown = e.type;
chart.cancelClick = false;
chart.mouseDownX = this.mouseDownX = e.chartX;
chart.mouseDownY = this.mouseDownY = e.chartY;
},
/**
* Perform a drag operation in response to a mousemove event while the mouse is down
*/
drag: function (e) {
var chart = this.chart,
chartOptions = chart.options.chart,
chartX = e.chartX,
chartY = e.chartY,
zoomHor = this.zoomHor,
zoomVert = this.zoomVert,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
clickedInside,
size,
mouseDownX = this.mouseDownX,
mouseDownY = this.mouseDownY,
panKey = chartOptions.panKey && e[chartOptions.panKey + 'Key'];
// If the mouse is outside the plot area, adjust to cooordinates
// inside to prevent the selection marker from going outside
if (chartX < plotLeft) {
chartX = plotLeft;
} else if (chartX > plotLeft + plotWidth) {
chartX = plotLeft + plotWidth;
}
if (chartY < plotTop) {
chartY = plotTop;
} else if (chartY > plotTop + plotHeight) {
chartY = plotTop + plotHeight;
}
// determine if the mouse has moved more than 10px
this.hasDragged = Math.sqrt(
Math.pow(mouseDownX - chartX, 2) +
Math.pow(mouseDownY - chartY, 2)
);
if (this.hasDragged > 10) {
clickedInside = chart.isInsidePlot(mouseDownX - plotLeft, mouseDownY - plotTop);
// make a selection
if (chart.hasCartesianSeries && (this.zoomX || this.zoomY) && clickedInside && !panKey) {
if (!this.selectionMarker) {
this.selectionMarker = chart.renderer.rect(
plotLeft,
plotTop,
zoomHor ? 1 : plotWidth,
zoomVert ? 1 : plotHeight,
0
)
.attr({
fill: chartOptions.selectionMarkerFill || 'rgba(69,114,167,0.25)',
zIndex: 7
})
.add();
}
}
// adjust the width of the selection marker
if (this.selectionMarker && zoomHor) {
size = chartX - mouseDownX;
this.selectionMarker.attr({
width: mathAbs(size),
x: (size > 0 ? 0 : size) + mouseDownX
});
}
// adjust the height of the selection marker
if (this.selectionMarker && zoomVert) {
size = chartY - mouseDownY;
this.selectionMarker.attr({
height: mathAbs(size),
y: (size > 0 ? 0 : size) + mouseDownY
});
}
// panning
if (clickedInside && !this.selectionMarker && chartOptions.panning) {
chart.pan(e, chartOptions.panning);
}
}
},
/**
* On mouse up or touch end across the entire document, drop the selection.
*/
drop: function (e) {
var pointer = this,
chart = this.chart,
hasPinched = this.hasPinched;
if (this.selectionMarker) {
var selectionData = {
xAxis: [],
yAxis: [],
originalEvent: e.originalEvent || e
},
selectionBox = this.selectionMarker,
selectionLeft = selectionBox.attr ? selectionBox.attr('x') : selectionBox.x,
selectionTop = selectionBox.attr ? selectionBox.attr('y') : selectionBox.y,
selectionWidth = selectionBox.attr ? selectionBox.attr('width') : selectionBox.width,
selectionHeight = selectionBox.attr ? selectionBox.attr('height') : selectionBox.height,
runZoom;
// a selection has been made
if (this.hasDragged || hasPinched) {
// record each axis' min and max
each(chart.axes, function (axis) {
if (axis.zoomEnabled && defined(axis.min) && (hasPinched || pointer[{ xAxis: 'zoomX', yAxis: 'zoomY' }[axis.coll]])) { // #859, #3569
var horiz = axis.horiz,
minPixelPadding = e.type === 'touchend' ? axis.minPixelPadding: 0, // #1207, #3075
selectionMin = axis.toValue((horiz ? selectionLeft : selectionTop) + minPixelPadding),
selectionMax = axis.toValue((horiz ? selectionLeft + selectionWidth : selectionTop + selectionHeight) - minPixelPadding);
selectionData[axis.coll].push({
axis: axis,
min: mathMin(selectionMin, selectionMax), // for reversed axes
max: mathMax(selectionMin, selectionMax)
});
runZoom = true;
}
});
if (runZoom) {
fireEvent(chart, 'selection', selectionData, function (args) {
chart.zoom(extend(args, hasPinched ? { animation: false } : null));
});
}
}
this.selectionMarker = this.selectionMarker.destroy();
// Reset scaling preview
if (hasPinched) {
this.scaleGroups();
}
}
// Reset all
if (chart) { // it may be destroyed on mouse up - #877
css(chart.container, { cursor: chart._cursor });
chart.cancelClick = this.hasDragged > 10; // #370
chart.mouseIsDown = this.hasDragged = this.hasPinched = false;
this.pinchDown = [];
}
},
onContainerMouseDown: function (e) {
e = this.normalize(e);
// issue #295, dragging not always working in Firefox
if (e.preventDefault) {
e.preventDefault();
}
this.dragStart(e);
},
onDocumentMouseUp: function (e) {
if (charts[hoverChartIndex]) {
charts[hoverChartIndex].pointer.drop(e);
}
},
/**
* Special handler for mouse move that will hide the tooltip when the mouse leaves the plotarea.
* Issue #149 workaround. The mouseleave event does not always fire.
*/
onDocumentMouseMove: function (e) {
var chart = this.chart,
chartPosition = this.chartPosition,
hoverSeries = chart.hoverSeries;
e = this.normalize(e, chartPosition);
// If we're outside, hide the tooltip
if (chartPosition && hoverSeries && !this.inClass(e.target, 'highcharts-tracker') &&
!chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
this.reset();
}
},
/**
* When mouse leaves the container, hide the tooltip.
*/
onContainerMouseLeave: function () {
var chart = charts[hoverChartIndex];
if (chart) {
chart.pointer.reset();
chart.pointer.chartPosition = null; // also reset the chart position, used in #149 fix
}
},
// The mousemove, touchmove and touchstart event handler
onContainerMouseMove: function (e) {
var chart = this.chart;
hoverChartIndex = chart.index;
e = this.normalize(e);
e.returnValue = false; // #2251, #3224
if (chart.mouseIsDown === 'mousedown') {
this.drag(e);
}
// Show the tooltip and run mouse over events (#977)
if ((this.inClass(e.target, 'highcharts-tracker') ||
chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) && !chart.openMenu) {
this.runPointActions(e);
}
},
/**
* Utility to detect whether an element has, or has a parent with, a specific
* class name. Used on detection of tracker objects and on deciding whether
* hovering the tooltip should cause the active series to mouse out.
*/
inClass: function (element, className) {
var elemClassName;
while (element) {
elemClassName = attr(element, 'class');
if (elemClassName) {
if (elemClassName.indexOf(className) !== -1) {
return true;
} else if (elemClassName.indexOf(PREFIX + 'container') !== -1) {
return false;
}
}
element = element.parentNode;
}
},
onTrackerMouseOut: function (e) {
var series = this.chart.hoverSeries,
relatedTarget = e.relatedTarget || e.toElement,
relatedSeries = relatedTarget && relatedTarget.point && relatedTarget.point.series; // #2499
if (series && !series.options.stickyTracking && !this.inClass(relatedTarget, PREFIX + 'tooltip') &&
relatedSeries !== series) {
series.onMouseOut();
}
},
onContainerClick: function (e) {
var chart = this.chart,
hoverPoint = chart.hoverPoint,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop;
e = this.normalize(e);
e.cancelBubble = true; // IE specific
if (!chart.cancelClick) {
// On tracker click, fire the series and point events. #783, #1583
if (hoverPoint && this.inClass(e.target, PREFIX + 'tracker')) {
// the series click event
fireEvent(hoverPoint.series, 'click', extend(e, {
point: hoverPoint
}));
// the point click event
if (chart.hoverPoint) { // it may be destroyed (#1844)
hoverPoint.firePointEvent('click', e);
}
// When clicking outside a tracker, fire a chart event
} else {
extend(e, this.getCoordinates(e));
// fire a click event in the chart
if (chart.isInsidePlot(e.chartX - plotLeft, e.chartY - plotTop)) {
fireEvent(chart, 'click', e);
}
}
}
},
/**
* Set the JS DOM events on the container and document. This method should contain
* a one-to-one assignment between methods and their handlers. Any advanced logic should
* be moved to the handler reflecting the event's name.
*/
setDOMEvents: function () {
var pointer = this,
container = pointer.chart.container;
container.onmousedown = function (e) {
pointer.onContainerMouseDown(e);
};
container.onmousemove = function (e) {
pointer.onContainerMouseMove(e);
};
container.onclick = function (e) {
pointer.onContainerClick(e);
};
addEvent(container, 'mouseleave', pointer.onContainerMouseLeave);
if (chartCount === 1) {
addEvent(doc, 'mouseup', pointer.onDocumentMouseUp);
}
if (hasTouch) {
container.ontouchstart = function (e) {
pointer.onContainerTouchStart(e);
};
container.ontouchmove = function (e) {
pointer.onContainerTouchMove(e);
};
if (chartCount === 1) {
addEvent(doc, 'touchend', pointer.onDocumentTouchEnd);
}
}
},
/**
* Destroys the Pointer object and disconnects DOM events.
*/
destroy: function () {
var prop;
removeEvent(this.chart.container, 'mouseleave', this.onContainerMouseLeave);
if (!chartCount) {
removeEvent(doc, 'mouseup', this.onDocumentMouseUp);
removeEvent(doc, 'touchend', this.onDocumentTouchEnd);
}
// memory and CPU leak
clearInterval(this.tooltipTimeout);
for (prop in this) {
this[prop] = null;
}
}
};
/* Support for touch devices */
extend(Highcharts.Pointer.prototype, {
/**
* Run translation operations
*/
pinchTranslate: function (pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
if (this.zoomHor || this.pinchHor) {
this.pinchTranslateDirection(true, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
if (this.zoomVert || this.pinchVert) {
this.pinchTranslateDirection(false, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
}
},
/**
* Run translation operations for each direction (horizontal and vertical) independently
*/
pinchTranslateDirection: function (horiz, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch, forcedScale) {
var chart = this.chart,
xy = horiz ? 'x' : 'y',
XY = horiz ? 'X' : 'Y',
sChartXY = 'chart' + XY,
wh = horiz ? 'width' : 'height',
plotLeftTop = chart['plot' + (horiz ? 'Left' : 'Top')],
selectionWH,
selectionXY,
clipXY,
scale = forcedScale || 1,
inverted = chart.inverted,
bounds = chart.bounds[horiz ? 'h' : 'v'],
singleTouch = pinchDown.length === 1,
touch0Start = pinchDown[0][sChartXY],
touch0Now = touches[0][sChartXY],
touch1Start = !singleTouch && pinchDown[1][sChartXY],
touch1Now = !singleTouch && touches[1][sChartXY],
outOfBounds,
transformScale,
scaleKey,
setScale = function () {
if (!singleTouch && mathAbs(touch0Start - touch1Start) > 20) { // Don't zoom if fingers are too close on this axis
scale = forcedScale || mathAbs(touch0Now - touch1Now) / mathAbs(touch0Start - touch1Start);
}
clipXY = ((plotLeftTop - touch0Now) / scale) + touch0Start;
selectionWH = chart['plot' + (horiz ? 'Width' : 'Height')] / scale;
};
// Set the scale, first pass
setScale();
selectionXY = clipXY; // the clip position (x or y) is altered if out of bounds, the selection position is not
// Out of bounds
if (selectionXY < bounds.min) {
selectionXY = bounds.min;
outOfBounds = true;
} else if (selectionXY + selectionWH > bounds.max) {
selectionXY = bounds.max - selectionWH;
outOfBounds = true;
}
// Is the chart dragged off its bounds, determined by dataMin and dataMax?
if (outOfBounds) {
// Modify the touchNow position in order to create an elastic drag movement. This indicates
// to the user that the chart is responsive but can't be dragged further.
touch0Now -= 0.8 * (touch0Now - lastValidTouch[xy][0]);
if (!singleTouch) {
touch1Now -= 0.8 * (touch1Now - lastValidTouch[xy][1]);
}
// Set the scale, second pass to adapt to the modified touchNow positions
setScale();
} else {
lastValidTouch[xy] = [touch0Now, touch1Now];
}
// Set geometry for clipping, selection and transformation
if (!inverted) { // TODO: implement clipping for inverted charts
clip[xy] = clipXY - plotLeftTop;
clip[wh] = selectionWH;
}
scaleKey = inverted ? (horiz ? 'scaleY' : 'scaleX') : 'scale' + XY;
transformScale = inverted ? 1 / scale : scale;
selectionMarker[wh] = selectionWH;
selectionMarker[xy] = selectionXY;
transform[scaleKey] = scale;
transform['translate' + XY] = (transformScale * plotLeftTop) + (touch0Now - (transformScale * touch0Start));
},
/**
* Handle touch events with two touches
*/
pinch: function (e) {
var self = this,
chart = self.chart,
pinchDown = self.pinchDown,
touches = e.touches,
touchesLength = touches.length,
lastValidTouch = self.lastValidTouch,
hasZoom = self.hasZoom,
selectionMarker = self.selectionMarker,
transform = {},
fireClickEvent = touchesLength === 1 && ((self.inClass(e.target, PREFIX + 'tracker') &&
chart.runTrackerClick) || self.runChartClick),
clip = {};
// On touch devices, only proceed to trigger click if a handler is defined
if (hasZoom && !fireClickEvent) {
e.preventDefault();
}
// Normalize each touch
map(touches, function (e) {
return self.normalize(e);
});
// Register the touch start position
if (e.type === 'touchstart') {
each(touches, function (e, i) {
pinchDown[i] = { chartX: e.chartX, chartY: e.chartY };
});
lastValidTouch.x = [pinchDown[0].chartX, pinchDown[1] && pinchDown[1].chartX];
lastValidTouch.y = [pinchDown[0].chartY, pinchDown[1] && pinchDown[1].chartY];
// Identify the data bounds in pixels
each(chart.axes, function (axis) {
if (axis.zoomEnabled) {
var bounds = chart.bounds[axis.horiz ? 'h' : 'v'],
minPixelPadding = axis.minPixelPadding,
min = axis.toPixels(pick(axis.options.min, axis.dataMin)),
max = axis.toPixels(pick(axis.options.max, axis.dataMax)),
absMin = mathMin(min, max),
absMax = mathMax(min, max);
// Store the bounds for use in the touchmove handler
bounds.min = mathMin(axis.pos, absMin - minPixelPadding);
bounds.max = mathMax(axis.pos + axis.len, absMax + minPixelPadding);
}
});
self.res = true; // reset on next move
// Event type is touchmove, handle panning and pinching
} else if (pinchDown.length) { // can be 0 when releasing, if touchend fires first
// Set the marker
if (!selectionMarker) {
self.selectionMarker = selectionMarker = extend({
destroy: noop
}, chart.plotBox);
}
self.pinchTranslate(pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
self.hasPinched = hasZoom;
// Scale and translate the groups to provide visual feedback during pinching
self.scaleGroups(transform, clip);
// Optionally move the tooltip on touchmove
if (!hasZoom && self.followTouchMove && touchesLength === 1) {
this.runPointActions(self.normalize(e));
} else if (self.res) {
self.res = false;
this.reset(false, 0);
}
}
},
onContainerTouchStart: function (e) {
var chart = this.chart;
hoverChartIndex = chart.index;
if (e.touches.length === 1) {
e = this.normalize(e);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop) && !chart.openMenu) {
// Run mouse events and display tooltip etc
this.runPointActions(e);
this.pinch(e);
} else {
// Hide the tooltip on touching outside the plot area (#1203)
this.reset();
}
} else if (e.touches.length === 2) {
this.pinch(e);
}
},
onContainerTouchMove: function (e) {
if (e.touches.length === 1 || e.touches.length === 2) {
this.pinch(e);
}
},
onDocumentTouchEnd: function (e) {
if (charts[hoverChartIndex]) {
charts[hoverChartIndex].pointer.drop(e);
}
}
});
if (win.PointerEvent || win.MSPointerEvent) {
// The touches object keeps track of the points being touched at all times
var touches = {},
hasPointerEvent = !!win.PointerEvent,
getWebkitTouches = function () {
var key, fake = [];
fake.item = function (i) { return this[i]; };
for (key in touches) {
if (touches.hasOwnProperty(key)) {
fake.push({
pageX: touches[key].pageX,
pageY: touches[key].pageY,
target: touches[key].target
});
}
}
return fake;
},
translateMSPointer = function (e, method, wktype, callback) {
var p;
e = e.originalEvent || e;
if ((e.pointerType === 'touch' || e.pointerType === e.MSPOINTER_TYPE_TOUCH) && charts[hoverChartIndex]) {
callback(e);
p = charts[hoverChartIndex].pointer;
p[method]({
type: wktype,
target: e.currentTarget,
preventDefault: noop,
touches: getWebkitTouches()
});
}
};
/**
* Extend the Pointer prototype with methods for each event handler and more
*/
extend(Pointer.prototype, {
onContainerPointerDown: function (e) {
translateMSPointer(e, 'onContainerTouchStart', 'touchstart', function (e) {
touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY, target: e.currentTarget };
});
},
onContainerPointerMove: function (e) {
translateMSPointer(e, 'onContainerTouchMove', 'touchmove', function (e) {
touches[e.pointerId] = { pageX: e.pageX, pageY: e.pageY };
if (!touches[e.pointerId].target) {
touches[e.pointerId].target = e.currentTarget;
}
});
},
onDocumentPointerUp: function (e) {
translateMSPointer(e, 'onContainerTouchEnd', 'touchend', function (e) {
delete touches[e.pointerId];
});
},
/**
* Add or remove the MS Pointer specific events
*/
batchMSEvents: function (fn) {
fn(this.chart.container, hasPointerEvent ? 'pointerdown' : 'MSPointerDown', this.onContainerPointerDown);
fn(this.chart.container, hasPointerEvent ? 'pointermove' : 'MSPointerMove', this.onContainerPointerMove);
fn(doc, hasPointerEvent ? 'pointerup' : 'MSPointerUp', this.onDocumentPointerUp);
}
});
// Disable default IE actions for pinch and such on chart element
wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
proceed.call(this, chart, options);
if (this.hasZoom || this.followTouchMove) {
css(chart.container, {
'-ms-touch-action': NONE,
'touch-action': NONE
});
}
});
// Add IE specific touch events to chart
wrap(Pointer.prototype, 'setDOMEvents', function (proceed) {
proceed.apply(this);
if (this.hasZoom || this.followTouchMove) {
this.batchMSEvents(addEvent);
}
});
// Destroy MS events also
wrap(Pointer.prototype, 'destroy', function (proceed) {
this.batchMSEvents(removeEvent);
proceed.call(this);
});
}
/**
* The overview of the chart's series
*/
var Legend = Highcharts.Legend = function (chart, options) {
this.init(chart, options);
};
Legend.prototype = {
/**
* Initialize the legend
*/
init: function (chart, options) {
var legend = this,
itemStyle = options.itemStyle,
padding,
itemMarginTop = options.itemMarginTop || 0;
this.options = options;
if (!options.enabled) {
return;
}
legend.itemStyle = itemStyle;
legend.itemHiddenStyle = merge(itemStyle, options.itemHiddenStyle);
legend.itemMarginTop = itemMarginTop;
legend.padding = padding = pick(options.padding, 8);
legend.initialItemX = padding;
legend.initialItemY = padding - 5; // 5 is the number of pixels above the text
legend.maxItemWidth = 0;
legend.chart = chart;
legend.itemHeight = 0;
legend.symbolWidth = pick(options.symbolWidth, 16);
legend.pages = [];
// Render it
legend.render();
// move checkboxes
addEvent(legend.chart, 'endResize', function () {
legend.positionCheckboxes();
});
},
/**
* Set the colors for the legend item
* @param {Object} item A Series or Point instance
* @param {Object} visible Dimmed or colored
*/
colorizeItem: function (item, visible) {
var legend = this,
options = legend.options,
legendItem = item.legendItem,
legendLine = item.legendLine,
legendSymbol = item.legendSymbol,
hiddenColor = legend.itemHiddenStyle.color,
textColor = visible ? options.itemStyle.color : hiddenColor,
symbolColor = visible ? (item.legendColor || item.color || '#CCC') : hiddenColor,
markerOptions = item.options && item.options.marker,
symbolAttr = { fill: symbolColor },
key,
val;
if (legendItem) {
legendItem.css({ fill: textColor, color: textColor }); // color for #1553, oldIE
}
if (legendLine) {
legendLine.attr({ stroke: symbolColor });
}
if (legendSymbol) {
// Apply marker options
if (markerOptions && legendSymbol.isMarker) { // #585
symbolAttr.stroke = symbolColor;
markerOptions = item.convertAttribs(markerOptions);
for (key in markerOptions) {
val = markerOptions[key];
if (val !== UNDEFINED) {
symbolAttr[key] = val;
}
}
}
legendSymbol.attr(symbolAttr);
}
},
/**
* Position the legend item
* @param {Object} item A Series or Point instance
*/
positionItem: function (item) {
var legend = this,
options = legend.options,
symbolPadding = options.symbolPadding,
ltr = !options.rtl,
legendItemPos = item._legendItemPos,
itemX = legendItemPos[0],
itemY = legendItemPos[1],
checkbox = item.checkbox;
if (item.legendGroup) {
item.legendGroup.translate(
ltr ? itemX : legend.legendWidth - itemX - 2 * symbolPadding - 4,
itemY
);
}
if (checkbox) {
checkbox.x = itemX;
checkbox.y = itemY;
}
},
/**
* Destroy a single legend item
* @param {Object} item The series or point
*/
destroyItem: function (item) {
var checkbox = item.checkbox;
// destroy SVG elements
each(['legendItem', 'legendLine', 'legendSymbol', 'legendGroup'], function (key) {
if (item[key]) {
item[key] = item[key].destroy();
}
});
if (checkbox) {
discardElement(item.checkbox);
}
},
/**
* Destroys the legend.
*/
destroy: function () {
var legend = this,
legendGroup = legend.group,
box = legend.box;
if (box) {
legend.box = box.destroy();
}
if (legendGroup) {
legend.group = legendGroup.destroy();
}
},
/**
* Position the checkboxes after the width is determined
*/
positionCheckboxes: function (scrollOffset) {
var alignAttr = this.group.alignAttr,
translateY,
clipHeight = this.clipHeight || this.legendHeight;
if (alignAttr) {
translateY = alignAttr.translateY;
each(this.allItems, function (item) {
var checkbox = item.checkbox,
top;
if (checkbox) {
top = (translateY + checkbox.y + (scrollOffset || 0) + 3);
css(checkbox, {
left: (alignAttr.translateX + item.checkboxOffset + checkbox.x - 20) + PX,
top: top + PX,
display: top > translateY - 6 && top < translateY + clipHeight - 6 ? '' : NONE
});
}
});
}
},
/**
* Render the legend title on top of the legend
*/
renderTitle: function () {
var options = this.options,
padding = this.padding,
titleOptions = options.title,
titleHeight = 0,
bBox;
if (titleOptions.text) {
if (!this.title) {
this.title = this.chart.renderer.label(titleOptions.text, padding - 3, padding - 4, null, null, null, null, null, 'legend-title')
.attr({ zIndex: 1 })
.css(titleOptions.style)
.add(this.group);
}
bBox = this.title.getBBox();
titleHeight = bBox.height;
this.offsetWidth = bBox.width; // #1717
this.contentGroup.attr({ translateY: titleHeight });
}
this.titleHeight = titleHeight;
},
/**
* Render a single specific legend item
* @param {Object} item A series or point
*/
renderItem: function (item) {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
options = legend.options,
horizontal = options.layout === 'horizontal',
symbolWidth = legend.symbolWidth,
symbolPadding = options.symbolPadding,
itemStyle = legend.itemStyle,
itemHiddenStyle = legend.itemHiddenStyle,
padding = legend.padding,
itemDistance = horizontal ? pick(options.itemDistance, 20) : 0,
ltr = !options.rtl,
itemHeight,
widthOption = options.width,
itemMarginBottom = options.itemMarginBottom || 0,
itemMarginTop = legend.itemMarginTop,
initialItemX = legend.initialItemX,
bBox,
itemWidth,
li = item.legendItem,
series = item.series && item.series.drawLegendSymbol ? item.series : item,
seriesOptions = series.options,
showCheckbox = legend.createCheckboxForItem && seriesOptions && seriesOptions.showCheckbox,
useHTML = options.useHTML;
if (!li) { // generate it once, later move it
// Generate the group box
// A group to hold the symbol and text. Text is to be appended in Legend class.
item.legendGroup = renderer.g('legend-item')
.attr({ zIndex: 1 })
.add(legend.scrollGroup);
// Generate the list item text and add it to the group
item.legendItem = li = renderer.text(
options.labelFormat ? format(options.labelFormat, item) : options.labelFormatter.call(item),
ltr ? symbolWidth + symbolPadding : -symbolPadding,
legend.baseline || 0,
useHTML
)
.css(merge(item.visible ? itemStyle : itemHiddenStyle)) // merge to prevent modifying original (#1021)
.attr({
align: ltr ? 'left' : 'right',
zIndex: 2
})
.add(item.legendGroup);
// Get the baseline for the first item - the font size is equal for all
if (!legend.baseline) {
legend.baseline = renderer.fontMetrics(itemStyle.fontSize, li).f + 3 + itemMarginTop;
li.attr('y', legend.baseline);
}
// Draw the legend symbol inside the group box
series.drawLegendSymbol(legend, item);
if (legend.setItemEvents) {
legend.setItemEvents(item, li, useHTML, itemStyle, itemHiddenStyle);
}
// Colorize the items
legend.colorizeItem(item, item.visible);
// add the HTML checkbox on top
if (showCheckbox) {
legend.createCheckboxForItem(item);
}
}
// calculate the positions for the next line
bBox = li.getBBox();
itemWidth = item.checkboxOffset =
options.itemWidth ||
item.legendItemWidth ||
symbolWidth + symbolPadding + bBox.width + itemDistance + (showCheckbox ? 20 : 0);
legend.itemHeight = itemHeight = mathRound(item.legendItemHeight || bBox.height);
// if the item exceeds the width, start a new line
if (horizontal && legend.itemX - initialItemX + itemWidth >
(widthOption || (chart.chartWidth - 2 * padding - initialItemX - options.x))) {
legend.itemX = initialItemX;
legend.itemY += itemMarginTop + legend.lastLineHeight + itemMarginBottom;
}
// If the item exceeds the height, start a new column
/*if (!horizontal && legend.itemY + options.y + itemHeight > chart.chartHeight - spacingTop - spacingBottom) {
legend.itemY = legend.initialItemY;
legend.itemX += legend.maxItemWidth;
legend.maxItemWidth = 0;
}*/
// Set the edge positions
legend.maxItemWidth = mathMax(legend.maxItemWidth, itemWidth);
legend.lastItemY = itemMarginTop + legend.itemY + itemMarginBottom;
legend.lastLineHeight = mathMax(itemHeight, legend.lastLineHeight); // #915
// cache the position of the newly generated or reordered items
item._legendItemPos = [legend.itemX, legend.itemY];
// advance
if (horizontal) {
legend.itemX += itemWidth;
} else {
legend.itemY += itemMarginTop + itemHeight + itemMarginBottom;
legend.lastLineHeight = itemHeight;
}
// the width of the widest item
legend.offsetWidth = widthOption || mathMax(
(horizontal ? legend.itemX - initialItemX - itemDistance : itemWidth) + padding,
legend.offsetWidth
);
},
/**
* Get all items, which is one item per series for normal series and one item per point
* for pie series.
*/
getAllItems: function () {
var allItems = [];
each(this.chart.series, function (series) {
var seriesOptions = series.options;
// Handle showInLegend. If the series is linked to another series, defaults to false.
if (!pick(seriesOptions.showInLegend, !defined(seriesOptions.linkedTo) ? UNDEFINED : false, true)) {
return;
}
// use points or series for the legend item depending on legendType
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
});
return allItems;
},
/**
* Adjust the chart margins by reserving space for the legend on only one side
* of the chart. If the position is set to a corner, top or bottom is reserved
* for horizontal legends and left or right for vertical ones.
*/
adjustMargins: function (margin, spacing) {
var chart = this.chart,
options = this.options,
// Use the first letter of each alignment option in order to detect the side
alignment = options.align[0] + options.verticalAlign[0] + options.layout[0];
if (this.display && !options.floating) {
each([
/(lth|ct|rth)/,
/(rtv|rm|rbv)/,
/(rbh|cb|lbh)/,
/(lbv|lm|ltv)/
], function (alignments, side) {
if (alignments.test(alignment) && !defined(margin[side])) {
// Now we have detected on which side of the chart we should reserve space for the legend
chart[marginNames[side]] = mathMax(
chart[marginNames[side]],
chart.legend[(side + 1) % 2 ? 'legendHeight' : 'legendWidth'] +
[1, -1, -1, 1][side] * options[(side % 2) ? 'x' : 'y'] +
pick(options.margin, 12) +
spacing[side]
);
}
});
}
},
/**
* Render the legend. This method can be called both before and after
* chart.render. If called after, it will only rearrange items instead
* of creating new ones.
*/
render: function () {
var legend = this,
chart = legend.chart,
renderer = chart.renderer,
legendGroup = legend.group,
allItems,
display,
legendWidth,
legendHeight,
box = legend.box,
options = legend.options,
padding = legend.padding,
legendBorderWidth = options.borderWidth,
legendBackgroundColor = options.backgroundColor;
legend.itemX = legend.initialItemX;
legend.itemY = legend.initialItemY;
legend.offsetWidth = 0;
legend.lastItemY = 0;
if (!legendGroup) {
legend.group = legendGroup = renderer.g('legend')
.attr({ zIndex: 7 })
.add();
legend.contentGroup = renderer.g()
.attr({ zIndex: 1 }) // above background
.add(legendGroup);
legend.scrollGroup = renderer.g()
.add(legend.contentGroup);
}
legend.renderTitle();
// add each series or point
allItems = legend.getAllItems();
// sort by legendIndex
stableSort(allItems, function (a, b) {
return ((a.options && a.options.legendIndex) || 0) - ((b.options && b.options.legendIndex) || 0);
});
// reversed legend
if (options.reversed) {
allItems.reverse();
}
legend.allItems = allItems;
legend.display = display = !!allItems.length;
// render the items
legend.lastLineHeight = 0;
each(allItems, function (item) {
legend.renderItem(item);
});
// Get the box
legendWidth = (options.width || legend.offsetWidth) + padding;
legendHeight = legend.lastItemY + legend.lastLineHeight + legend.titleHeight;
legendHeight = legend.handleOverflow(legendHeight);
legendHeight += padding;
// Draw the border and/or background
if (legendBorderWidth || legendBackgroundColor) {
if (!box) {
legend.box = box = renderer.rect(
0,
0,
legendWidth,
legendHeight,
options.borderRadius,
legendBorderWidth || 0
).attr({
stroke: options.borderColor,
'stroke-width': legendBorderWidth || 0,
fill: legendBackgroundColor || NONE
})
.add(legendGroup)
.shadow(options.shadow);
box.isNew = true;
} else if (legendWidth > 0 && legendHeight > 0) {
box[box.isNew ? 'attr' : 'animate'](
box.crisp({ width: legendWidth, height: legendHeight })
);
box.isNew = false;
}
// hide the border if no items
box[display ? 'show' : 'hide']();
}
legend.legendWidth = legendWidth;
legend.legendHeight = legendHeight;
// Now that the legend width and height are established, put the items in the
// final position
each(allItems, function (item) {
legend.positionItem(item);
});
// 1.x compatibility: positioning based on style
/*var props = ['left', 'right', 'top', 'bottom'],
prop,
i = 4;
while (i--) {
prop = props[i];
if (options.style[prop] && options.style[prop] !== 'auto') {
options[i < 2 ? 'align' : 'verticalAlign'] = prop;
options[i < 2 ? 'x' : 'y'] = pInt(options.style[prop]) * (i % 2 ? -1 : 1);
}
}*/
if (display) {
legendGroup.align(extend({
width: legendWidth,
height: legendHeight
}, options), true, 'spacingBox');
}
if (!chart.isResizing) {
this.positionCheckboxes();
}
},
/**
* Set up the overflow handling by adding navigation with up and down arrows below the
* legend.
*/
handleOverflow: function (legendHeight) {
var legend = this,
chart = this.chart,
renderer = chart.renderer,
options = this.options,
optionsY = options.y,
alignTop = options.verticalAlign === 'top',
spaceHeight = chart.spacingBox.height + (alignTop ? -optionsY : optionsY) - this.padding,
maxHeight = options.maxHeight,
clipHeight,
clipRect = this.clipRect,
navOptions = options.navigation,
animation = pick(navOptions.animation, true),
arrowSize = navOptions.arrowSize || 12,
nav = this.nav,
pages = this.pages,
lastY,
allItems = this.allItems;
// Adjust the height
if (options.layout === 'horizontal') {
spaceHeight /= 2;
}
if (maxHeight) {
spaceHeight = mathMin(spaceHeight, maxHeight);
}
// Reset the legend height and adjust the clipping rectangle
pages.length = 0;
if (legendHeight > spaceHeight && !options.useHTML) {
this.clipHeight = clipHeight = mathMax(spaceHeight - 20 - this.titleHeight - this.padding, 0);
this.currentPage = pick(this.currentPage, 1);
this.fullHeight = legendHeight;
// Fill pages with Y positions so that the top of each a legend item defines
// the scroll top for each page (#2098)
each(allItems, function (item, i) {
var y = item._legendItemPos[1],
h = mathRound(item.legendItem.getBBox().height),
len = pages.length;
if (!len || (y - pages[len - 1] > clipHeight && (lastY || y) !== pages[len - 1])) {
pages.push(lastY || y);
len++;
}
if (i === allItems.length - 1 && y + h - pages[len - 1] > clipHeight) {
pages.push(y);
}
if (y !== lastY) {
lastY = y;
}
});
// Only apply clipping if needed. Clipping causes blurred legend in PDF export (#1787)
if (!clipRect) {
clipRect = legend.clipRect = renderer.clipRect(0, this.padding, 9999, 0);
legend.contentGroup.clip(clipRect);
}
clipRect.attr({
height: clipHeight
});
// Add navigation elements
if (!nav) {
this.nav = nav = renderer.g().attr({ zIndex: 1 }).add(this.group);
this.up = renderer.symbol('triangle', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(-1, animation);
})
.add(nav);
this.pager = renderer.text('', 15, 10)
.css(navOptions.style)
.add(nav);
this.down = renderer.symbol('triangle-down', 0, 0, arrowSize, arrowSize)
.on('click', function () {
legend.scroll(1, animation);
})
.add(nav);
}
// Set initial position
legend.scroll(0);
legendHeight = spaceHeight;
} else if (nav) {
clipRect.attr({
height: chart.chartHeight
});
nav.hide();
this.scrollGroup.attr({
translateY: 1
});
this.clipHeight = 0; // #1379
}
return legendHeight;
},
/**
* Scroll the legend by a number of pages
* @param {Object} scrollBy
* @param {Object} animation
*/
scroll: function (scrollBy, animation) {
var pages = this.pages,
pageCount = pages.length,
currentPage = this.currentPage + scrollBy,
clipHeight = this.clipHeight,
navOptions = this.options.navigation,
activeColor = navOptions.activeColor,
inactiveColor = navOptions.inactiveColor,
pager = this.pager,
padding = this.padding,
scrollOffset;
// When resizing while looking at the last page
if (currentPage > pageCount) {
currentPage = pageCount;
}
if (currentPage > 0) {
if (animation !== UNDEFINED) {
setAnimation(animation, this.chart);
}
this.nav.attr({
translateX: padding,
translateY: clipHeight + this.padding + 7 + this.titleHeight,
visibility: VISIBLE
});
this.up.attr({
fill: currentPage === 1 ? inactiveColor : activeColor
})
.css({
cursor: currentPage === 1 ? 'default' : 'pointer'
});
pager.attr({
text: currentPage + '/' + pageCount
});
this.down.attr({
x: 18 + this.pager.getBBox().width, // adjust to text width
fill: currentPage === pageCount ? inactiveColor : activeColor
})
.css({
cursor: currentPage === pageCount ? 'default' : 'pointer'
});
scrollOffset = -pages[currentPage - 1] + this.initialItemY;
this.scrollGroup.animate({
translateY: scrollOffset
});
this.currentPage = currentPage;
this.positionCheckboxes(scrollOffset);
}
}
};
/*
* LegendSymbolMixin
*/
var LegendSymbolMixin = Highcharts.LegendSymbolMixin = {
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawRectangle: function (legend, item) {
var symbolHeight = legend.options.symbolHeight || 12;
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 5 - (symbolHeight / 2),
legend.symbolWidth,
symbolHeight,
legend.options.symbolRadius || 0
).attr({
zIndex: 3
}).add(item.legendGroup);
},
/**
* Get the series' symbol in the legend. This method should be overridable to create custom
* symbols through Highcharts.seriesTypes[type].prototype.drawLegendSymbols.
*
* @param {Object} legend The legend object
*/
drawLineMarker: function (legend) {
var options = this.options,
markerOptions = options.marker,
radius,
legendOptions = legend.options,
legendSymbol,
symbolWidth = legend.symbolWidth,
renderer = this.chart.renderer,
legendItemGroup = this.legendGroup,
verticalCenter = legend.baseline - mathRound(renderer.fontMetrics(legendOptions.itemStyle.fontSize, this.legendItem).b * 0.3),
attr;
// Draw the line
if (options.lineWidth) {
attr = {
'stroke-width': options.lineWidth
};
if (options.dashStyle) {
attr.dashstyle = options.dashStyle;
}
this.legendLine = renderer.path([
M,
0,
verticalCenter,
L,
symbolWidth,
verticalCenter
])
.attr(attr)
.add(legendItemGroup);
}
// Draw the marker
if (markerOptions && markerOptions.enabled !== false) {
radius = markerOptions.radius;
this.legendSymbol = legendSymbol = renderer.symbol(
this.symbol,
(symbolWidth / 2) - radius,
verticalCenter - radius,
2 * radius,
2 * radius
)
.add(legendItemGroup);
legendSymbol.isMarker = true;
}
}
};
// Workaround for #2030, horizontal legend items not displaying in IE11 Preview,
// and for #2580, a similar drawing flaw in Firefox 26.
// TODO: Explore if there's a general cause for this. The problem may be related
// to nested group elements, as the legend item texts are within 4 group elements.
if (/Trident\/7\.0/.test(userAgent) || isFirefox) {
wrap(Legend.prototype, 'positionItem', function (proceed, item) {
var legend = this,
runPositionItem = function () { // If chart destroyed in sync, this is undefined (#2030)
if (item._legendItemPos) {
proceed.call(legend, item);
}
};
// Do it now, for export and to get checkbox placement
runPositionItem();
// Do it after to work around the core issue
setTimeout(runPositionItem);
});
}
/**
* The chart class
* @param {Object} options
* @param {Function} callback Function to run when the chart has loaded
*/
var Chart = Highcharts.Chart = function () {
this.init.apply(this, arguments);
};
Chart.prototype = {
/**
* Hook for modules
*/
callbacks: [],
/**
* Initialize the chart
*/
init: function (userOptions, callback) {
// Handle regular options
var options,
seriesOptions = userOptions.series; // skip merging data points to increase performance
userOptions.series = null;
options = merge(defaultOptions, userOptions); // do the merge
options.series = userOptions.series = seriesOptions; // set back the series data
this.userOptions = userOptions;
var optionsChart = options.chart;
// Create margin & spacing array
this.margin = this.splashArray('margin', optionsChart);
this.spacing = this.splashArray('spacing', optionsChart);
var chartEvents = optionsChart.events;
//this.runChartClick = chartEvents && !!chartEvents.click;
this.bounds = { h: {}, v: {} }; // Pixel data bounds for touch zoom
this.callback = callback;
this.isResizing = 0;
this.options = options;
//chartTitleOptions = UNDEFINED;
//chartSubtitleOptions = UNDEFINED;
this.axes = [];
this.series = [];
this.hasCartesianSeries = optionsChart.showAxes;
//this.axisOffset = UNDEFINED;
//this.maxTicks = UNDEFINED; // handle the greatest amount of ticks on grouped axes
//this.inverted = UNDEFINED;
//this.loadingShown = UNDEFINED;
//this.container = UNDEFINED;
//this.chartWidth = UNDEFINED;
//this.chartHeight = UNDEFINED;
//this.marginRight = UNDEFINED;
//this.marginBottom = UNDEFINED;
//this.containerWidth = UNDEFINED;
//this.containerHeight = UNDEFINED;
//this.oldChartWidth = UNDEFINED;
//this.oldChartHeight = UNDEFINED;
//this.renderTo = UNDEFINED;
//this.renderToClone = UNDEFINED;
//this.spacingBox = UNDEFINED
//this.legend = UNDEFINED;
// Elements
//this.chartBackground = UNDEFINED;
//this.plotBackground = UNDEFINED;
//this.plotBGImage = UNDEFINED;
//this.plotBorder = UNDEFINED;
//this.loadingDiv = UNDEFINED;
//this.loadingSpan = UNDEFINED;
var chart = this,
eventType;
// Add the chart to the global lookup
chart.index = charts.length;
charts.push(chart);
chartCount++;
// Set up auto resize
if (optionsChart.reflow !== false) {
addEvent(chart, 'load', function () {
chart.initReflow();
});
}
// Chart event handlers
if (chartEvents) {
for (eventType in chartEvents) {
addEvent(chart, eventType, chartEvents[eventType]);
}
}
chart.xAxis = [];
chart.yAxis = [];
// Expose methods and variables
chart.animation = useCanVG ? false : pick(optionsChart.animation, true);
chart.pointCount = chart.colorCounter = chart.symbolCounter = 0;
chart.firstRender();
},
/**
* Initialize an individual series, called internally before render time
*/
initSeries: function (options) {
var chart = this,
optionsChart = chart.options.chart,
type = options.type || optionsChart.type || optionsChart.defaultSeriesType,
series,
constr = seriesTypes[type];
// No such series type
if (!constr) {
error(17, true);
}
series = new constr();
series.init(this, options);
return series;
},
/**
* Check whether a given point is within the plot area
*
* @param {Number} plotX Pixel x relative to the plot area
* @param {Number} plotY Pixel y relative to the plot area
* @param {Boolean} inverted Whether the chart is inverted
*/
isInsidePlot: function (plotX, plotY, inverted) {
var x = inverted ? plotY : plotX,
y = inverted ? plotX : plotY;
return x >= 0 &&
x <= this.plotWidth &&
y >= 0 &&
y <= this.plotHeight;
},
/**
* Redraw legend, axes or series based on updated data
*
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
redraw: function (animation) {
var chart = this,
axes = chart.axes,
series = chart.series,
pointer = chart.pointer,
legend = chart.legend,
redrawLegend = chart.isDirtyLegend,
hasStackedSeries,
hasDirtyStacks,
hasCartesianSeries = chart.hasCartesianSeries,
isDirtyBox = chart.isDirtyBox, // todo: check if it has actually changed?
seriesLength = series.length,
i = seriesLength,
serie,
renderer = chart.renderer,
isHiddenChart = renderer.isHidden(),
afterRedraw = [];
setAnimation(animation, chart);
if (isHiddenChart) {
chart.cloneRenderTo();
}
// Adjust title layout (reflow multiline text)
chart.layOutTitles();
// link stacked series
while (i--) {
serie = series[i];
if (serie.options.stacking) {
hasStackedSeries = true;
if (serie.isDirty) {
hasDirtyStacks = true;
break;
}
}
}
if (hasDirtyStacks) { // mark others as dirty
i = seriesLength;
while (i--) {
serie = series[i];
if (serie.options.stacking) {
serie.isDirty = true;
}
}
}
// handle updated data in the series
each(series, function (serie) {
if (serie.isDirty) { // prepare the data so axis can read it
if (serie.options.legendType === 'point') {
redrawLegend = true;
}
}
});
// handle added or removed series
if (redrawLegend && legend.options.enabled) { // series or pie points are added or removed
// draw legend graphics
legend.render();
chart.isDirtyLegend = false;
}
// reset stacks
if (hasStackedSeries) {
chart.getStacks();
}
if (hasCartesianSeries) {
if (!chart.isResizing) {
// reset maxTicks
chart.maxTicks = null;
// set axes scales
each(axes, function (axis) {
axis.setScale();
});
}
}
chart.getMargins(); // #3098
if (hasCartesianSeries) {
// If one axis is dirty, all axes must be redrawn (#792, #2169)
each(axes, function (axis) {
if (axis.isDirty) {
isDirtyBox = true;
}
});
// redraw axes
each(axes, function (axis) {
// Fire 'afterSetExtremes' only if extremes are set
if (axis.isDirtyExtremes) { // #821
axis.isDirtyExtremes = false;
afterRedraw.push(function () { // prevent a recursive call to chart.redraw() (#1119)
fireEvent(axis, 'afterSetExtremes', extend(axis.eventArgs, axis.getExtremes())); // #747, #751
delete axis.eventArgs;
});
}
if (isDirtyBox || hasStackedSeries) {
axis.redraw();
}
});
}
// the plot areas size has changed
if (isDirtyBox) {
chart.drawChartBox();
}
// redraw affected series
each(series, function (serie) {
if (serie.isDirty && serie.visible &&
(!serie.isCartesian || serie.xAxis)) { // issue #153
serie.redraw();
}
});
// move tooltip or reset
if (pointer) {
pointer.reset(true);
}
// redraw if canvas
renderer.draw();
// fire the event
fireEvent(chart, 'redraw'); // jQuery breaks this when calling it from addEvent. Overwrites chart.redraw
if (isHiddenChart) {
chart.cloneRenderTo(true);
}
// Fire callbacks that are put on hold until after the redraw
each(afterRedraw, function (callback) {
callback.call();
});
},
/**
* Get an axis, series or point object by id.
* @param id {String} The id as given in the configuration options
*/
get: function (id) {
var chart = this,
axes = chart.axes,
series = chart.series;
var i,
j,
points;
// search axes
for (i = 0; i < axes.length; i++) {
if (axes[i].options.id === id) {
return axes[i];
}
}
// search series
for (i = 0; i < series.length; i++) {
if (series[i].options.id === id) {
return series[i];
}
}
// search points
for (i = 0; i < series.length; i++) {
points = series[i].points || [];
for (j = 0; j < points.length; j++) {
if (points[j].id === id) {
return points[j];
}
}
}
return null;
},
/**
* Create the Axis instances based on the config options
*/
getAxes: function () {
var chart = this,
options = this.options,
xAxisOptions = options.xAxis = splat(options.xAxis || {}),
yAxisOptions = options.yAxis = splat(options.yAxis || {}),
optionsArray,
axis;
// make sure the options are arrays and add some members
each(xAxisOptions, function (axis, i) {
axis.index = i;
axis.isX = true;
});
each(yAxisOptions, function (axis, i) {
axis.index = i;
});
// concatenate all axis options into one array
optionsArray = xAxisOptions.concat(yAxisOptions);
each(optionsArray, function (axisOptions) {
axis = new Axis(chart, axisOptions);
});
},
/**
* Get the currently selected points from all series
*/
getSelectedPoints: function () {
var points = [];
each(this.series, function (serie) {
points = points.concat(grep(serie.points || [], function (point) {
return point.selected;
}));
});
return points;
},
/**
* Get the currently selected series
*/
getSelectedSeries: function () {
return grep(this.series, function (serie) {
return serie.selected;
});
},
/**
* Generate stacks for each series and calculate stacks total values
*/
getStacks: function () {
var chart = this;
// reset stacks for each yAxis
each(chart.yAxis, function (axis) {
if (axis.stacks && axis.hasVisibleSeries) {
axis.oldStacks = axis.stacks;
}
});
each(chart.series, function (series) {
if (series.options.stacking && (series.visible === true || chart.options.chart.ignoreHiddenSeries === false)) {
series.stackKey = series.type + pick(series.options.stack, '');
}
});
},
/**
* Show the title and subtitle of the chart
*
* @param titleOptions {Object} New title options
* @param subtitleOptions {Object} New subtitle options
*
*/
setTitle: function (titleOptions, subtitleOptions, redraw) {
var chart = this,
options = chart.options,
chartTitleOptions,
chartSubtitleOptions;
chartTitleOptions = options.title = merge(options.title, titleOptions);
chartSubtitleOptions = options.subtitle = merge(options.subtitle, subtitleOptions);
// add title and subtitle
each([
['title', titleOptions, chartTitleOptions],
['subtitle', subtitleOptions, chartSubtitleOptions]
], function (arr) {
var name = arr[0],
title = chart[name],
titleOptions = arr[1],
chartTitleOptions = arr[2];
if (title && titleOptions) {
chart[name] = title = title.destroy(); // remove old
}
if (chartTitleOptions && chartTitleOptions.text && !title) {
chart[name] = chart.renderer.text(
chartTitleOptions.text,
0,
0,
chartTitleOptions.useHTML
)
.attr({
align: chartTitleOptions.align,
'class': PREFIX + name,
zIndex: chartTitleOptions.zIndex || 4
})
.css(chartTitleOptions.style)
.add();
}
});
chart.layOutTitles(redraw);
},
/**
* Lay out the chart titles and cache the full offset height for use in getMargins
*/
layOutTitles: function (redraw) {
var titleOffset = 0,
title = this.title,
subtitle = this.subtitle,
options = this.options,
titleOptions = options.title,
subtitleOptions = options.subtitle,
requiresDirtyBox,
renderer = this.renderer,
autoWidth = this.spacingBox.width - 44; // 44 makes room for default context button
if (title) {
title
.css({ width: (titleOptions.width || autoWidth) + PX })
.align(extend({
y: renderer.fontMetrics(titleOptions.style.fontSize, title).b - 3
}, titleOptions), false, 'spacingBox');
if (!titleOptions.floating && !titleOptions.verticalAlign) {
titleOffset = title.getBBox().height;
}
}
if (subtitle) {
subtitle
.css({ width: (subtitleOptions.width || autoWidth) + PX })
.align(extend({
y: titleOffset + (titleOptions.margin - 13) + renderer.fontMetrics(titleOptions.style.fontSize, subtitle).b
}, subtitleOptions), false, 'spacingBox');
if (!subtitleOptions.floating && !subtitleOptions.verticalAlign) {
titleOffset = mathCeil(titleOffset + subtitle.getBBox().height);
}
}
requiresDirtyBox = this.titleOffset !== titleOffset;
this.titleOffset = titleOffset; // used in getMargins
if (!this.isDirtyBox && requiresDirtyBox) {
this.isDirtyBox = requiresDirtyBox;
// Redraw if necessary (#2719, #2744)
if (this.hasRendered && pick(redraw, true) && this.isDirtyBox) {
this.redraw();
}
}
},
/**
* Get chart width and height according to options and container size
*/
getChartSize: function () {
var chart = this,
optionsChart = chart.options.chart,
widthOption = optionsChart.width,
heightOption = optionsChart.height,
renderTo = chart.renderToClone || chart.renderTo;
// get inner width and height from jQuery (#824)
if (!defined(widthOption)) {
chart.containerWidth = adapterRun(renderTo, 'width');
}
if (!defined(heightOption)) {
chart.containerHeight = adapterRun(renderTo, 'height');
}
chart.chartWidth = mathMax(0, widthOption || chart.containerWidth || 600); // #1393, 1460
chart.chartHeight = mathMax(0, pick(heightOption,
// the offsetHeight of an empty container is 0 in standard browsers, but 19 in IE7:
chart.containerHeight > 19 ? chart.containerHeight : 400));
},
/**
* Create a clone of the chart's renderTo div and place it outside the viewport to allow
* size computation on chart.render and chart.redraw
*/
cloneRenderTo: function (revert) {
var clone = this.renderToClone,
container = this.container;
// Destroy the clone and bring the container back to the real renderTo div
if (revert) {
if (clone) {
this.renderTo.appendChild(container);
discardElement(clone);
delete this.renderToClone;
}
// Set up the clone
} else {
if (container && container.parentNode === this.renderTo) {
this.renderTo.removeChild(container); // do not clone this
}
this.renderToClone = clone = this.renderTo.cloneNode(0);
css(clone, {
position: ABSOLUTE,
top: '-9999px',
display: 'block' // #833
});
if (clone.style.setProperty) { // #2631
clone.style.setProperty('display', 'block', 'important');
}
doc.body.appendChild(clone);
if (container) {
clone.appendChild(container);
}
}
},
/**
* Get the containing element, determine the size and create the inner container
* div to hold the chart
*/
getContainer: function () {
var chart = this,
container,
optionsChart = chart.options.chart,
chartWidth,
chartHeight,
renderTo,
indexAttrName = 'data-highcharts-chart',
oldChartIndex,
containerId;
chart.renderTo = renderTo = optionsChart.renderTo;
containerId = PREFIX + idCounter++;
if (isString(renderTo)) {
chart.renderTo = renderTo = doc.getElementById(renderTo);
}
// Display an error if the renderTo is wrong
if (!renderTo) {
error(13, true);
}
// If the container already holds a chart, destroy it. The check for hasRendered is there
// because web pages that are saved to disk from the browser, will preserve the data-highcharts-chart
// attribute and the SVG contents, but not an interactive chart. So in this case,
// charts[oldChartIndex] will point to the wrong chart if any (#2609).
oldChartIndex = pInt(attr(renderTo, indexAttrName));
if (!isNaN(oldChartIndex) && charts[oldChartIndex] && charts[oldChartIndex].hasRendered) {
charts[oldChartIndex].destroy();
}
// Make a reference to the chart from the div
attr(renderTo, indexAttrName, chart.index);
// remove previous chart
renderTo.innerHTML = '';
// If the container doesn't have an offsetWidth, it has or is a child of a node
// that has display:none. We need to temporarily move it out to a visible
// state to determine the size, else the legend and tooltips won't render
// properly. The allowClone option is used in sparklines as a micro optimization,
// saving about 1-2 ms each chart.
if (!optionsChart.skipClone && !renderTo.offsetWidth) {
chart.cloneRenderTo();
}
// get the width and height
chart.getChartSize();
chartWidth = chart.chartWidth;
chartHeight = chart.chartHeight;
// create the inner container
chart.container = container = createElement(DIV, {
className: PREFIX + 'container' +
(optionsChart.className ? ' ' + optionsChart.className : ''),
id: containerId
}, extend({
position: RELATIVE,
overflow: HIDDEN, // needed for context menu (avoid scrollbars) and
// content overflow in IE
width: chartWidth + PX,
height: chartHeight + PX,
textAlign: 'left',
lineHeight: 'normal', // #427
zIndex: 0, // #1072
'-webkit-tap-highlight-color': 'rgba(0,0,0,0)'
}, optionsChart.style),
chart.renderToClone || renderTo
);
// cache the cursor (#1650)
chart._cursor = container.style.cursor;
// Initialize the renderer
chart.renderer =
optionsChart.forExport ? // force SVG, used for SVG export
new SVGRenderer(container, chartWidth, chartHeight, optionsChart.style, true) :
new Renderer(container, chartWidth, chartHeight, optionsChart.style);
if (useCanVG) {
// If we need canvg library, extend and configure the renderer
// to get the tracker for translating mouse events
chart.renderer.create(chart, container, chartWidth, chartHeight);
}
// Add a reference to the charts index
chart.renderer.chartIndex = chart.index;
},
/**
* Calculate margins by rendering axis labels in a preliminary position. Title,
* subtitle and legend have already been rendered at this stage, but will be
* moved into their final positions
*/
getMargins: function (skipAxes) {
var chart = this,
spacing = chart.spacing,
margin = chart.margin,
titleOffset = chart.titleOffset;
chart.resetMargins();
// Adjust for title and subtitle
if (titleOffset && !defined(margin[0])) {
chart.plotTop = mathMax(chart.plotTop, titleOffset + chart.options.title.margin + spacing[0]);
}
// Adjust for legend
chart.legend.adjustMargins(margin, spacing);
// adjust for scroller
if (chart.extraBottomMargin) {
chart.marginBottom += chart.extraBottomMargin;
}
if (chart.extraTopMargin) {
chart.plotTop += chart.extraTopMargin;
}
if (!skipAxes) {
this.getAxisMargins();
}
},
getAxisMargins: function () {
var chart = this,
axisOffset = chart.axisOffset = [0, 0, 0, 0], // top, right, bottom, left
margin = chart.margin;
// pre-render axes to get labels offset width
if (chart.hasCartesianSeries) {
each(chart.axes, function (axis) {
axis.getOffset();
});
}
// Add the axis offsets
each(marginNames, function (m, side) {
if (!defined(margin[side])) {
chart[m] += axisOffset[side];
}
});
chart.setChartSize();
},
/**
* Resize the chart to its container if size is not explicitly set
*/
reflow: function (e) {
var chart = this,
optionsChart = chart.options.chart,
renderTo = chart.renderTo,
width = optionsChart.width || adapterRun(renderTo, 'width'),
height = optionsChart.height || adapterRun(renderTo, 'height'),
target = e ? e.target : win, // #805 - MooTools doesn't supply e
doReflow = function () {
if (chart.container) { // It may have been destroyed in the meantime (#1257)
chart.setSize(width, height, false);
chart.hasUserSize = null;
}
};
// Width and height checks for display:none. Target is doc in IE8 and Opera,
// win in Firefox, Chrome and IE9.
if (!chart.hasUserSize && width && height && (target === win || target === doc)) {
if (width !== chart.containerWidth || height !== chart.containerHeight) {
clearTimeout(chart.reflowTimeout);
if (e) { // Called from window.resize
chart.reflowTimeout = setTimeout(doReflow, 100);
} else { // Called directly (#2224)
doReflow();
}
}
chart.containerWidth = width;
chart.containerHeight = height;
}
},
/**
* Add the event handlers necessary for auto resizing
*/
initReflow: function () {
var chart = this,
reflow = function (e) {
chart.reflow(e);
};
addEvent(win, 'resize', reflow);
addEvent(chart, 'destroy', function () {
removeEvent(win, 'resize', reflow);
});
},
/**
* Resize the chart to a given width and height
* @param {Number} width
* @param {Number} height
* @param {Object|Boolean} animation
*/
setSize: function (width, height, animation) {
var chart = this,
chartWidth,
chartHeight,
fireEndResize;
// Handle the isResizing counter
chart.isResizing += 1;
fireEndResize = function () {
if (chart) {
fireEvent(chart, 'endResize', null, function () {
chart.isResizing -= 1;
});
}
};
// set the animation for the current process
setAnimation(animation, chart);
chart.oldChartHeight = chart.chartHeight;
chart.oldChartWidth = chart.chartWidth;
if (defined(width)) {
chart.chartWidth = chartWidth = mathMax(0, mathRound(width));
chart.hasUserSize = !!chartWidth;
}
if (defined(height)) {
chart.chartHeight = chartHeight = mathMax(0, mathRound(height));
}
// Resize the container with the global animation applied if enabled (#2503)
(globalAnimation ? animate : css)(chart.container, {
width: chartWidth + PX,
height: chartHeight + PX
}, globalAnimation);
chart.setChartSize(true);
chart.renderer.setSize(chartWidth, chartHeight, animation);
// handle axes
chart.maxTicks = null;
each(chart.axes, function (axis) {
axis.isDirty = true;
axis.setScale();
});
// make sure non-cartesian series are also handled
each(chart.series, function (serie) {
serie.isDirty = true;
});
chart.isDirtyLegend = true; // force legend redraw
chart.isDirtyBox = true; // force redraw of plot and chart border
chart.layOutTitles(); // #2857
chart.getMargins();
chart.redraw(animation);
chart.oldChartHeight = null;
fireEvent(chart, 'resize');
// fire endResize and set isResizing back
// If animation is disabled, fire without delay
if (globalAnimation === false) {
fireEndResize();
} else { // else set a timeout with the animation duration
setTimeout(fireEndResize, (globalAnimation && globalAnimation.duration) || 500);
}
},
/**
* Set the public chart properties. This is done before and after the pre-render
* to determine margin sizes
*/
setChartSize: function (skipAxes) {
var chart = this,
inverted = chart.inverted,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
optionsChart = chart.options.chart,
spacing = chart.spacing,
clipOffset = chart.clipOffset,
clipX,
clipY,
plotLeft,
plotTop,
plotWidth,
plotHeight,
plotBorderWidth;
chart.plotLeft = plotLeft = mathRound(chart.plotLeft);
chart.plotTop = plotTop = mathRound(chart.plotTop);
chart.plotWidth = plotWidth = mathMax(0, mathRound(chartWidth - plotLeft - chart.marginRight));
chart.plotHeight = plotHeight = mathMax(0, mathRound(chartHeight - plotTop - chart.marginBottom));
chart.plotSizeX = inverted ? plotHeight : plotWidth;
chart.plotSizeY = inverted ? plotWidth : plotHeight;
chart.plotBorderWidth = optionsChart.plotBorderWidth || 0;
// Set boxes used for alignment
chart.spacingBox = renderer.spacingBox = {
x: spacing[3],
y: spacing[0],
width: chartWidth - spacing[3] - spacing[1],
height: chartHeight - spacing[0] - spacing[2]
};
chart.plotBox = renderer.plotBox = {
x: plotLeft,
y: plotTop,
width: plotWidth,
height: plotHeight
};
plotBorderWidth = 2 * mathFloor(chart.plotBorderWidth / 2);
clipX = mathCeil(mathMax(plotBorderWidth, clipOffset[3]) / 2);
clipY = mathCeil(mathMax(plotBorderWidth, clipOffset[0]) / 2);
chart.clipBox = {
x: clipX,
y: clipY,
width: mathFloor(chart.plotSizeX - mathMax(plotBorderWidth, clipOffset[1]) / 2 - clipX),
height: mathMax(0, mathFloor(chart.plotSizeY - mathMax(plotBorderWidth, clipOffset[2]) / 2 - clipY))
};
if (!skipAxes) {
each(chart.axes, function (axis) {
axis.setAxisSize();
axis.setAxisTranslation();
});
}
},
/**
* Initial margins before auto size margins are applied
*/
resetMargins: function () {
var chart = this;
each(marginNames, function (m, side) {
chart[m] = pick(chart.margin[side], chart.spacing[side]);
});
chart.axisOffset = [0, 0, 0, 0]; // top, right, bottom, left
chart.clipOffset = [0, 0, 0, 0];
},
/**
* Draw the borders and backgrounds for chart and plot area
*/
drawChartBox: function () {
var chart = this,
optionsChart = chart.options.chart,
renderer = chart.renderer,
chartWidth = chart.chartWidth,
chartHeight = chart.chartHeight,
chartBackground = chart.chartBackground,
plotBackground = chart.plotBackground,
plotBorder = chart.plotBorder,
plotBGImage = chart.plotBGImage,
chartBorderWidth = optionsChart.borderWidth || 0,
chartBackgroundColor = optionsChart.backgroundColor,
plotBackgroundColor = optionsChart.plotBackgroundColor,
plotBackgroundImage = optionsChart.plotBackgroundImage,
plotBorderWidth = optionsChart.plotBorderWidth || 0,
mgn,
bgAttr,
plotLeft = chart.plotLeft,
plotTop = chart.plotTop,
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
plotBox = chart.plotBox,
clipRect = chart.clipRect,
clipBox = chart.clipBox;
// Chart area
mgn = chartBorderWidth + (optionsChart.shadow ? 8 : 0);
if (chartBorderWidth || chartBackgroundColor) {
if (!chartBackground) {
bgAttr = {
fill: chartBackgroundColor || NONE
};
if (chartBorderWidth) { // #980
bgAttr.stroke = optionsChart.borderColor;
bgAttr['stroke-width'] = chartBorderWidth;
}
chart.chartBackground = renderer.rect(mgn / 2, mgn / 2, chartWidth - mgn, chartHeight - mgn,
optionsChart.borderRadius, chartBorderWidth)
.attr(bgAttr)
.addClass(PREFIX + 'background')
.add()
.shadow(optionsChart.shadow);
} else { // resize
chartBackground.animate(
chartBackground.crisp({ width: chartWidth - mgn, height: chartHeight - mgn })
);
}
}
// Plot background
if (plotBackgroundColor) {
if (!plotBackground) {
chart.plotBackground = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0)
.attr({
fill: plotBackgroundColor
})
.add()
.shadow(optionsChart.plotShadow);
} else {
plotBackground.animate(plotBox);
}
}
if (plotBackgroundImage) {
if (!plotBGImage) {
chart.plotBGImage = renderer.image(plotBackgroundImage, plotLeft, plotTop, plotWidth, plotHeight)
.add();
} else {
plotBGImage.animate(plotBox);
}
}
// Plot clip
if (!clipRect) {
chart.clipRect = renderer.clipRect(clipBox);
} else {
clipRect.animate({
width: clipBox.width,
height: clipBox.height
});
}
// Plot area border
if (plotBorderWidth) {
if (!plotBorder) {
chart.plotBorder = renderer.rect(plotLeft, plotTop, plotWidth, plotHeight, 0, -plotBorderWidth)
.attr({
stroke: optionsChart.plotBorderColor,
'stroke-width': plotBorderWidth,
fill: NONE,
zIndex: 1
})
.add();
} else {
plotBorder.animate(
plotBorder.crisp({ x: plotLeft, y: plotTop, width: plotWidth, height: plotHeight, strokeWidth: -plotBorderWidth }) //#3282 plotBorder should be negative
);
}
}
// reset
chart.isDirtyBox = false;
},
/**
* Detect whether a certain chart property is needed based on inspecting its options
* and series. This mainly applies to the chart.invert property, and in extensions to
* the chart.angular and chart.polar properties.
*/
propFromSeries: function () {
var chart = this,
optionsChart = chart.options.chart,
klass,
seriesOptions = chart.options.series,
i,
value;
each(['inverted', 'angular', 'polar'], function (key) {
// The default series type's class
klass = seriesTypes[optionsChart.type || optionsChart.defaultSeriesType];
// Get the value from available chart-wide properties
value = (
chart[key] || // 1. it is set before
optionsChart[key] || // 2. it is set in the options
(klass && klass.prototype[key]) // 3. it's default series class requires it
);
// 4. Check if any the chart's series require it
i = seriesOptions && seriesOptions.length;
while (!value && i--) {
klass = seriesTypes[seriesOptions[i].type];
if (klass && klass.prototype[key]) {
value = true;
}
}
// Set the chart property
chart[key] = value;
});
},
/**
* Link two or more series together. This is done initially from Chart.render,
* and after Chart.addSeries and Series.remove.
*/
linkSeries: function () {
var chart = this,
chartSeries = chart.series;
// Reset links
each(chartSeries, function (series) {
series.linkedSeries.length = 0;
});
// Apply new links
each(chartSeries, function (series) {
var linkedTo = series.options.linkedTo;
if (isString(linkedTo)) {
if (linkedTo === ':previous') {
linkedTo = chart.series[series.index - 1];
} else {
linkedTo = chart.get(linkedTo);
}
if (linkedTo) {
linkedTo.linkedSeries.push(series);
series.linkedParent = linkedTo;
}
}
});
},
/**
* Render series for the chart
*/
renderSeries: function () {
each(this.series, function (serie) {
serie.translate();
serie.render();
});
},
/**
* Render labels for the chart
*/
renderLabels: function () {
var chart = this,
labels = chart.options.labels;
if (labels.items) {
each(labels.items, function (label) {
var style = extend(labels.style, label.style),
x = pInt(style.left) + chart.plotLeft,
y = pInt(style.top) + chart.plotTop + 12;
// delete to prevent rewriting in IE
delete style.left;
delete style.top;
chart.renderer.text(
label.html,
x,
y
)
.attr({ zIndex: 2 })
.css(style)
.add();
});
}
},
/**
* Render all graphics for the chart
*/
render: function () {
var chart = this,
axes = chart.axes,
renderer = chart.renderer,
options = chart.options,
tempWidth,
tempHeight,
redoHorizontal,
redoVertical;
// Title
chart.setTitle();
// Legend
chart.legend = new Legend(chart, options.legend);
chart.getStacks(); // render stacks
// Get chart margins
chart.getMargins(true);
chart.setChartSize();
// Record preliminary dimensions for later comparison
tempWidth = chart.plotWidth;
tempHeight = chart.plotHeight = chart.plotHeight - 13; // 13 is the most common height of X axis labels
// Get margins by pre-rendering axes
each(axes, function (axis) {
axis.setScale();
});
chart.getAxisMargins();
// If the plot area size has changed significantly, calculate tick positions again
redoHorizontal = tempWidth / chart.plotWidth > 1.2;
redoVertical = tempHeight / chart.plotHeight > 1.1;
if (redoHorizontal || redoVertical) {
chart.maxTicks = null; // reset for second pass
each(axes, function (axis) {
if ((axis.horiz && redoHorizontal) || (!axis.horiz && redoVertical)) {
axis.setTickInterval(true); // update to reflect the new margins
}
});
chart.getMargins(); // second pass to check for new labels
}
// Draw the borders and backgrounds
chart.drawChartBox();
// Axes
if (chart.hasCartesianSeries) {
each(axes, function (axis) {
axis.render();
});
}
// The series
if (!chart.seriesGroup) {
chart.seriesGroup = renderer.g('series-group')
.attr({ zIndex: 3 })
.add();
}
chart.renderSeries();
// Labels
chart.renderLabels();
// Credits
chart.showCredits(options.credits);
// Set flag
chart.hasRendered = true;
},
/**
* Show chart credits based on config options
*/
showCredits: function (credits) {
if (credits.enabled && !this.credits) {
this.credits = this.renderer.text(
credits.text,
0,
0
)
.on('click', function () {
if (credits.href) {
location.href = credits.href;
}
})
.attr({
align: credits.position.align,
zIndex: 8
})
.css(credits.style)
.add()
.align(credits.position);
}
},
/**
* Clean up memory usage
*/
destroy: function () {
var chart = this,
axes = chart.axes,
series = chart.series,
container = chart.container,
i,
parentNode = container && container.parentNode;
// fire the chart.destoy event
fireEvent(chart, 'destroy');
// Delete the chart from charts lookup array
charts[chart.index] = UNDEFINED;
chartCount--;
chart.renderTo.removeAttribute('data-highcharts-chart');
// remove events
removeEvent(chart);
// ==== Destroy collections:
// Destroy axes
i = axes.length;
while (i--) {
axes[i] = axes[i].destroy();
}
// Destroy each series
i = series.length;
while (i--) {
series[i] = series[i].destroy();
}
// ==== Destroy chart properties:
each(['title', 'subtitle', 'chartBackground', 'plotBackground', 'plotBGImage',
'plotBorder', 'seriesGroup', 'clipRect', 'credits', 'pointer', 'scroller',
'rangeSelector', 'legend', 'resetZoomButton', 'tooltip', 'renderer'], function (name) {
var prop = chart[name];
if (prop && prop.destroy) {
chart[name] = prop.destroy();
}
});
// remove container and all SVG
if (container) { // can break in IE when destroyed before finished loading
container.innerHTML = '';
removeEvent(container);
if (parentNode) {
discardElement(container);
}
}
// clean it all up
for (i in chart) {
delete chart[i];
}
},
/**
* VML namespaces can't be added until after complete. Listening
* for Perini's doScroll hack is not enough.
*/
isReadyToRender: function () {
var chart = this;
// Note: in spite of JSLint's complaints, win == win.top is required
/*jslint eqeq: true*/
if ((!hasSVG && (win == win.top && doc.readyState !== 'complete')) || (useCanVG && !win.canvg)) {
/*jslint eqeq: false*/
if (useCanVG) {
// Delay rendering until canvg library is downloaded and ready
CanVGController.push(function () { chart.firstRender(); }, chart.options.global.canvasToolsURL);
} else {
doc.attachEvent('onreadystatechange', function () {
doc.detachEvent('onreadystatechange', chart.firstRender);
if (doc.readyState === 'complete') {
chart.firstRender();
}
});
}
return false;
}
return true;
},
/**
* Prepare for first rendering after all data are loaded
*/
firstRender: function () {
var chart = this,
options = chart.options,
callback = chart.callback;
// Check whether the chart is ready to render
if (!chart.isReadyToRender()) {
return;
}
// Create the container
chart.getContainer();
// Run an early event after the container and renderer are established
fireEvent(chart, 'init');
chart.resetMargins();
chart.setChartSize();
// Set the common chart properties (mainly invert) from the given series
chart.propFromSeries();
// get axes
chart.getAxes();
// Initialize the series
each(options.series || [], function (serieOptions) {
chart.initSeries(serieOptions);
});
chart.linkSeries();
// Run an event after axes and series are initialized, but before render. At this stage,
// the series data is indexed and cached in the xData and yData arrays, so we can access
// those before rendering. Used in Highstock.
fireEvent(chart, 'beforeRender');
// depends on inverted and on margins being set
if (Highcharts.Pointer) {
chart.pointer = new Pointer(chart, options);
}
chart.render();
// add canvas
chart.renderer.draw();
// run callbacks
if (callback) {
callback.apply(chart, [chart]);
}
each(chart.callbacks, function (fn) {
if (chart.index !== UNDEFINED) { // Chart destroyed in its own callback (#3600)
fn.apply(chart, [chart]);
}
});
// Fire the load event
fireEvent(chart, 'load');
// If the chart was rendered outside the top container, put it back in (#3679)
chart.cloneRenderTo(true);
},
/**
* Creates arrays for spacing and margin from given options.
*/
splashArray: function (target, options) {
var oVar = options[target],
tArray = isObject(oVar) ? oVar : [oVar, oVar, oVar, oVar];
return [pick(options[target + 'Top'], tArray[0]),
pick(options[target + 'Right'], tArray[1]),
pick(options[target + 'Bottom'], tArray[2]),
pick(options[target + 'Left'], tArray[3])];
}
}; // end Chart
/**
* The Point object and prototype. Inheritable and used as base for PiePoint
*/
var Point = function () {};
Point.prototype = {
/**
* Initialize the point
* @param {Object} series The series object containing this point
* @param {Object} options The data in either number, array or object format
*/
init: function (series, options, x) {
var point = this,
colors;
point.series = series;
point.color = series.color; // #3445
point.applyOptions(options, x);
point.pointAttr = {};
if (series.options.colorByPoint) {
colors = series.options.colors || series.chart.options.colors;
point.color = point.color || colors[series.colorCounter++];
// loop back to zero
if (series.colorCounter === colors.length) {
series.colorCounter = 0;
}
}
series.chart.pointCount++;
return point;
},
/**
* Apply the options containing the x and y data and possible some extra properties.
* This is called on point init or from point.update.
*
* @param {Object} options
*/
applyOptions: function (options, x) {
var point = this,
series = point.series,
pointValKey = series.options.pointValKey || series.pointValKey;
options = Point.prototype.optionsToObject.call(this, options);
// copy options directly to point
extend(point, options);
point.options = point.options ? extend(point.options, options) : options;
// For higher dimension series types. For instance, for ranges, point.y is mapped to point.low.
if (pointValKey) {
point.y = point[pointValKey];
}
// If no x is set by now, get auto incremented value. All points must have an
// x value, however the y value can be null to create a gap in the series
if (point.x === UNDEFINED && series) {
point.x = x === UNDEFINED ? series.autoIncrement() : x;
}
return point;
},
/**
* Transform number or array configs into objects
*/
optionsToObject: function (options) {
var ret = {},
series = this.series,
pointArrayMap = series.pointArrayMap || ['y'],
valueCount = pointArrayMap.length,
firstItemType,
i = 0,
j = 0;
if (typeof options === 'number' || options === null) {
ret[pointArrayMap[0]] = options;
} else if (isArray(options)) {
// with leading x value
if (options.length > valueCount) {
firstItemType = typeof options[0];
if (firstItemType === 'string') {
ret.name = options[0];
} else if (firstItemType === 'number') {
ret.x = options[0];
}
i++;
}
while (j < valueCount) {
ret[pointArrayMap[j++]] = options[i++];
}
} else if (typeof options === 'object') {
ret = options;
// This is the fastest way to detect if there are individual point dataLabels that need
// to be considered in drawDataLabels. These can only occur in object configs.
if (options.dataLabels) {
series._hasPointLabels = true;
}
// Same approach as above for markers
if (options.marker) {
series._hasPointMarkers = true;
}
}
return ret;
},
/**
* Destroy a point to clear memory. Its reference still stays in series.data.
*/
destroy: function () {
var point = this,
series = point.series,
chart = series.chart,
hoverPoints = chart.hoverPoints,
prop;
chart.pointCount--;
if (hoverPoints) {
point.setState();
erase(hoverPoints, point);
if (!hoverPoints.length) {
chart.hoverPoints = null;
}
}
if (point === chart.hoverPoint) {
point.onMouseOut();
}
// remove all events
if (point.graphic || point.dataLabel) { // removeEvent and destroyElements are performance expensive
removeEvent(point);
point.destroyElements();
}
if (point.legendItem) { // pies have legend items
chart.legend.destroyItem(point);
}
for (prop in point) {
point[prop] = null;
}
},
/**
* Destroy SVG elements associated with the point
*/
destroyElements: function () {
var point = this,
props = ['graphic', 'dataLabel', 'dataLabelUpper', 'group', 'connector', 'shadowGroup'],
prop,
i = 6;
while (i--) {
prop = props[i];
if (point[prop]) {
point[prop] = point[prop].destroy();
}
}
},
/**
* Return the configuration hash needed for the data label and tooltip formatters
*/
getLabelConfig: function () {
var point = this;
return {
x: point.category,
y: point.y,
key: point.name || point.category,
series: point.series,
point: point,
percentage: point.percentage,
total: point.total || point.stackTotal
};
},
/**
* Extendable method for formatting each point's tooltip line
*
* @return {String} A string to be concatenated in to the common tooltip text
*/
tooltipFormatter: function (pointFormat) {
// Insert options for valueDecimals, valuePrefix, and valueSuffix
var series = this.series,
seriesTooltipOptions = series.tooltipOptions,
valueDecimals = pick(seriesTooltipOptions.valueDecimals, ''),
valuePrefix = seriesTooltipOptions.valuePrefix || '',
valueSuffix = seriesTooltipOptions.valueSuffix || '';
// Loop over the point array map and replace unformatted values with sprintf formatting markup
each(series.pointArrayMap || ['y'], function (key) {
key = '{point.' + key; // without the closing bracket
if (valuePrefix || valueSuffix) {
pointFormat = pointFormat.replace(key + '}', valuePrefix + key + '}' + valueSuffix);
}
pointFormat = pointFormat.replace(key + '}', key + ':,.' + valueDecimals + 'f}');
});
return format(pointFormat, {
point: this,
series: this.series
});
},
/**
* Fire an event on the Point object. Must not be renamed to fireEvent, as this
* causes a name clash in MooTools
* @param {String} eventType
* @param {Object} eventArgs Additional event arguments
* @param {Function} defaultFunction Default event handler
*/
firePointEvent: function (eventType, eventArgs, defaultFunction) {
var point = this,
series = this.series,
seriesOptions = series.options;
// load event handlers on demand to save time on mouseover/out
if (seriesOptions.point.events[eventType] || (point.options && point.options.events && point.options.events[eventType])) {
this.importEvents();
}
// add default handler if in selection mode
if (eventType === 'click' && seriesOptions.allowPointSelect) {
defaultFunction = function (event) {
// Control key is for Windows, meta (= Cmd key) for Mac, Shift for Opera
point.select(null, event.ctrlKey || event.metaKey || event.shiftKey);
};
}
fireEvent(this, eventType, eventArgs, defaultFunction);
}
};/**
* @classDescription The base function which all other series types inherit from. The data in the series is stored
* in various arrays.
*
* - First, series.options.data contains all the original config options for
* each point whether added by options or methods like series.addPoint.
* - Next, series.data contains those values converted to points, but in case the series data length
* exceeds the cropThreshold, or if the data is grouped, series.data doesn't contain all the points. It
* only contains the points that have been created on demand.
* - Then there's series.points that contains all currently visible point objects. In case of cropping,
* the cropped-away points are not part of this array. The series.points array starts at series.cropStart
* compared to series.data and series.options.data. If however the series data is grouped, these can't
* be correlated one to one.
* - series.xData and series.processedXData contain clean x values, equivalent to series.data and series.points.
* - series.yData and series.processedYData contain clean x values, equivalent to series.data and series.points.
*
* @param {Object} chart
* @param {Object} options
*/
var Series = Highcharts.Series = function () {};
Series.prototype = {
isCartesian: true,
type: 'line',
pointClass: Point,
sorted: true, // requires the data to be sorted
requireSorting: true,
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'lineColor',
'stroke-width': 'lineWidth',
fill: 'fillColor',
r: 'radius'
},
axisTypes: ['xAxis', 'yAxis'],
colorCounter: 0,
parallelArrays: ['x', 'y'], // each point's x and y values are stored in this.xData and this.yData
init: function (chart, options) {
var series = this,
eventType,
events,
chartSeries = chart.series,
sortByIndex = function (a, b) {
return pick(a.options.index, a._i) - pick(b.options.index, b._i);
};
series.chart = chart;
series.options = options = series.setOptions(options); // merge with plotOptions
series.linkedSeries = [];
// bind the axes
series.bindAxes();
// set some variables
extend(series, {
name: options.name,
state: NORMAL_STATE,
pointAttr: {},
visible: options.visible !== false, // true by default
selected: options.selected === true // false by default
});
// special
if (useCanVG) {
options.animation = false;
}
// register event listeners
events = options.events;
for (eventType in events) {
addEvent(series, eventType, events[eventType]);
}
if (
(events && events.click) ||
(options.point && options.point.events && options.point.events.click) ||
options.allowPointSelect
) {
chart.runTrackerClick = true;
}
series.getColor();
series.getSymbol();
// Set the data
each(series.parallelArrays, function (key) {
series[key + 'Data'] = [];
});
series.setData(options.data, false);
// Mark cartesian
if (series.isCartesian) {
chart.hasCartesianSeries = true;
}
// Register it in the chart
chartSeries.push(series);
series._i = chartSeries.length - 1;
// Sort series according to index option (#248, #1123, #2456)
stableSort(chartSeries, sortByIndex);
if (this.yAxis) {
stableSort(this.yAxis.series, sortByIndex);
}
each(chartSeries, function (series, i) {
series.index = i;
series.name = series.name || 'Series ' + (i + 1);
});
},
/**
* Set the xAxis and yAxis properties of cartesian series, and register the series
* in the axis.series array
*/
bindAxes: function () {
var series = this,
seriesOptions = series.options,
chart = series.chart,
axisOptions;
each(series.axisTypes || [], function (AXIS) { // repeat for xAxis and yAxis
each(chart[AXIS], function (axis) { // loop through the chart's axis objects
axisOptions = axis.options;
// apply if the series xAxis or yAxis option mathches the number of the
// axis, or if undefined, use the first axis
if ((seriesOptions[AXIS] === axisOptions.index) ||
(seriesOptions[AXIS] !== UNDEFINED && seriesOptions[AXIS] === axisOptions.id) ||
(seriesOptions[AXIS] === UNDEFINED && axisOptions.index === 0)) {
// register this series in the axis.series lookup
axis.series.push(series);
// set this series.xAxis or series.yAxis reference
series[AXIS] = axis;
// mark dirty for redraw
axis.isDirty = true;
}
});
// The series needs an X and an Y axis
if (!series[AXIS] && series.optionalAxis !== AXIS) {
error(18, true);
}
});
},
/**
* For simple series types like line and column, the data values are held in arrays like
* xData and yData for quick lookup to find extremes and more. For multidimensional series
* like bubble and map, this can be extended with arrays like zData and valueData by
* adding to the series.parallelArrays array.
*/
updateParallelArrays: function (point, i) {
var series = point.series,
args = arguments,
fn = typeof i === 'number' ?
// Insert the value in the given position
function (key) {
var val = key === 'y' && series.toYData ? series.toYData(point) : point[key];
series[key + 'Data'][i] = val;
} :
// Apply the method specified in i with the following arguments as arguments
function (key) {
Array.prototype[i].apply(series[key + 'Data'], Array.prototype.slice.call(args, 2));
};
each(series.parallelArrays, fn);
},
/**
* Return an auto incremented x value based on the pointStart and pointInterval options.
* This is only used if an x value is not given for the point that calls autoIncrement.
*/
autoIncrement: function () {
var options = this.options,
xIncrement = this.xIncrement,
date,
pointInterval,
pointIntervalUnit = options.pointIntervalUnit;
xIncrement = pick(xIncrement, options.pointStart, 0);
this.pointInterval = pointInterval = pick(this.pointInterval, options.pointInterval, 1);
// Added code for pointInterval strings
if (pointIntervalUnit === 'month' || pointIntervalUnit === 'year') {
date = new Date(xIncrement);
date = (pointIntervalUnit === 'month') ?
+date[setMonth](date[getMonth]() + pointInterval) :
+date[setFullYear](date[getFullYear]() + pointInterval);
pointInterval = date - xIncrement;
}
this.xIncrement = xIncrement + pointInterval;
return xIncrement;
},
/**
* Divide the series data into segments divided by null values.
*/
getSegments: function () {
var series = this,
lastNull = -1,
segments = [],
i,
points = series.points,
pointsLength = points.length;
if (pointsLength) { // no action required for []
// if connect nulls, just remove null points
if (series.options.connectNulls) {
i = pointsLength;
while (i--) {
if (points[i].y === null) {
points.splice(i, 1);
}
}
if (points.length) {
segments = [points];
}
// else, split on null points
} else {
each(points, function (point, i) {
if (point.y === null) {
if (i > lastNull + 1) {
segments.push(points.slice(lastNull + 1, i));
}
lastNull = i;
} else if (i === pointsLength - 1) { // last value
segments.push(points.slice(lastNull + 1, i + 1));
}
});
}
}
// register it
series.segments = segments;
},
/**
* Set the series options by merging from the options tree
* @param {Object} itemOptions
*/
setOptions: function (itemOptions) {
var chart = this.chart,
chartOptions = chart.options,
plotOptions = chartOptions.plotOptions,
userOptions = chart.userOptions || {},
userPlotOptions = userOptions.plotOptions || {},
typeOptions = plotOptions[this.type],
options,
zones;
this.userOptions = itemOptions;
options = merge(
typeOptions,
plotOptions.series,
itemOptions
);
// The tooltip options are merged between global and series specific options
this.tooltipOptions = merge(
defaultOptions.tooltip,
defaultOptions.plotOptions[this.type].tooltip,
userOptions.tooltip,
userPlotOptions.series && userPlotOptions.series.tooltip,
userPlotOptions[this.type] && userPlotOptions[this.type].tooltip,
itemOptions.tooltip
);
// Delete marker object if not allowed (#1125)
if (typeOptions.marker === null) {
delete options.marker;
}
// Handle color zones
this.zoneAxis = options.zoneAxis;
zones = this.zones = (options.zones || []).slice();
if ((options.negativeColor || options.negativeFillColor) && !options.zones) {
zones.push({
value: options[this.zoneAxis + 'Threshold'] || options.threshold || 0,
color: options.negativeColor,
fillColor: options.negativeFillColor
});
}
if (zones.length) { // Push one extra zone for the rest
if (defined(zones[zones.length - 1].value)) {
zones.push({
color: this.color,
fillColor: this.fillColor
});
}
}
return options;
},
getCyclic: function (prop, value, defaults) {
var i,
userOptions = this.userOptions,
indexName = '_' + prop + 'Index',
counterName = prop + 'Counter';
if (!value) {
if (defined(userOptions[indexName])) { // after Series.update()
i = userOptions[indexName];
} else {
userOptions[indexName] = i = this.chart[counterName] % defaults.length;
this.chart[counterName] += 1;
}
value = defaults[i];
}
this[prop] = value;
},
/**
* Get the series' color
*/
getColor: function () {
if (!this.options.colorByPoint) {
this.getCyclic('color', this.options.color || defaultPlotOptions[this.type].color, this.chart.options.colors);
}
},
/**
* Get the series' symbol
*/
getSymbol: function () {
var seriesMarkerOption = this.options.marker;
this.getCyclic('symbol', seriesMarkerOption.symbol, this.chart.options.symbols);
// don't substract radius in image symbols (#604)
if (/^url/.test(this.symbol)) {
seriesMarkerOption.radius = 0;
}
},
drawLegendSymbol: LegendSymbolMixin.drawLineMarker,
/**
* Replace the series data with a new set of data
* @param {Object} data
* @param {Object} redraw
*/
setData: function (data, redraw, animation, updatePoints) {
var series = this,
oldData = series.points,
oldDataLength = (oldData && oldData.length) || 0,
dataLength,
options = series.options,
chart = series.chart,
firstPoint = null,
xAxis = series.xAxis,
hasCategories = xAxis && !!xAxis.categories,
i,
turboThreshold = options.turboThreshold,
pt,
xData = this.xData,
yData = this.yData,
pointArrayMap = series.pointArrayMap,
valueCount = pointArrayMap && pointArrayMap.length;
data = data || [];
dataLength = data.length;
redraw = pick(redraw, true);
// If the point count is the same as is was, just run Point.update which is
// cheaper, allows animation, and keeps references to points.
if (updatePoints !== false && dataLength && oldDataLength === dataLength && !series.cropped && !series.hasGroupedData && series.visible) {
each(data, function (point, i) {
oldData[i].update(point, false, null, false);
});
} else {
// Reset properties
series.xIncrement = null;
series.pointRange = hasCategories ? 1 : options.pointRange;
series.colorCounter = 0; // for series with colorByPoint (#1547)
// Update parallel arrays
each(this.parallelArrays, function (key) {
series[key + 'Data'].length = 0;
});
// In turbo mode, only one- or twodimensional arrays of numbers are allowed. The
// first value is tested, and we assume that all the rest are defined the same
// way. Although the 'for' loops are similar, they are repeated inside each
// if-else conditional for max performance.
if (turboThreshold && dataLength > turboThreshold) {
// find the first non-null point
i = 0;
while (firstPoint === null && i < dataLength) {
firstPoint = data[i];
i++;
}
if (isNumber(firstPoint)) { // assume all points are numbers
var x = pick(options.pointStart, 0),
pointInterval = pick(options.pointInterval, 1);
for (i = 0; i < dataLength; i++) {
xData[i] = x;
yData[i] = data[i];
x += pointInterval;
}
series.xIncrement = x;
} else if (isArray(firstPoint)) { // assume all points are arrays
if (valueCount) { // [x, low, high] or [x, o, h, l, c]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt.slice(1, valueCount + 1);
}
} else { // [x, y]
for (i = 0; i < dataLength; i++) {
pt = data[i];
xData[i] = pt[0];
yData[i] = pt[1];
}
}
} else {
error(12); // Highcharts expects configs to be numbers or arrays in turbo mode
}
} else {
for (i = 0; i < dataLength; i++) {
if (data[i] !== UNDEFINED) { // stray commas in oldIE
pt = { series: series };
series.pointClass.prototype.applyOptions.apply(pt, [data[i]]);
series.updateParallelArrays(pt, i);
if (hasCategories && pt.name) {
xAxis.names[pt.x] = pt.name; // #2046
}
}
}
}
// Forgetting to cast strings to numbers is a common caveat when handling CSV or JSON
if (isString(yData[0])) {
error(14, true);
}
series.data = [];
series.options.data = data;
//series.zData = zData;
// destroy old points
i = oldDataLength;
while (i--) {
if (oldData[i] && oldData[i].destroy) {
oldData[i].destroy();
}
}
// reset minRange (#878)
if (xAxis) {
xAxis.minRange = xAxis.userMinRange;
}
// redraw
series.isDirty = series.isDirtyData = chart.isDirtyBox = true;
animation = false;
}
if (redraw) {
chart.redraw(animation);
}
},
/**
* Process the data by cropping away unused data points if the series is longer
* than the crop threshold. This saves computing time for lage series.
*/
processData: function (force) {
var series = this,
processedXData = series.xData, // copied during slice operation below
processedYData = series.yData,
dataLength = processedXData.length,
croppedData,
cropStart = 0,
cropped,
distance,
closestPointRange,
xAxis = series.xAxis,
i, // loop variable
options = series.options,
cropThreshold = options.cropThreshold,
isCartesian = series.isCartesian,
xExtremes,
min,
max;
// If the series data or axes haven't changed, don't go through this. Return false to pass
// the message on to override methods like in data grouping.
if (isCartesian && !series.isDirty && !xAxis.isDirty && !series.yAxis.isDirty && !force) {
return false;
}
if (xAxis) {
xExtremes = xAxis.getExtremes(); // corrected for log axis (#3053)
min = xExtremes.min;
max = xExtremes.max;
}
// optionally filter out points outside the plot area
if (isCartesian && series.sorted && (!cropThreshold || dataLength > cropThreshold || series.forceCrop)) {
// it's outside current extremes
if (processedXData[dataLength - 1] < min || processedXData[0] > max) {
processedXData = [];
processedYData = [];
// only crop if it's actually spilling out
} else if (processedXData[0] < min || processedXData[dataLength - 1] > max) {
croppedData = this.cropData(series.xData, series.yData, min, max);
processedXData = croppedData.xData;
processedYData = croppedData.yData;
cropStart = croppedData.start;
cropped = true;
}
}
// Find the closest distance between processed points
for (i = processedXData.length - 1; i >= 0; i--) {
distance = processedXData[i] - processedXData[i - 1];
if (distance > 0 && (closestPointRange === UNDEFINED || distance < closestPointRange)) {
closestPointRange = distance;
// Unsorted data is not supported by the line tooltip, as well as data grouping and
// navigation in Stock charts (#725) and width calculation of columns (#1900)
} else if (distance < 0 && series.requireSorting) {
error(15);
}
}
// Record the properties
series.cropped = cropped; // undefined or true
series.cropStart = cropStart;
series.processedXData = processedXData;
series.processedYData = processedYData;
if (options.pointRange === null) { // null means auto, as for columns, candlesticks and OHLC
series.pointRange = closestPointRange || 1;
}
series.closestPointRange = closestPointRange;
},
/**
* Iterate over xData and crop values between min and max. Returns object containing crop start/end
* cropped xData with corresponding part of yData, dataMin and dataMax within the cropped range
*/
cropData: function (xData, yData, min, max) {
var dataLength = xData.length,
cropStart = 0,
cropEnd = dataLength,
cropShoulder = pick(this.cropShoulder, 1), // line-type series need one point outside
i;
// iterate up to find slice start
for (i = 0; i < dataLength; i++) {
if (xData[i] >= min) {
cropStart = mathMax(0, i - cropShoulder);
break;
}
}
// proceed to find slice end
for (; i < dataLength; i++) {
if (xData[i] > max) {
cropEnd = i + cropShoulder;
break;
}
}
return {
xData: xData.slice(cropStart, cropEnd),
yData: yData.slice(cropStart, cropEnd),
start: cropStart,
end: cropEnd
};
},
/**
* Generate the data point after the data has been processed by cropping away
* unused points and optionally grouped in Highcharts Stock.
*/
generatePoints: function () {
var series = this,
options = series.options,
dataOptions = options.data,
data = series.data,
dataLength,
processedXData = series.processedXData,
processedYData = series.processedYData,
pointClass = series.pointClass,
processedDataLength = processedXData.length,
cropStart = series.cropStart || 0,
cursor,
hasGroupedData = series.hasGroupedData,
point,
points = [],
i;
if (!data && !hasGroupedData) {
var arr = [];
arr.length = dataOptions.length;
data = series.data = arr;
}
for (i = 0; i < processedDataLength; i++) {
cursor = cropStart + i;
if (!hasGroupedData) {
if (data[cursor]) {
point = data[cursor];
} else if (dataOptions[cursor] !== UNDEFINED) { // #970
data[cursor] = point = (new pointClass()).init(series, dataOptions[cursor], processedXData[i]);
}
points[i] = point;
} else {
// splat the y data in case of ohlc data array
points[i] = (new pointClass()).init(series, [processedXData[i]].concat(splat(processedYData[i])));
}
points[i].index = cursor; // For faster access in Point.update
}
// Hide cropped-away points - this only runs when the number of points is above cropThreshold, or when
// swithching view from non-grouped data to grouped data (#637)
if (data && (processedDataLength !== (dataLength = data.length) || hasGroupedData)) {
for (i = 0; i < dataLength; i++) {
if (i === cropStart && !hasGroupedData) { // when has grouped data, clear all points
i += processedDataLength;
}
if (data[i]) {
data[i].destroyElements();
data[i].plotX = UNDEFINED; // #1003
}
}
}
series.data = data;
series.points = points;
},
/**
* Calculate Y extremes for visible data
*/
getExtremes: function (yData) {
var xAxis = this.xAxis,
yAxis = this.yAxis,
xData = this.processedXData,
yDataLength,
activeYData = [],
activeCounter = 0,
xExtremes = xAxis.getExtremes(), // #2117, need to compensate for log X axis
xMin = xExtremes.min,
xMax = xExtremes.max,
validValue,
withinRange,
dataMin,
dataMax,
x,
y,
i,
j;
yData = yData || this.stackedYData || this.processedYData;
yDataLength = yData.length;
for (i = 0; i < yDataLength; i++) {
x = xData[i];
y = yData[i];
// For points within the visible range, including the first point outside the
// visible range, consider y extremes
validValue = y !== null && y !== UNDEFINED && (!yAxis.isLog || (y.length || y > 0));
withinRange = this.getExtremesFromAll || this.cropped || ((xData[i + 1] || x) >= xMin &&
(xData[i - 1] || x) <= xMax);
if (validValue && withinRange) {
j = y.length;
if (j) { // array, like ohlc or range data
while (j--) {
if (y[j] !== null) {
activeYData[activeCounter++] = y[j];
}
}
} else {
activeYData[activeCounter++] = y;
}
}
}
this.dataMin = pick(dataMin, arrayMin(activeYData));
this.dataMax = pick(dataMax, arrayMax(activeYData));
},
/**
* Translate data points from raw data values to chart specific positioning data
* needed later in drawPoints, drawGraph and drawTracker.
*/
translate: function () {
if (!this.processedXData) { // hidden series
this.processData();
}
this.generatePoints();
var series = this,
options = series.options,
stacking = options.stacking,
xAxis = series.xAxis,
categories = xAxis.categories,
yAxis = series.yAxis,
points = series.points,
dataLength = points.length,
hasModifyValue = !!series.modifyValue,
i,
pointPlacement = options.pointPlacement,
dynamicallyPlaced = pointPlacement === 'between' || isNumber(pointPlacement),
threshold = options.threshold,
plotX,
plotY,
lastPlotX,
closestPointRangePx = Number.MAX_VALUE;
// Translate each point
for (i = 0; i < dataLength; i++) {
var point = points[i],
xValue = point.x,
yValue = point.y,
yBottom = point.low,
stack = stacking && yAxis.stacks[(series.negStacks && yValue < threshold ? '-' : '') + series.stackKey],
pointStack,
stackValues;
// Discard disallowed y values for log axes (#3434)
if (yAxis.isLog && yValue !== null && yValue <= 0) {
point.y = yValue = null;
error(10);
}
// Get the plotX translation
point.plotX = plotX = xAxis.translate(xValue, 0, 0, 0, 1, pointPlacement, this.type === 'flags'); // Math.round fixes #591
// Calculate the bottom y value for stacked series
if (stacking && series.visible && stack && stack[xValue]) {
pointStack = stack[xValue];
stackValues = pointStack.points[series.index + ',' + i];
yBottom = stackValues[0];
yValue = stackValues[1];
if (yBottom === 0) {
yBottom = pick(threshold, yAxis.min);
}
if (yAxis.isLog && yBottom <= 0) { // #1200, #1232
yBottom = null;
}
point.total = point.stackTotal = pointStack.total;
point.percentage = pointStack.total && (point.y / pointStack.total * 100);
point.stackY = yValue;
// Place the stack label
pointStack.setOffset(series.pointXOffset || 0, series.barW || 0);
}
// Set translated yBottom or remove it
point.yBottom = defined(yBottom) ?
yAxis.translate(yBottom, 0, 1, 0, 1) :
null;
// general hook, used for Highstock compare mode
if (hasModifyValue) {
yValue = series.modifyValue(yValue, point);
}
// Set the the plotY value, reset it for redraws
point.plotY = plotY = (typeof yValue === 'number' && yValue !== Infinity) ?
mathMin(mathMax(-1e5, yAxis.translate(yValue, 0, 1, 0, 1)), 1e5) : // #3201
UNDEFINED;
point.isInside = plotY !== UNDEFINED && plotY >= 0 && plotY <= yAxis.len && // #3519
plotX >= 0 && plotX <= xAxis.len;
// Set client related positions for mouse tracking
point.clientX = dynamicallyPlaced ? xAxis.translate(xValue, 0, 0, 0, 1) : plotX; // #1514
point.negative = point.y < (threshold || 0);
// some API data
point.category = categories && categories[point.x] !== UNDEFINED ?
categories[point.x] : point.x;
// Determine auto enabling of markers (#3635)
if (i) {
closestPointRangePx = mathMin(closestPointRangePx, mathAbs(plotX - lastPlotX));
}
lastPlotX = plotX;
}
series.closestPointRangePx = closestPointRangePx;
// now that we have the cropped data, build the segments
series.getSegments();
},
/**
* Set the clipping for the series. For animated series it is called twice, first to initiate
* animating the clip then the second time without the animation to set the final clip.
*/
setClip: function (animation) {
var chart = this.chart,
renderer = chart.renderer,
inverted = chart.inverted,
seriesClipBox = this.clipBox,
clipBox = seriesClipBox || chart.clipBox,
sharedClipKey = this.sharedClipKey || ['_sharedClip', animation && animation.duration, animation && animation.easing, clipBox.height].join(','),
clipRect = chart[sharedClipKey],
markerClipRect = chart[sharedClipKey + 'm'];
// If a clipping rectangle with the same properties is currently present in the chart, use that.
if (!clipRect) {
// When animation is set, prepare the initial positions
if (animation) {
clipBox.width = 0;
chart[sharedClipKey + 'm'] = markerClipRect = renderer.clipRect(
-99, // include the width of the first marker
inverted ? -chart.plotLeft : -chart.plotTop,
99,
inverted ? chart.chartWidth : chart.chartHeight
);
}
chart[sharedClipKey] = clipRect = renderer.clipRect(clipBox);
}
clipRect.count += 1;
if (this.options.clip !== false) {
this.group.clip(animation || seriesClipBox ? clipRect : chart.clipRect);
this.markerGroup.clip(markerClipRect);
this.sharedClipKey = sharedClipKey;
}
// Remove the shared clipping rectancgle when all series are shown
if (!animation) {
clipRect.count -= 1;
if (clipRect.count === 0 && sharedClipKey && chart[sharedClipKey]) {
if (!seriesClipBox) {
chart[sharedClipKey] = chart[sharedClipKey].destroy();
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'] = chart[sharedClipKey + 'm'].destroy();
}
}
}
},
/**
* Animate in the series
*/
animate: function (init) {
var series = this,
chart = series.chart,
clipRect,
animation = series.options.animation,
sharedClipKey;
// Animation option is set to true
if (animation && !isObject(animation)) {
animation = defaultPlotOptions[series.type].animation;
}
// Initialize the animation. Set up the clipping rectangle.
if (init) {
series.setClip(animation);
// Run the animation
} else {
sharedClipKey = this.sharedClipKey;
clipRect = chart[sharedClipKey];
if (clipRect) {
clipRect.animate({
width: chart.plotSizeX
}, animation);
}
if (chart[sharedClipKey + 'm']) {
chart[sharedClipKey + 'm'].animate({
width: chart.plotSizeX + 99
}, animation);
}
// Delete this function to allow it only once
series.animate = null;
}
},
/**
* This runs after animation to land on the final plot clipping
*/
afterAnimate: function () {
this.setClip();
fireEvent(this, 'afterAnimate');
},
/**
* Draw the markers
*/
drawPoints: function () {
var series = this,
pointAttr,
points = series.points,
chart = series.chart,
plotX,
plotY,
i,
point,
radius,
symbol,
isImage,
graphic,
options = series.options,
seriesMarkerOptions = options.marker,
seriesPointAttr = series.pointAttr[''],
pointMarkerOptions,
hasPointMarker,
enabled,
isInside,
markerGroup = series.markerGroup,
xAxis = series.xAxis,
globallyEnabled = pick(
seriesMarkerOptions.enabled,
xAxis.isRadial,
series.closestPointRangePx > 2 * seriesMarkerOptions.radius
);
if (seriesMarkerOptions.enabled !== false || series._hasPointMarkers) {
i = points.length;
while (i--) {
point = points[i];
plotX = mathFloor(point.plotX); // #1843
plotY = point.plotY;
graphic = point.graphic;
pointMarkerOptions = point.marker || {};
hasPointMarker = !!point.marker;
enabled = (globallyEnabled && pointMarkerOptions.enabled === UNDEFINED) || pointMarkerOptions.enabled;
isInside = point.isInside;
// only draw the point if y is defined
if (enabled && plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
// shortcuts
pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || seriesPointAttr;
radius = pointAttr.r;
symbol = pick(pointMarkerOptions.symbol, series.symbol);
isImage = symbol.indexOf('url') === 0;
if (graphic) { // update
graphic[isInside ? 'show' : 'hide'](true) // Since the marker group isn't clipped, each individual marker must be toggled
.animate(extend({
x: plotX - radius,
y: plotY - radius
}, graphic.symbolName ? { // don't apply to image symbols #507
width: 2 * radius,
height: 2 * radius
} : {}));
} else if (isInside && (radius > 0 || isImage)) {
point.graphic = graphic = chart.renderer.symbol(
symbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius,
hasPointMarker ? pointMarkerOptions : seriesMarkerOptions
)
.attr(pointAttr)
.add(markerGroup);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
}
}
},
/**
* Convert state properties from API naming conventions to SVG attributes
*
* @param {Object} options API options object
* @param {Object} base1 SVG attribute object to inherit from
* @param {Object} base2 Second level SVG attribute object to inherit from
*/
convertAttribs: function (options, base1, base2, base3) {
var conversion = this.pointAttrToOptions,
attr,
option,
obj = {};
options = options || {};
base1 = base1 || {};
base2 = base2 || {};
base3 = base3 || {};
for (attr in conversion) {
option = conversion[attr];
obj[attr] = pick(options[option], base1[attr], base2[attr], base3[attr]);
}
return obj;
},
/**
* Get the state attributes. Each series type has its own set of attributes
* that are allowed to change on a point's state change. Series wide attributes are stored for
* all series, and additionally point specific attributes are stored for all
* points with individual marker options. If such options are not defined for the point,
* a reference to the series wide attributes is stored in point.pointAttr.
*/
getAttribs: function () {
var series = this,
seriesOptions = series.options,
normalOptions = defaultPlotOptions[series.type].marker ? seriesOptions.marker : seriesOptions,
stateOptions = normalOptions.states,
stateOptionsHover = stateOptions[HOVER_STATE],
pointStateOptionsHover,
seriesColor = series.color,
seriesNegativeColor = series.options.negativeColor,
normalDefaults = {
stroke: seriesColor,
fill: seriesColor
},
points = series.points || [], // #927
i,
point,
seriesPointAttr = [],
pointAttr,
pointAttrToOptions = series.pointAttrToOptions,
hasPointSpecificOptions = series.hasPointSpecificOptions,
defaultLineColor = normalOptions.lineColor,
defaultFillColor = normalOptions.fillColor,
turboThreshold = seriesOptions.turboThreshold,
zones = series.zones,
zoneAxis = series.zoneAxis || 'y',
attr,
key;
// series type specific modifications
if (seriesOptions.marker) { // line, spline, area, areaspline, scatter
// if no hover radius is given, default to normal radius + 2
stateOptionsHover.radius = stateOptionsHover.radius || normalOptions.radius + stateOptionsHover.radiusPlus;
stateOptionsHover.lineWidth = stateOptionsHover.lineWidth || normalOptions.lineWidth + stateOptionsHover.lineWidthPlus;
} else { // column, bar, pie
// if no hover color is given, brighten the normal color
stateOptionsHover.color = stateOptionsHover.color ||
Color(stateOptionsHover.color || seriesColor)
.brighten(stateOptionsHover.brightness).get();
// if no hover negativeColor is given, brighten the normal negativeColor
stateOptionsHover.negativeColor = stateOptionsHover.negativeColor ||
Color(stateOptionsHover.negativeColor || seriesNegativeColor)
.brighten(stateOptionsHover.brightness).get();
}
// general point attributes for the series normal state
seriesPointAttr[NORMAL_STATE] = series.convertAttribs(normalOptions, normalDefaults);
// HOVER_STATE and SELECT_STATE states inherit from normal state except the default radius
each([HOVER_STATE, SELECT_STATE], function (state) {
seriesPointAttr[state] =
series.convertAttribs(stateOptions[state], seriesPointAttr[NORMAL_STATE]);
});
// set it
series.pointAttr = seriesPointAttr;
// Generate the point-specific attribute collections if specific point
// options are given. If not, create a referance to the series wide point
// attributes
i = points.length;
if (!turboThreshold || i < turboThreshold || hasPointSpecificOptions) {
while (i--) {
point = points[i];
normalOptions = (point.options && point.options.marker) || point.options;
if (normalOptions && normalOptions.enabled === false) {
normalOptions.radius = 0;
}
if (zones.length) {
var j = 0,
threshold = zones[j];
while (point[zoneAxis] >= threshold.value) {
threshold = zones[++j];
}
point.color = point.fillColor = threshold.color;
}
hasPointSpecificOptions = seriesOptions.colorByPoint || point.color; // #868
// check if the point has specific visual options
if (point.options) {
for (key in pointAttrToOptions) {
if (defined(normalOptions[pointAttrToOptions[key]])) {
hasPointSpecificOptions = true;
}
}
}
// a specific marker config object is defined for the individual point:
// create it's own attribute collection
if (hasPointSpecificOptions) {
normalOptions = normalOptions || {};
pointAttr = [];
stateOptions = normalOptions.states || {}; // reassign for individual point
pointStateOptionsHover = stateOptions[HOVER_STATE] = stateOptions[HOVER_STATE] || {};
// Handle colors for column and pies
if (!seriesOptions.marker) { // column, bar, point
// If no hover color is given, brighten the normal color. #1619, #2579
pointStateOptionsHover.color = pointStateOptionsHover.color || (!point.options.color && stateOptionsHover[(point.negative && seriesNegativeColor ? 'negativeColor' : 'color')]) ||
Color(point.color)
.brighten(pointStateOptionsHover.brightness || stateOptionsHover.brightness)
.get();
}
// normal point state inherits series wide normal state
attr = { color: point.color }; // #868
if (!defaultFillColor) { // Individual point color or negative color markers (#2219)
attr.fillColor = point.color;
}
if (!defaultLineColor) {
attr.lineColor = point.color; // Bubbles take point color, line markers use white
}
pointAttr[NORMAL_STATE] = series.convertAttribs(extend(attr, normalOptions), seriesPointAttr[NORMAL_STATE]);
// inherit from point normal and series hover
pointAttr[HOVER_STATE] = series.convertAttribs(
stateOptions[HOVER_STATE],
seriesPointAttr[HOVER_STATE],
pointAttr[NORMAL_STATE]
);
// inherit from point normal and series hover
pointAttr[SELECT_STATE] = series.convertAttribs(
stateOptions[SELECT_STATE],
seriesPointAttr[SELECT_STATE],
pointAttr[NORMAL_STATE]
);
// no marker config object is created: copy a reference to the series-wide
// attribute collection
} else {
pointAttr = seriesPointAttr;
}
point.pointAttr = pointAttr;
}
}
},
/**
* Clear DOM objects and free up memory
*/
destroy: function () {
var series = this,
chart = series.chart,
issue134 = /AppleWebKit\/533/.test(userAgent),
destroy,
i,
data = series.data || [],
point,
prop,
axis;
// add event hook
fireEvent(series, 'destroy');
// remove all events
removeEvent(series);
// erase from axes
each(series.axisTypes || [], function (AXIS) {
axis = series[AXIS];
if (axis) {
erase(axis.series, series);
axis.isDirty = axis.forceRedraw = true;
}
});
// remove legend items
if (series.legendItem) {
series.chart.legend.destroyItem(series);
}
// destroy all points with their elements
i = data.length;
while (i--) {
point = data[i];
if (point && point.destroy) {
point.destroy();
}
}
series.points = null;
// Clear the animation timeout if we are destroying the series during initial animation
clearTimeout(series.animationTimeout);
// destroy all SVGElements associated to the series
each(['area', 'graph', 'dataLabelsGroup', 'group', 'markerGroup', 'tracker',
'graphNeg', 'areaNeg', 'posClip', 'negClip'], function (prop) {
if (series[prop]) {
// issue 134 workaround
destroy = issue134 && prop === 'group' ?
'hide' :
'destroy';
series[prop][destroy]();
}
});
// remove from hoverSeries
if (chart.hoverSeries === series) {
chart.hoverSeries = null;
}
erase(chart.series, series);
// clear all members
for (prop in series) {
delete series[prop];
}
},
/**
* Return the graph path of a segment
*/
getSegmentPath: function (segment) {
var series = this,
segmentPath = [],
step = series.options.step;
// build the segment line
each(segment, function (point, i) {
var plotX = point.plotX,
plotY = point.plotY,
lastPoint;
if (series.getPointSpline) { // generate the spline as defined in the SplineSeries object
segmentPath.push.apply(segmentPath, series.getPointSpline(segment, point, i));
} else {
// moveTo or lineTo
segmentPath.push(i ? L : M);
// step line?
if (step && i) {
lastPoint = segment[i - 1];
if (step === 'right') {
segmentPath.push(
lastPoint.plotX,
plotY
);
} else if (step === 'center') {
segmentPath.push(
(lastPoint.plotX + plotX) / 2,
lastPoint.plotY,
(lastPoint.plotX + plotX) / 2,
plotY
);
} else {
segmentPath.push(
plotX,
lastPoint.plotY
);
}
}
// normal line to next point
segmentPath.push(
point.plotX,
point.plotY
);
}
});
return segmentPath;
},
/**
* Get the graph path
*/
getGraphPath: function () {
var series = this,
graphPath = [],
segmentPath,
singlePoints = []; // used in drawTracker
// Divide into segments and build graph and area paths
each(series.segments, function (segment) {
segmentPath = series.getSegmentPath(segment);
// add the segment to the graph, or a single point for tracking
if (segment.length > 1) {
graphPath = graphPath.concat(segmentPath);
} else {
singlePoints.push(segment[0]);
}
});
// Record it for use in drawGraph and drawTracker, and return graphPath
series.singlePoints = singlePoints;
series.graphPath = graphPath;
return graphPath;
},
/**
* Draw the actual graph
*/
drawGraph: function () {
var series = this,
options = this.options,
props = [['graph', options.lineColor || this.color, options.dashStyle]],
lineWidth = options.lineWidth,
roundCap = options.linecap !== 'square',
graphPath = this.getGraphPath(),
fillColor = (this.fillGraph && this.color) || NONE, // polygon series use filled graph
zones = this.zones;
each(zones, function (threshold, i) {
props.push(['colorGraph' + i, threshold.color || series.color, threshold.dashStyle || options.dashStyle]);
});
// Draw the graph
each(props, function (prop, i) {
var graphKey = prop[0],
graph = series[graphKey],
attribs;
if (graph) {
stop(graph); // cancel running animations, #459
graph.animate({ d: graphPath });
} else if ((lineWidth || fillColor) && graphPath.length) { // #1487
attribs = {
stroke: prop[1],
'stroke-width': lineWidth,
fill: fillColor,
zIndex: 1 // #1069
};
if (prop[2]) {
attribs.dashstyle = prop[2];
} else if (roundCap) {
attribs['stroke-linecap'] = attribs['stroke-linejoin'] = 'round';
}
series[graphKey] = series.chart.renderer.path(graphPath)
.attr(attribs)
.add(series.group)
.shadow(!i && options.shadow);
}
});
},
/**
* Clip the graphs into the positive and negative coloured graphs
*/
applyZones: function () {
var series = this,
chart = this.chart,
renderer = chart.renderer,
zones = this.zones,
translatedFrom,
translatedTo,
clips = this.clips || [],
clipAttr,
graph = this.graph,
area = this.area,
chartSizeMax = mathMax(chart.chartWidth, chart.chartHeight),
zoneAxis = this.zoneAxis || 'y',
axis = this[zoneAxis + 'Axis'],
reversed = axis.reversed,
horiz = axis.horiz;
if (zones.length && (graph || area)) {
// The use of the Color Threshold assumes there are no gaps
// so it is safe to hide the original graph and area
graph.hide();
if (area) { area.hide(); }
// Create the clips
each(zones, function (threshold, i) {
translatedFrom = pick(translatedTo, (reversed ? (horiz ? chart.plotWidth : 0) : (horiz ? 0 : axis.toPixels(axis.min))));
translatedTo = mathRound(axis.toPixels(pick(threshold.value, axis.max), true));
if (axis.isXAxis) {
clipAttr = {
x: reversed ? translatedTo : translatedFrom,
y: 0,
width: Math.abs(translatedFrom - translatedTo),
height: chartSizeMax
};
if (!horiz) {
clipAttr.x = chart.plotHeight - clipAttr.x;
}
} else {
clipAttr = {
x: 0,
y: reversed ? translatedFrom : translatedTo,
width: chartSizeMax,
height: Math.abs(translatedFrom - translatedTo)
};
if (horiz) {
clipAttr.y = chart.plotWidth - clipAttr.y;
}
}
/// VML SUPPPORT
if (chart.inverted && renderer.isVML) {
if (axis.isXAxis) {
clipAttr = {
x: 0,
y: reversed ? translatedFrom : translatedTo,
height: clipAttr.width,
width: chart.chartWidth
};
} else {
clipAttr = {
x: clipAttr.y - chart.plotLeft - chart.spacingBox.x,
y: 0,
width: clipAttr.height,
height: chart.chartHeight
};
}
}
/// END OF VML SUPPORT
if (clips[i]) {
clips[i].animate(clipAttr);
} else {
clips[i] = renderer.clipRect(clipAttr);
series['colorGraph' + i].clip(clips[i]);
if (area) {
series['colorArea' + i].clip(clips[i]);
}
}
});
this.clips = clips;
}
},
/**
* Initialize and perform group inversion on series.group and series.markerGroup
*/
invertGroups: function () {
var series = this,
chart = series.chart;
// Pie, go away (#1736)
if (!series.xAxis) {
return;
}
// A fixed size is needed for inversion to work
function setInvert() {
var size = {
width: series.yAxis.len,
height: series.xAxis.len
};
each(['group', 'markerGroup'], function (groupName) {
if (series[groupName]) {
series[groupName].attr(size).invert();
}
});
}
addEvent(chart, 'resize', setInvert); // do it on resize
addEvent(series, 'destroy', function () {
removeEvent(chart, 'resize', setInvert);
});
// Do it now
setInvert(); // do it now
// On subsequent render and redraw, just do setInvert without setting up events again
series.invertGroups = setInvert;
},
/**
* General abstraction for creating plot groups like series.group, series.dataLabelsGroup and
* series.markerGroup. On subsequent calls, the group will only be adjusted to the updated plot size.
*/
plotGroup: function (prop, name, visibility, zIndex, parent) {
var group = this[prop],
isNew = !group;
// Generate it on first call
if (isNew) {
this[prop] = group = this.chart.renderer.g(name)
.attr({
visibility: visibility,
zIndex: zIndex || 0.1 // IE8 needs this
})
.add(parent);
}
// Place it on first and subsequent (redraw) calls
group[isNew ? 'attr' : 'animate'](this.getPlotBox());
return group;
},
/**
* Get the translation and scale for the plot area of this series
*/
getPlotBox: function () {
var chart = this.chart,
xAxis = this.xAxis,
yAxis = this.yAxis;
// Swap axes for inverted (#2339)
if (chart.inverted) {
xAxis = yAxis;
yAxis = this.xAxis;
}
return {
translateX: xAxis ? xAxis.left : chart.plotLeft,
translateY: yAxis ? yAxis.top : chart.plotTop,
scaleX: 1, // #1623
scaleY: 1
};
},
/**
* Render the graph and markers
*/
render: function () {
var series = this,
chart = series.chart,
group,
options = series.options,
animation = options.animation,
// Animation doesn't work in IE8 quirks when the group div is hidden,
// and looks bad in other oldIE
animDuration = (animation && !!series.animate && chart.renderer.isSVG && pick(animation.duration, 500)) || 0,
visibility = series.visible ? VISIBLE : HIDDEN,
zIndex = options.zIndex,
hasRendered = series.hasRendered,
chartSeriesGroup = chart.seriesGroup;
// the group
group = series.plotGroup(
'group',
'series',
visibility,
zIndex,
chartSeriesGroup
);
series.markerGroup = series.plotGroup(
'markerGroup',
'markers',
visibility,
zIndex,
chartSeriesGroup
);
// initiate the animation
if (animDuration) {
series.animate(true);
}
// cache attributes for shapes
series.getAttribs();
// SVGRenderer needs to know this before drawing elements (#1089, #1795)
group.inverted = series.isCartesian ? chart.inverted : false;
// draw the graph if any
if (series.drawGraph) {
series.drawGraph();
series.applyZones();
}
each(series.points, function (point) {
if (point.redraw) {
point.redraw();
}
});
// draw the data labels (inn pies they go before the points)
if (series.drawDataLabels) {
series.drawDataLabels();
}
// draw the points
if (series.visible) {
series.drawPoints();
}
// draw the mouse tracking area
if (series.drawTracker && series.options.enableMouseTracking !== false) {
series.drawTracker();
}
// Handle inverted series and tracker groups
if (chart.inverted) {
series.invertGroups();
}
// Run the animation
if (animDuration) {
series.animate();
}
// Call the afterAnimate function on animation complete (but don't overwrite the animation.complete option
// which should be available to the user).
if (!hasRendered) {
if (animDuration) {
series.animationTimeout = setTimeout(function () {
series.afterAnimate();
}, animDuration);
} else {
series.afterAnimate();
}
}
series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
// (See #322) series.isDirty = series.isDirtyData = false; // means data is in accordance with what you see
series.hasRendered = true;
},
/**
* Redraw the series after an update in the axes.
*/
redraw: function () {
var series = this,
chart = series.chart,
wasDirtyData = series.isDirtyData, // cache it here as it is set to false in render, but used after
group = series.group,
xAxis = series.xAxis,
yAxis = series.yAxis;
// reposition on resize
if (group) {
if (chart.inverted) {
group.attr({
width: chart.plotWidth,
height: chart.plotHeight
});
}
group.animate({
translateX: pick(xAxis && xAxis.left, chart.plotLeft),
translateY: pick(yAxis && yAxis.top, chart.plotTop)
});
}
series.translate();
series.render();
if (wasDirtyData) {
fireEvent(series, 'updatedData');
}
},
/**
* KD Tree && PointSearching Implementation
*/
kdDimensions: 1,
kdTree: null,
kdAxisArray: ['plotX', 'plotY'],
kdComparer: 'distX',
searchPoint: function (e) {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
inverted = series.chart.inverted;
e.plotX = inverted ? xAxis.len - e.chartY + xAxis.pos : e.chartX - xAxis.pos;
e.plotY = inverted ? yAxis.len - e.chartX + yAxis.pos : e.chartY - yAxis.pos;
return this.searchKDTree(e);
},
buildKDTree: function () {
var series = this,
dimensions = series.kdDimensions;
// Internal function
function _kdtree(points, depth, dimensions) {
var axis, median, length = points && points.length;
if (length) {
// alternate between the axis
axis = series.kdAxisArray[depth % dimensions];
// sort point array
points.sort(function(a, b) {
return a[axis] - b[axis];
});
median = Math.floor(length / 2);
// build and return node
return {
point: points[median],
left: _kdtree(points.slice(0, median), depth + 1, dimensions),
right: _kdtree(points.slice(median + 1), depth + 1, dimensions)
};
}
}
function startRecursive() {
series.kdTree = _kdtree(series.points, dimensions, dimensions);
}
delete series.kdTree;
if (series.options.kdSync) { // For testing tooltips, don't build async
startRecursive();
} else {
setTimeout(startRecursive);
}
},
searchKDTree: function (point) {
var series = this,
kdComparer = this.kdComparer,
kdX = this.kdAxisArray[0],
kdY = this.kdAxisArray[1];
// Internal function
function _distance(p1, p2) {
var x = (defined(p1[kdX]) && defined(p2[kdX])) ? Math.pow(p1[kdX] - p2[kdX], 2) : null,
y = (defined(p1[kdY]) && defined(p2[kdY])) ? Math.pow(p1[kdY] - p2[kdY], 2) : null,
r = (x || 0) + (y || 0);
return {
distX: defined(x) ? Math.sqrt(x) : Number.MAX_VALUE,
distY: defined(y) ? Math.sqrt(y) : Number.MAX_VALUE,
distR: defined(r) ? Math.sqrt(r) : Number.MAX_VALUE
};
}
function _search(search, tree, depth, dimensions) {
var point = tree.point,
axis = series.kdAxisArray[depth % dimensions],
tdist,
sideA,
sideB,
ret = point,
nPoint1,
nPoint2;
point.dist = _distance(search, point);
// Pick side based on distance to splitting point
tdist = search[axis] - point[axis];
sideA = tdist < 0 ? 'left' : 'right';
// End of tree
if (tree[sideA]) {
nPoint1 =_search(search, tree[sideA], depth + 1, dimensions);
ret = (nPoint1.dist[kdComparer] < ret.dist[kdComparer] ? nPoint1 : point);
sideB = tdist < 0 ? 'right' : 'left';
if (tree[sideB]) {
// compare distance to current best to splitting point to decide wether to check side B or not
if (Math.sqrt(tdist*tdist) < ret.dist[kdComparer]) {
nPoint2 = _search(search, tree[sideB], depth + 1, dimensions);
ret = (nPoint2.dist[kdComparer] < ret.dist[kdComparer] ? nPoint2 : ret);
}
}
}
return ret;
}
if (!this.kdTree) {
this.buildKDTree();
}
if (this.kdTree) {
return _search(point,
this.kdTree, this.kdDimensions, this.kdDimensions);
} else {
return UNDEFINED;
}
}
}; // end Series prototype
// Extend the Chart prototype for dynamic methods
extend(Chart.prototype, {
/**
* Add a series dynamically after time
*
* @param {Object} options The config options
* @param {Boolean} redraw Whether to redraw the chart after adding. Defaults to true.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
* @return {Object} series The newly created series object
*/
addSeries: function (options, redraw, animation) {
var series,
chart = this;
if (options) {
redraw = pick(redraw, true); // defaults to true
fireEvent(chart, 'addSeries', { options: options }, function () {
series = chart.initSeries(options);
chart.isDirtyLegend = true; // the series array is out of sync with the display
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
return series;
},
/**
* Add an axis to the chart
* @param {Object} options The axis option
* @param {Boolean} isX Whether it is an X axis or a value axis
*/
addAxis: function (options, isX, redraw, animation) {
var key = isX ? 'xAxis' : 'yAxis',
chartOptions = this.options,
axis;
/*jslint unused: false*/
axis = new Axis(this, merge(options, {
index: this[key].length,
isX: isX
}));
/*jslint unused: true*/
// Push the new axis options to the chart options
chartOptions[key] = splat(chartOptions[key] || {});
chartOptions[key].push(options);
if (pick(redraw, true)) {
this.redraw(animation);
}
},
/**
* Dim the chart and show a loading text or symbol
* @param {String} str An optional text to show in the loading label instead of the default one
*/
showLoading: function (str) {
var chart = this,
options = chart.options,
loadingDiv = chart.loadingDiv,
loadingOptions = options.loading,
setLoadingSize = function () {
if (loadingDiv) {
css(loadingDiv, {
left: chart.plotLeft + PX,
top: chart.plotTop + PX,
width: chart.plotWidth + PX,
height: chart.plotHeight + PX
});
}
};
// create the layer at the first call
if (!loadingDiv) {
chart.loadingDiv = loadingDiv = createElement(DIV, {
className: PREFIX + 'loading'
}, extend(loadingOptions.style, {
zIndex: 10,
display: NONE
}), chart.container);
chart.loadingSpan = createElement(
'span',
null,
loadingOptions.labelStyle,
loadingDiv
);
addEvent(chart, 'redraw', setLoadingSize); // #1080
}
// update text
chart.loadingSpan.innerHTML = str || options.lang.loading;
// show it
if (!chart.loadingShown) {
css(loadingDiv, {
opacity: 0,
display: ''
});
animate(loadingDiv, {
opacity: loadingOptions.style.opacity
}, {
duration: loadingOptions.showDuration || 0
});
chart.loadingShown = true;
}
setLoadingSize();
},
/**
* Hide the loading layer
*/
hideLoading: function () {
var options = this.options,
loadingDiv = this.loadingDiv;
if (loadingDiv) {
animate(loadingDiv, {
opacity: 0
}, {
duration: options.loading.hideDuration || 100,
complete: function () {
css(loadingDiv, { display: NONE });
}
});
}
this.loadingShown = false;
}
});
// extend the Point prototype for dynamic methods
extend(Point.prototype, {
/**
* Update the point with new options (typically x/y data) and optionally redraw the series.
*
* @param {Object} options Point options as defined in the series.data array
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*
*/
update: function (options, redraw, animation, runEvent) {
var point = this,
series = point.series,
graphic = point.graphic,
i,
chart = series.chart,
seriesOptions = series.options,
names = series.xAxis.names;
redraw = pick(redraw, true);
function update() {
point.applyOptions(options);
// Update visuals
if (isObject(options) && !isArray(options)) {
// Defer the actual redraw until getAttribs has been called (#3260)
point.redraw = function () {
if (graphic) {
if (options && options.marker && options.marker.symbol) {
point.graphic = graphic.destroy();
} else {
graphic.attr(point.pointAttr[point.state || '']);
}
}
if (options && options.dataLabels && point.dataLabel) { // #2468
point.dataLabel = point.dataLabel.destroy();
}
point.redraw = null;
};
}
// record changes in the parallel arrays
i = point.index;
series.updateParallelArrays(point, i);
if (names && point.name) {
names[point.x] = point.name;
}
seriesOptions.data[i] = point.options;
// redraw
series.isDirty = series.isDirtyData = true;
if (!series.fixedBox && series.hasCartesianSeries) { // #1906, #2320
chart.isDirtyBox = true;
}
if (seriesOptions.legendType === 'point') { // #1831, #1885
chart.legend.destroyItem(point);
}
if (redraw) {
chart.redraw(animation);
}
}
// Fire the event with a default handler of doing the update
if (runEvent === false) { // When called from setData
update();
} else {
point.firePointEvent('update', { options: options }, update);
}
},
/**
* Remove a point and optionally redraw the series and if necessary the axes
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
this.series.removePoint(inArray(this, this.series.data), redraw, animation);
}
});
// Extend the series prototype for dynamic methods
extend(Series.prototype, {
/**
* Add a point dynamically after chart load time
* @param {Object} options Point options as given in series.data
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean} shift If shift is true, a point is shifted off the start
* of the series as one is appended to the end.
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
addPoint: function (options, redraw, shift, animation) {
var series = this,
seriesOptions = series.options,
data = series.data,
graph = series.graph,
area = series.area,
chart = series.chart,
names = series.xAxis && series.xAxis.names,
currentShift = (graph && graph.shift) || 0,
dataOptions = seriesOptions.data,
point,
isInTheMiddle,
xData = series.xData,
x,
i;
setAnimation(animation, chart);
// Make graph animate sideways
if (shift) {
each([graph, area, series.graphNeg, series.areaNeg], function (shape) {
if (shape) {
shape.shift = currentShift + 1;
}
});
}
if (area) {
area.isArea = true; // needed in animation, both with and without shift
}
// Optional redraw, defaults to true
redraw = pick(redraw, true);
// Get options and push the point to xData, yData and series.options. In series.generatePoints
// the Point instance will be created on demand and pushed to the series.data array.
point = { series: series };
series.pointClass.prototype.applyOptions.apply(point, [options]);
x = point.x;
// Get the insertion point
i = xData.length;
if (series.requireSorting && x < xData[i - 1]) {
isInTheMiddle = true;
while (i && xData[i - 1] > x) {
i--;
}
}
series.updateParallelArrays(point, 'splice', i, 0, 0); // insert undefined item
series.updateParallelArrays(point, i); // update it
if (names && point.name) {
names[x] = point.name;
}
dataOptions.splice(i, 0, options);
if (isInTheMiddle) {
series.data.splice(i, 0, null);
series.processData();
}
// Generate points to be added to the legend (#1329)
if (seriesOptions.legendType === 'point') {
series.generatePoints();
}
// Shift the first point off the parallel arrays
// todo: consider series.removePoint(i) method
if (shift) {
if (data[0] && data[0].remove) {
data[0].remove(false);
} else {
data.shift();
series.updateParallelArrays(point, 'shift');
dataOptions.shift();
}
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
series.getAttribs(); // #1937
chart.redraw();
}
},
/**
* Remove a point (rendered or not), by index
*/
removePoint: function (i, redraw, animation) {
var series = this,
data = series.data,
point = data[i],
points = series.points,
chart = series.chart,
remove = function () {
if (data.length === points.length) {
points.splice(i, 1);
}
data.splice(i, 1);
series.options.data.splice(i, 1);
series.updateParallelArrays(point || { series: series }, 'splice', i, 1);
if (point) {
point.destroy();
}
// redraw
series.isDirty = true;
series.isDirtyData = true;
if (redraw) {
chart.redraw();
}
};
setAnimation(animation, chart);
redraw = pick(redraw, true);
// Fire the event with a default handler of removing the point
if (point) {
point.firePointEvent('remove', null, remove);
} else {
remove();
}
},
/**
* Remove a series and optionally redraw the chart
*
* @param {Boolean} redraw Whether to redraw the chart or wait for an explicit call
* @param {Boolean|Object} animation Whether to apply animation, and optionally animation
* configuration
*/
remove: function (redraw, animation) {
var series = this,
chart = series.chart;
redraw = pick(redraw, true);
if (!series.isRemoving) { /* prevent triggering native event in jQuery
(calling the remove function from the remove event) */
series.isRemoving = true;
// fire the event with a default handler of removing the point
fireEvent(series, 'remove', null, function () {
// destroy elements
series.destroy();
// redraw
chart.isDirtyLegend = chart.isDirtyBox = true;
chart.linkSeries();
if (redraw) {
chart.redraw(animation);
}
});
}
series.isRemoving = false;
},
/**
* Update the series with a new set of options
*/
update: function (newOptions, redraw) {
var series = this,
chart = this.chart,
// must use user options when changing type because this.options is merged
// in with type specific plotOptions
oldOptions = this.userOptions,
oldType = this.type,
proto = seriesTypes[oldType].prototype,
preserve = ['group', 'markerGroup', 'dataLabelsGroup'],
n;
// If we're changing type or zIndex, create new groups (#3380, #3404)
if ((newOptions.type && newOptions.type !== oldType) || newOptions.zIndex !== undefined) {
preserve.length = 0;
}
// Make sure groups are not destroyed (#3094)
each(preserve, function (prop) {
preserve[prop] = series[prop];
delete series[prop];
});
// Do the merge, with some forced options
newOptions = merge(oldOptions, {
animation: false,
index: this.index,
pointStart: this.xData[0] // when updating after addPoint
}, { data: this.options.data }, newOptions);
// Destroy the series and delete all properties. Reinsert all methods
// and properties from the new type prototype (#2270, #3719)
this.remove(false);
for (n in proto) {
this[n] = UNDEFINED;
}
extend(this, seriesTypes[newOptions.type || oldType].prototype);
// Re-register groups (#3094)
each(preserve, function (prop) {
series[prop] = preserve[prop];
});
this.init(chart, newOptions);
chart.linkSeries(); // Links are lost in this.remove (#3028)
if (pick(redraw, true)) {
chart.redraw(false);
}
}
});
// Extend the Axis.prototype for dynamic methods
extend(Axis.prototype, {
/**
* Update the axis with a new options structure
*/
update: function (newOptions, redraw) {
var chart = this.chart;
newOptions = chart.options[this.coll][this.options.index] = merge(this.userOptions, newOptions);
this.destroy(true);
this._addedPlotLB = UNDEFINED; // #1611, #2887
this.init(chart, extend(newOptions, { events: UNDEFINED }));
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Remove the axis from the chart
*/
remove: function (redraw) {
var chart = this.chart,
key = this.coll, // xAxis or yAxis
axisSeries = this.series,
i = axisSeries.length;
// Remove associated series (#2687)
while (i--) {
if (axisSeries[i]) {
axisSeries[i].remove(false);
}
}
// Remove the axis
erase(chart.axes, this);
erase(chart[key], this);
chart.options[key].splice(this.options.index, 1);
each(chart[key], function (axis, i) { // Re-index, #1706
axis.options.index = i;
});
this.destroy();
chart.isDirtyBox = true;
if (pick(redraw, true)) {
chart.redraw();
}
},
/**
* Update the axis title by options
*/
setTitle: function (newTitleOptions, redraw) {
this.update({ title: newTitleOptions }, redraw);
},
/**
* Set new axis categories and optionally redraw
* @param {Array} categories
* @param {Boolean} redraw
*/
setCategories: function (categories, redraw) {
this.update({ categories: categories }, redraw);
}
});
/**
* LineSeries object
*/
var LineSeries = extendClass(Series);
seriesTypes.line = LineSeries;
/**
* Set the default options for column
*/
defaultPlotOptions.column = merge(defaultSeriesOptions, {
borderColor: '#FFFFFF',
//borderWidth: 1,
borderRadius: 0,
//colorByPoint: undefined,
groupPadding: 0.2,
//grouping: true,
marker: null, // point options are specified in the base options
pointPadding: 0.1,
//pointWidth: null,
minPointLength: 0,
cropThreshold: 50, // when there are more points, they will not animate out of the chart on xAxis.setExtremes
pointRange: null, // null means auto, meaning 1 in a categorized axis and least distance between points if not categories
states: {
hover: {
brightness: 0.1,
shadow: false,
halo: false
},
select: {
color: '#C0C0C0',
borderColor: '#000000',
shadow: false
}
},
dataLabels: {
align: null, // auto
verticalAlign: null, // auto
y: null
},
stickyTracking: false,
tooltip: {
distance: 6
},
threshold: 0
});
/**
* ColumnSeries object
*/
var ColumnSeries = extendClass(Series, {
type: 'column',
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
fill: 'color',
r: 'borderRadius'
},
cropShoulder: 0,
directTouch: true, // When tooltip is not shared, this series (and derivatives) requires direct touch/hover. KD-tree does not apply.
trackerGroups: ['group', 'dataLabelsGroup'],
negStacks: true, // use separate negative stacks, unlike area stacks where a negative
// point is substracted from previous (#1910)
/**
* Initialize the series
*/
init: function () {
Series.prototype.init.apply(this, arguments);
var series = this,
chart = series.chart;
// if the series is added dynamically, force redraw of other
// series affected by a new column
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
},
/**
* Return the width and x offset of the columns adjusted for grouping, groupPadding, pointPadding,
* pointWidth etc.
*/
getColumnMetrics: function () {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis,
reversedXAxis = xAxis.reversed,
stackKey,
stackGroups = {},
columnIndex,
columnCount = 0;
// Get the total number of column type series.
// This is called on every series. Consider moving this logic to a
// chart.orderStacks() function and call it on init, addSeries and removeSeries
if (options.grouping === false) {
columnCount = 1;
} else {
each(series.chart.series, function (otherSeries) {
var otherOptions = otherSeries.options,
otherYAxis = otherSeries.yAxis;
if (otherSeries.type === series.type && otherSeries.visible &&
yAxis.len === otherYAxis.len && yAxis.pos === otherYAxis.pos) { // #642, #2086
if (otherOptions.stacking) {
stackKey = otherSeries.stackKey;
if (stackGroups[stackKey] === UNDEFINED) {
stackGroups[stackKey] = columnCount++;
}
columnIndex = stackGroups[stackKey];
} else if (otherOptions.grouping !== false) { // #1162
columnIndex = columnCount++;
}
otherSeries.columnIndex = columnIndex;
}
});
}
var categoryWidth = mathMin(
mathAbs(xAxis.transA) * (xAxis.ordinalSlope || options.pointRange || xAxis.closestPointRange || xAxis.tickInterval || 1), // #2610
xAxis.len // #1535
),
groupPadding = categoryWidth * options.groupPadding,
groupWidth = categoryWidth - 2 * groupPadding,
pointOffsetWidth = groupWidth / columnCount,
optionPointWidth = options.pointWidth,
pointPadding = defined(optionPointWidth) ? (pointOffsetWidth - optionPointWidth) / 2 :
pointOffsetWidth * options.pointPadding,
pointWidth = pick(optionPointWidth, pointOffsetWidth - 2 * pointPadding), // exact point width, used in polar charts
colIndex = (reversedXAxis ?
columnCount - (series.columnIndex || 0) : // #1251
series.columnIndex) || 0,
pointXOffset = pointPadding + (groupPadding + colIndex *
pointOffsetWidth - (categoryWidth / 2)) *
(reversedXAxis ? -1 : 1);
// Save it for reading in linked series (Error bars particularly)
return (series.columnMetrics = {
width: pointWidth,
offset: pointXOffset
});
},
/**
* Translate each point to the plot area coordinate system and find shape positions
*/
translate: function () {
var series = this,
chart = series.chart,
options = series.options,
borderWidth = series.borderWidth = pick(
options.borderWidth,
series.closestPointRange * series.xAxis.transA < 2 ? 0 : 1 // #3635
),
yAxis = series.yAxis,
threshold = options.threshold,
translatedThreshold = series.translatedThreshold = yAxis.getThreshold(threshold),
minPointLength = pick(options.minPointLength, 5),
metrics = series.getColumnMetrics(),
pointWidth = metrics.width,
seriesBarW = series.barW = mathMax(pointWidth, 1 + 2 * borderWidth), // postprocessed for border width
pointXOffset = series.pointXOffset = metrics.offset,
xCrisp = -(borderWidth % 2 ? 0.5 : 0),
yCrisp = borderWidth % 2 ? 0.5 : 1;
if (chart.renderer.isVML && chart.inverted) {
yCrisp += 1;
}
// When the pointPadding is 0, we want the columns to be packed tightly, so we allow individual
// columns to have individual sizes. When pointPadding is greater, we strive for equal-width
// columns (#2694).
if (options.pointPadding) {
seriesBarW = mathCeil(seriesBarW);
}
Series.prototype.translate.apply(series);
// Record the new values
each(series.points, function (point) {
var yBottom = pick(point.yBottom, translatedThreshold),
plotY = mathMin(mathMax(-999 - yBottom, point.plotY), yAxis.len + 999 + yBottom), // Don't draw too far outside plot area (#1303, #2241)
barX = point.plotX + pointXOffset,
barW = seriesBarW,
barY = mathMin(plotY, yBottom),
right,
bottom,
fromTop,
barH = mathMax(plotY, yBottom) - barY;
// Handle options.minPointLength
if (mathAbs(barH) < minPointLength) {
if (minPointLength) {
barH = minPointLength;
barY =
mathRound(mathAbs(barY - translatedThreshold) > minPointLength ? // stacked
yBottom - minPointLength : // keep position
translatedThreshold - (yAxis.translate(point.y, 0, 1, 0, 1) <= translatedThreshold ? minPointLength : 0)); // use exact yAxis.translation (#1485)
}
}
// Cache for access in polar
point.barX = barX;
point.pointWidth = pointWidth;
// Fix the tooltip on center of grouped columns (#1216, #424, #3648)
point.tooltipPos = chart.inverted ?
[yAxis.len + yAxis.pos - chart.plotLeft - plotY, series.xAxis.len - barX - barW / 2] :
[barX + barW / 2, plotY + yAxis.pos - chart.plotTop];
// Round off to obtain crisp edges and avoid overlapping with neighbours (#2694)
right = mathRound(barX + barW) + xCrisp;
barX = mathRound(barX) + xCrisp;
barW = right - barX;
fromTop = mathAbs(barY) < 0.5;
bottom = mathMin(mathRound(barY + barH) + yCrisp, 9e4); // #3575
barY = mathRound(barY) + yCrisp;
barH = bottom - barY;
// Top edges are exceptions
if (fromTop) {
barY -= 1;
barH += 1;
}
// Register shape type and arguments to be used in drawPoints
point.shapeType = 'rect';
point.shapeArgs = {
x: barX,
y: barY,
width: barW,
height: barH
};
});
},
getSymbol: noop,
/**
* Use a solid rectangle like the area series types
*/
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* Columns have no graph
*/
drawGraph: noop,
/**
* Draw the columns. For bars, the series.group is rotated, so the same coordinates
* apply for columns and bars. This method is inherited by scatter series.
*
*/
drawPoints: function () {
var series = this,
chart = this.chart,
options = series.options,
renderer = chart.renderer,
animationLimit = options.animationLimit || 250,
shapeArgs,
pointAttr;
// draw the columns
each(series.points, function (point) {
var plotY = point.plotY,
graphic = point.graphic,
borderAttr;
if (plotY !== UNDEFINED && !isNaN(plotY) && point.y !== null) {
shapeArgs = point.shapeArgs;
borderAttr = defined(series.borderWidth) ? {
'stroke-width': series.borderWidth
} : {};
pointAttr = point.pointAttr[point.selected ? SELECT_STATE : NORMAL_STATE] || series.pointAttr[NORMAL_STATE];
if (graphic) { // update
stop(graphic);
graphic.attr(borderAttr)[chart.pointCount < animationLimit ? 'animate' : 'attr'](merge(shapeArgs));
} else {
point.graphic = graphic = renderer[point.shapeType](shapeArgs)
.attr(borderAttr)
.attr(pointAttr)
.add(series.group)
.shadow(options.shadow, null, options.stacking && !options.borderRadius);
}
} else if (graphic) {
point.graphic = graphic.destroy(); // #1269
}
});
},
/**
* Animate the column heights one by one from zero
* @param {Boolean} init Whether to initialize the animation or run it
*/
animate: function (init) {
var series = this,
yAxis = this.yAxis,
options = series.options,
inverted = this.chart.inverted,
attr = {},
translatedThreshold;
if (hasSVG) { // VML is too slow anyway
if (init) {
attr.scaleY = 0.001;
translatedThreshold = mathMin(yAxis.pos + yAxis.len, mathMax(yAxis.pos, yAxis.toPixels(options.threshold)));
if (inverted) {
attr.translateX = translatedThreshold - yAxis.len;
} else {
attr.translateY = translatedThreshold;
}
series.group.attr(attr);
} else { // run the animation
attr.scaleY = 1;
attr[inverted ? 'translateX' : 'translateY'] = yAxis.pos;
series.group.animate(attr, series.options.animation);
// delete this function to allow it only once
series.animate = null;
}
}
},
/**
* Remove this series from the chart
*/
remove: function () {
var series = this,
chart = series.chart;
// column and bar series affects other series of the same type
// as they are either stacked or grouped
if (chart.hasRendered) {
each(chart.series, function (otherSeries) {
if (otherSeries.type === series.type) {
otherSeries.isDirty = true;
}
});
}
Series.prototype.remove.apply(series, arguments);
}
});
seriesTypes.column = ColumnSeries;
/**
* Set the default options for scatter
*/
defaultPlotOptions.scatter = merge(defaultSeriesOptions, {
lineWidth: 0,
marker: {
enabled: true // Overrides auto-enabling in line series (#3647)
},
tooltip: {
headerFormat: '<span style="color:{series.color}">\u25CF</span> <span style="font-size: 10px;"> {series.name}</span><br/>',
pointFormat: 'x: <b>{point.x}</b><br/>y: <b>{point.y}</b><br/>'
}
});
/**
* The scatter series class
*/
var ScatterSeries = extendClass(Series, {
type: 'scatter',
sorted: false,
requireSorting: false,
noSharedTooltip: true,
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
takeOrdinalPosition: false, // #2342
kdDimensions: 2,
kdComparer: 'distR',
drawGraph: function () {
if (this.options.lineWidth) {
Series.prototype.drawGraph.call(this);
}
}
});
seriesTypes.scatter = ScatterSeries;
/**
* Draw the data labels
*/
Series.prototype.drawDataLabels = function () {
var series = this,
seriesOptions = series.options,
cursor = seriesOptions.cursor,
options = seriesOptions.dataLabels,
points = series.points,
pointOptions,
generalOptions,
hasRendered = series.hasRendered || 0,
str,
dataLabelsGroup,
renderer = series.chart.renderer;
if (options.enabled || series._hasPointLabels) {
// Process default alignment of data labels for columns
if (series.dlProcessOptions) {
series.dlProcessOptions(options);
}
// Create a separate group for the data labels to avoid rotation
dataLabelsGroup = series.plotGroup(
'dataLabelsGroup',
'data-labels',
options.defer ? HIDDEN : VISIBLE,
options.zIndex || 6
);
if (pick(options.defer, true)) {
dataLabelsGroup.attr({ opacity: +hasRendered }); // #3300
if (!hasRendered) {
addEvent(series, 'afterAnimate', function () {
if (series.visible) { // #3023, #3024
dataLabelsGroup.show();
}
dataLabelsGroup[seriesOptions.animation ? 'animate' : 'attr']({ opacity: 1 }, { duration: 200 });
});
}
}
// Make the labels for each point
generalOptions = options;
each(points, function (point) {
var enabled,
dataLabel = point.dataLabel,
labelConfig,
attr,
name,
rotation,
connector = point.connector,
isNew = true,
style,
moreStyle = {};
// Determine if each data label is enabled
pointOptions = point.dlOptions || (point.options && point.options.dataLabels); // dlOptions is used in treemaps
enabled = pick(pointOptions && pointOptions.enabled, generalOptions.enabled); // #2282
// If the point is outside the plot area, destroy it. #678, #820
if (dataLabel && !enabled) {
point.dataLabel = dataLabel.destroy();
// Individual labels are disabled if the are explicitly disabled
// in the point options, or if they fall outside the plot area.
} else if (enabled) {
// Create individual options structure that can be extended without
// affecting others
options = merge(generalOptions, pointOptions);
style = options.style;
rotation = options.rotation;
// Get the string
labelConfig = point.getLabelConfig();
str = options.format ?
format(options.format, labelConfig) :
options.formatter.call(labelConfig, options);
// Determine the color
style.color = pick(options.color, style.color, series.color, 'black');
// update existing label
if (dataLabel) {
if (defined(str)) {
dataLabel
.attr({
text: str
});
isNew = false;
} else { // #1437 - the label is shown conditionally
point.dataLabel = dataLabel = dataLabel.destroy();
if (connector) {
point.connector = connector.destroy();
}
}
// create new label
} else if (defined(str)) {
attr = {
//align: align,
fill: options.backgroundColor,
stroke: options.borderColor,
'stroke-width': options.borderWidth,
r: options.borderRadius || 0,
rotation: rotation,
padding: options.padding,
zIndex: 1
};
// Get automated contrast color
if (style.color === 'contrast') {
moreStyle.color = options.inside || options.distance < 0 || !!seriesOptions.stacking ?
renderer.getContrast(point.color || series.color) :
'#000000';
}
if (cursor) {
moreStyle.cursor = cursor;
}
// Remove unused attributes (#947)
for (name in attr) {
if (attr[name] === UNDEFINED) {
delete attr[name];
}
}
dataLabel = point.dataLabel = renderer[rotation ? 'text' : 'label']( // labels don't support rotation
str,
0,
-999,
null,
null,
null,
options.useHTML
)
.attr(attr)
.css(extend(style, moreStyle))
.add(dataLabelsGroup)
.shadow(options.shadow);
}
if (dataLabel) {
// Now the data label is created and placed at 0,0, so we need to align it
series.alignDataLabel(point, dataLabel, options, null, isNew);
}
}
});
}
};
/**
* Align each individual data label
*/
Series.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
var chart = this.chart,
inverted = chart.inverted,
plotX = pick(point.plotX, -999),
plotY = pick(point.plotY, -999),
bBox = dataLabel.getBBox(),
baseline = chart.renderer.fontMetrics(options.style.fontSize).b,
rotCorr, // rotation correction
// Math.round for rounding errors (#2683), alignTo to allow column labels (#2700)
visible = this.visible && (point.series.forceDL || chart.isInsidePlot(plotX, mathRound(plotY), inverted) ||
(alignTo && chart.isInsidePlot(plotX, inverted ? alignTo.x + 1 : alignTo.y + alignTo.height - 1, inverted))),
alignAttr; // the final position;
if (visible) {
// The alignment box is a singular point
alignTo = extend({
x: inverted ? chart.plotWidth - plotY : plotX,
y: mathRound(inverted ? chart.plotHeight - plotX : plotY),
width: 0,
height: 0
}, alignTo);
// Add the text size for alignment calculation
extend(options, {
width: bBox.width,
height: bBox.height
});
// Allow a hook for changing alignment in the last moment, then do the alignment
if (options.rotation) { // Fancy box alignment isn't supported for rotated text
rotCorr = chart.renderer.rotCorr(baseline, options.rotation); // #3723
dataLabel[isNew ? 'attr' : 'animate']({
x: alignTo.x + options.x + alignTo.width / 2 + rotCorr.x,
y: alignTo.y + options.y + alignTo.height / 2
})
.attr({ // #3003
align: options.align
});
} else {
dataLabel.align(options, null, alignTo);
alignAttr = dataLabel.alignAttr;
// Handle justify or crop
if (pick(options.overflow, 'justify') === 'justify') {
this.justifyDataLabel(dataLabel, options, alignAttr, bBox, alignTo, isNew);
} else if (pick(options.crop, true)) {
// Now check that the data label is within the plot area
visible = chart.isInsidePlot(alignAttr.x, alignAttr.y) && chart.isInsidePlot(alignAttr.x + bBox.width, alignAttr.y + bBox.height);
}
}
}
// Show or hide based on the final aligned position
if (!visible) {
dataLabel.attr({ y: -999 });
dataLabel.placed = false; // don't animate back in
}
};
/**
* If data labels fall partly outside the plot area, align them back in, in a way that
* doesn't hide the point.
*/
Series.prototype.justifyDataLabel = function (dataLabel, options, alignAttr, bBox, alignTo, isNew) {
var chart = this.chart,
align = options.align,
verticalAlign = options.verticalAlign,
off,
justified,
padding = dataLabel.box ? 0 : (dataLabel.padding || 0);
// Off left
off = alignAttr.x + padding;
if (off < 0) {
if (align === 'right') {
options.align = 'left';
} else {
options.x = -off;
}
justified = true;
}
// Off right
off = alignAttr.x + bBox.width - padding;
if (off > chart.plotWidth) {
if (align === 'left') {
options.align = 'right';
} else {
options.x = chart.plotWidth - off;
}
justified = true;
}
// Off top
off = alignAttr.y + padding;
if (off < 0) {
if (verticalAlign === 'bottom') {
options.verticalAlign = 'top';
} else {
options.y = -off;
}
justified = true;
}
// Off bottom
off = alignAttr.y + bBox.height - padding;
if (off > chart.plotHeight) {
if (verticalAlign === 'top') {
options.verticalAlign = 'bottom';
} else {
options.y = chart.plotHeight - off;
}
justified = true;
}
if (justified) {
dataLabel.placed = !isNew;
dataLabel.align(options, null, alignTo);
}
};
/**
* Override the base drawDataLabels method by pie specific functionality
*/
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawDataLabels = function () {
var series = this,
data = series.data,
point,
chart = series.chart,
options = series.options.dataLabels,
connectorPadding = pick(options.connectorPadding, 10),
connectorWidth = pick(options.connectorWidth, 1),
plotWidth = chart.plotWidth,
plotHeight = chart.plotHeight,
connector,
connectorPath,
softConnector = pick(options.softConnector, true),
distanceOption = options.distance,
seriesCenter = series.center,
radius = seriesCenter[2] / 2,
centerY = seriesCenter[1],
outside = distanceOption > 0,
dataLabel,
dataLabelWidth,
labelPos,
labelHeight,
halves = [// divide the points into right and left halves for anti collision
[], // right
[] // left
],
x,
y,
visibility,
rankArr,
i,
j,
overflow = [0, 0, 0, 0], // top, right, bottom, left
sort = function (a, b) {
return b.y - a.y;
};
// get out if not enabled
if (!series.visible || (!options.enabled && !series._hasPointLabels)) {
return;
}
// run parent method
Series.prototype.drawDataLabels.apply(series);
// arrange points for detection collision
each(data, function (point) {
if (point.dataLabel && point.visible) { // #407, #2510
halves[point.half].push(point);
}
});
/* Loop over the points in each half, starting from the top and bottom
* of the pie to detect overlapping labels.
*/
i = 2;
while (i--) {
var slots = [],
slotsLength,
usedSlots = [],
points = halves[i],
pos,
bottom,
length = points.length,
slotIndex;
if (!length) {
continue;
}
// Sort by angle
series.sortByAngle(points, i - 0.5);
// Assume equal label heights on either hemisphere (#2630)
j = labelHeight = 0;
while (!labelHeight && points[j]) { // #1569
labelHeight = points[j] && points[j].dataLabel && (points[j].dataLabel.getBBox().height || 21); // 21 is for #968
j++;
}
// Only do anti-collision when we are outside the pie and have connectors (#856)
if (distanceOption > 0) {
// Build the slots
bottom = mathMin(centerY + radius + distanceOption, chart.plotHeight);
for (pos = mathMax(0, centerY - radius - distanceOption); pos <= bottom; pos += labelHeight) {
slots.push(pos);
}
slotsLength = slots.length;
/* Visualize the slots
if (!series.slotElements) {
series.slotElements = [];
}
if (i === 1) {
series.slotElements.forEach(function (elem) {
elem.destroy();
});
series.slotElements.length = 0;
}
slots.forEach(function (pos, no) {
var slotX = series.getX(pos, i) + chart.plotLeft - (i ? 100 : 0),
slotY = pos + chart.plotTop;
if (!isNaN(slotX)) {
series.slotElements.push(chart.renderer.rect(slotX, slotY - 7, 100, labelHeight, 1)
.attr({
'stroke-width': 1,
stroke: 'silver',
fill: 'rgba(0,0,255,0.1)'
})
.add());
series.slotElements.push(chart.renderer.text('Slot '+ no, slotX, slotY + 4)
.attr({
fill: 'silver'
}).add());
}
});
// */
// if there are more values than available slots, remove lowest values
if (length > slotsLength) {
// create an array for sorting and ranking the points within each quarter
rankArr = [].concat(points);
rankArr.sort(sort);
j = length;
while (j--) {
rankArr[j].rank = j;
}
j = length;
while (j--) {
if (points[j].rank >= slotsLength) {
points.splice(j, 1);
}
}
length = points.length;
}
// The label goes to the nearest open slot, but not closer to the edge than
// the label's index.
for (j = 0; j < length; j++) {
point = points[j];
labelPos = point.labelPos;
var closest = 9999,
distance,
slotI;
// find the closest slot index
for (slotI = 0; slotI < slotsLength; slotI++) {
distance = mathAbs(slots[slotI] - labelPos[1]);
if (distance < closest) {
closest = distance;
slotIndex = slotI;
}
}
// if that slot index is closer to the edges of the slots, move it
// to the closest appropriate slot
if (slotIndex < j && slots[j] !== null) { // cluster at the top
slotIndex = j;
} else if (slotsLength < length - j + slotIndex && slots[j] !== null) { // cluster at the bottom
slotIndex = slotsLength - length + j;
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
} else {
// Slot is taken, find next free slot below. In the next run, the next slice will find the
// slot above these, because it is the closest one
while (slots[slotIndex] === null) { // make sure it is not taken
slotIndex++;
}
}
usedSlots.push({ i: slotIndex, y: slots[slotIndex] });
slots[slotIndex] = null; // mark as taken
}
// sort them in order to fill in from the top
usedSlots.sort(sort);
}
// now the used slots are sorted, fill them up sequentially
for (j = 0; j < length; j++) {
var slot, naturalY;
point = points[j];
labelPos = point.labelPos;
dataLabel = point.dataLabel;
visibility = point.visible === false ? HIDDEN : VISIBLE;
naturalY = labelPos[1];
if (distanceOption > 0) {
slot = usedSlots.pop();
slotIndex = slot.i;
// if the slot next to currrent slot is free, the y value is allowed
// to fall back to the natural position
y = slot.y;
if ((naturalY > y && slots[slotIndex + 1] !== null) ||
(naturalY < y && slots[slotIndex - 1] !== null)) {
y = mathMin(mathMax(0, naturalY), chart.plotHeight);
}
} else {
y = naturalY;
}
// get the x - use the natural x position for first and last slot, to prevent the top
// and botton slice connectors from touching each other on either side
x = options.justify ?
seriesCenter[0] + (i ? -1 : 1) * (radius + distanceOption) :
series.getX(y === centerY - radius - distanceOption || y === centerY + radius + distanceOption ? naturalY : y, i);
// Record the placement and visibility
dataLabel._attr = {
visibility: visibility,
align: labelPos[6]
};
dataLabel._pos = {
x: x + options.x +
({ left: connectorPadding, right: -connectorPadding }[labelPos[6]] || 0),
y: y + options.y - 10 // 10 is for the baseline (label vs text)
};
dataLabel.connX = x;
dataLabel.connY = y;
// Detect overflowing data labels
if (this.options.size === null) {
dataLabelWidth = dataLabel.width;
// Overflow left
if (x - dataLabelWidth < connectorPadding) {
overflow[3] = mathMax(mathRound(dataLabelWidth - x + connectorPadding), overflow[3]);
// Overflow right
} else if (x + dataLabelWidth > plotWidth - connectorPadding) {
overflow[1] = mathMax(mathRound(x + dataLabelWidth - plotWidth + connectorPadding), overflow[1]);
}
// Overflow top
if (y - labelHeight / 2 < 0) {
overflow[0] = mathMax(mathRound(-y + labelHeight / 2), overflow[0]);
// Overflow left
} else if (y + labelHeight / 2 > plotHeight) {
overflow[2] = mathMax(mathRound(y + labelHeight / 2 - plotHeight), overflow[2]);
}
}
} // for each point
} // for each half
// Do not apply the final placement and draw the connectors until we have verified
// that labels are not spilling over.
if (arrayMax(overflow) === 0 || this.verifyDataLabelOverflow(overflow)) {
// Place the labels in the final position
this.placeDataLabels();
// Draw the connectors
if (outside && connectorWidth) {
each(this.points, function (point) {
connector = point.connector;
labelPos = point.labelPos;
dataLabel = point.dataLabel;
if (dataLabel && dataLabel._pos) {
visibility = dataLabel._attr.visibility;
x = dataLabel.connX;
y = dataLabel.connY;
connectorPath = softConnector ? [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
'C',
x, y, // first break, next to the label
2 * labelPos[2] - labelPos[4], 2 * labelPos[3] - labelPos[5],
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
] : [
M,
x + (labelPos[6] === 'left' ? 5 : -5), y, // end of the string at the label
L,
labelPos[2], labelPos[3], // second break
L,
labelPos[4], labelPos[5] // base
];
if (connector) {
connector.animate({ d: connectorPath });
connector.attr('visibility', visibility);
} else {
point.connector = connector = series.chart.renderer.path(connectorPath).attr({
'stroke-width': connectorWidth,
stroke: options.connectorColor || point.color || '#606060',
visibility: visibility
//zIndex: 0 // #2722 (reversed)
})
.add(series.dataLabelsGroup);
}
} else if (connector) {
point.connector = connector.destroy();
}
});
}
}
};
/**
* Perform the final placement of the data labels after we have verified that they
* fall within the plot area.
*/
seriesTypes.pie.prototype.placeDataLabels = function () {
each(this.points, function (point) {
var dataLabel = point.dataLabel,
_pos;
if (dataLabel) {
_pos = dataLabel._pos;
if (_pos) {
dataLabel.attr(dataLabel._attr);
dataLabel[dataLabel.moved ? 'animate' : 'attr'](_pos);
dataLabel.moved = true;
} else if (dataLabel) {
dataLabel.attr({ y: -999 });
}
}
});
};
seriesTypes.pie.prototype.alignDataLabel = noop;
/**
* Verify whether the data labels are allowed to draw, or we should run more translation and data
* label positioning to keep them inside the plot area. Returns true when data labels are ready
* to draw.
*/
seriesTypes.pie.prototype.verifyDataLabelOverflow = function (overflow) {
var center = this.center,
options = this.options,
centerOption = options.center,
minSize = options.minSize || 80,
newSize = minSize,
ret;
// Handle horizontal size and center
if (centerOption[0] !== null) { // Fixed center
newSize = mathMax(center[2] - mathMax(overflow[1], overflow[3]), minSize);
} else { // Auto center
newSize = mathMax(
center[2] - overflow[1] - overflow[3], // horizontal overflow
minSize
);
center[0] += (overflow[3] - overflow[1]) / 2; // horizontal center
}
// Handle vertical size and center
if (centerOption[1] !== null) { // Fixed center
newSize = mathMax(mathMin(newSize, center[2] - mathMax(overflow[0], overflow[2])), minSize);
} else { // Auto center
newSize = mathMax(
mathMin(
newSize,
center[2] - overflow[0] - overflow[2] // vertical overflow
),
minSize
);
center[1] += (overflow[0] - overflow[2]) / 2; // vertical center
}
// If the size must be decreased, we need to run translate and drawDataLabels again
if (newSize < center[2]) {
center[2] = newSize;
this.translate(center);
each(this.points, function (point) {
if (point.dataLabel) {
point.dataLabel._pos = null; // reset
}
});
if (this.drawDataLabels) {
this.drawDataLabels();
}
// Else, return true to indicate that the pie and its labels is within the plot area
} else {
ret = true;
}
return ret;
};
}
if (seriesTypes.column) {
/**
* Override the basic data label alignment by adjusting for the position of the column
*/
seriesTypes.column.prototype.alignDataLabel = function (point, dataLabel, options, alignTo, isNew) {
var inverted = this.chart.inverted,
series = point.series,
dlBox = point.dlBox || point.shapeArgs, // data label box for alignment
below = point.below || (point.plotY > pick(this.translatedThreshold, series.yAxis.len)),
inside = pick(options.inside, !!this.options.stacking); // draw it inside the box?
// Align to the column itself, or the top of it
if (dlBox) { // Area range uses this method but not alignTo
alignTo = merge(dlBox);
if (inverted) {
alignTo = {
x: series.yAxis.len - alignTo.y - alignTo.height,
y: series.xAxis.len - alignTo.x - alignTo.width,
width: alignTo.height,
height: alignTo.width
};
}
// Compute the alignment box
if (!inside) {
if (inverted) {
alignTo.x += below ? 0 : alignTo.width;
alignTo.width = 0;
} else {
alignTo.y += below ? alignTo.height : 0;
alignTo.height = 0;
}
}
}
// When alignment is undefined (typically columns and bars), display the individual
// point below or above the point depending on the threshold
options.align = pick(
options.align,
!inverted || inside ? 'center' : below ? 'right' : 'left'
);
options.verticalAlign = pick(
options.verticalAlign,
inverted || inside ? 'middle' : below ? 'top' : 'bottom'
);
// Call the parent method
Series.prototype.alignDataLabel.call(this, point, dataLabel, options, alignTo, isNew);
};
}
/**
* @license Highmaps JS v1.1.0 (2015-02-16)
* Highcharts module to hide overlapping data labels. This module is included by default in Highmaps.
*
* (c) 2010-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/*global Highcharts, HighchartsAdapter */
(function (H) {
var Chart = H.Chart,
each = H.each,
addEvent = HighchartsAdapter.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need to be
// considered because they are usually accompanied by data labels that lie inside the columns.
Chart.prototype.callbacks.push(function (chart) {
function collectAndHide() {
var labels = [];
each(chart.series, function (series) {
var dlOptions = series.options.dataLabels;
if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap) {
each(series.points, function (point) {
if (point.dataLabel) {
point.dataLabel.labelrank = point.labelrank;
labels.push(point.dataLabel);
}
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it now ...
collectAndHide();
// ... and after each chart redraw
addEvent(chart, 'redraw', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
* visual imression.
*/
Chart.prototype.hideOverlappingLabels = function (labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
intersectRect = function (pos1, pos2, size1, size2) {
return !(
pos2.x > pos1.x + size1.width ||
pos2.x + size2.width < pos1.x ||
pos2.y > pos1.y + size1.height ||
pos2.y + size2.height < pos1.y
);
};
// Mark with initial opacity
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
label.oldOpacity = label.opacity;
label.newOpacity = 1;
}
}
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0 &&
intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) {
(label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
}
}
}
// Hide or show
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
if (label.oldOpacity !== label.newOpacity && label.placed) {
label.alignAttr.opacity = label.newOpacity;
label[label.isOld && label.newOpacity ? 'animate' : 'attr'](label.alignAttr);
}
label.isOld = true;
}
}
};
}(Highcharts));/**
* Override to use the extreme coordinates from the SVG shape, not the
* data values
*/
wrap(Axis.prototype, 'getSeriesExtremes', function (proceed) {
var isXAxis = this.isXAxis,
dataMin,
dataMax,
xData = [],
useMapGeometry;
// Remove the xData array and cache it locally so that the proceed method doesn't use it
if (isXAxis) {
each(this.series, function (series, i) {
if (series.useMapGeometry) {
xData[i] = series.xData;
series.xData = [];
}
});
}
// Call base to reach normal cartesian series (like mappoint)
proceed.call(this);
// Run extremes logic for map and mapline
if (isXAxis) {
dataMin = pick(this.dataMin, Number.MAX_VALUE);
dataMax = pick(this.dataMax, -Number.MAX_VALUE);
each(this.series, function (series, i) {
if (series.useMapGeometry) {
dataMin = Math.min(dataMin, pick(series.minX, dataMin));
dataMax = Math.max(dataMax, pick(series.maxX, dataMin));
series.xData = xData[i]; // Reset xData array
useMapGeometry = true;
}
});
if (useMapGeometry) {
this.dataMin = dataMin;
this.dataMax = dataMax;
}
}
});
/**
* Override axis translation to make sure the aspect ratio is always kept
*/
wrap(Axis.prototype, 'setAxisTranslation', function (proceed) {
var chart = this.chart,
mapRatio,
plotRatio = chart.plotWidth / chart.plotHeight,
adjustedAxisLength,
xAxis = chart.xAxis[0],
padAxis,
fixTo,
fixDiff;
// Run the parent method
proceed.call(this);
// On Y axis, handle both
if (chart.options.chart.preserveAspectRatio && this.coll === 'yAxis' && xAxis.transA !== UNDEFINED) {
// Use the same translation for both axes
this.transA = xAxis.transA = Math.min(this.transA, xAxis.transA);
mapRatio = plotRatio / ((xAxis.max - xAxis.min) / (this.max - this.min));
// What axis to pad to put the map in the middle
padAxis = mapRatio < 1 ? this : xAxis;
// Pad it
adjustedAxisLength = (padAxis.max - padAxis.min) * padAxis.transA;
padAxis.pixelPadding = padAxis.len - adjustedAxisLength;
padAxis.minPixelPadding = padAxis.pixelPadding / 2;
fixTo = padAxis.fixTo;
if (fixTo) {
fixDiff = fixTo[1] - padAxis.toValue(fixTo[0], true);
fixDiff *= padAxis.transA;
if (Math.abs(fixDiff) > padAxis.minPixelPadding || (padAxis.min === padAxis.dataMin && padAxis.max === padAxis.dataMax)) { // zooming out again, keep within restricted area
fixDiff = 0;
}
padAxis.minPixelPadding -= fixDiff;
}
}
});
/**
* Override Axis.render in order to delete the fixTo prop
*/
wrap(Axis.prototype, 'render', function (proceed) {
proceed.call(this);
this.fixTo = null;
});
/**
* The ColorAxis object for inclusion in gradient legends
*/
var ColorAxis = Highcharts.ColorAxis = function () {
this.isColorAxis = true;
this.init.apply(this, arguments);
};
extend(ColorAxis.prototype, Axis.prototype);
extend(ColorAxis.prototype, {
defaultColorAxisOptions: {
lineWidth: 0,
gridLineWidth: 1,
tickPixelInterval: 72,
startOnTick: true,
endOnTick: true,
offset: 0,
marker: {
animation: {
duration: 50
},
color: 'gray',
width: 0.01
},
labels: {
overflow: 'justify'
},
minColor: '#EFEFFF',
maxColor: '#003875',
tickLength: 5
},
init: function (chart, userOptions) {
var horiz = chart.options.legend.layout !== 'vertical',
options;
// Build the options
options = merge(this.defaultColorAxisOptions, {
side: horiz ? 2 : 1,
reversed: !horiz
}, userOptions, {
isX: horiz,
opposite: !horiz,
showEmpty: false,
title: null,
isColor: true
});
Axis.prototype.init.call(this, chart, options);
// Base init() pushes it to the xAxis array, now pop it again
//chart[this.isXAxis ? 'xAxis' : 'yAxis'].pop();
// Prepare data classes
if (userOptions.dataClasses) {
this.initDataClasses(userOptions);
}
this.initStops(userOptions);
// Override original axis properties
this.isXAxis = true;
this.horiz = horiz;
this.zoomEnabled = false;
},
/*
* Return an intermediate color between two colors, according to pos where 0
* is the from color and 1 is the to color
*/
tweenColors: function (from, to, pos) {
// Check for has alpha, because rgba colors perform worse due to lack of
// support in WebKit.
var hasAlpha;
from = from.rgba;
to = to.rgba;
hasAlpha = (to[3] !== 1 || from[3] !== 1);
if (!to.length || !from.length) {
Highcharts.error(23);
}
return (hasAlpha ? 'rgba(' : 'rgb(') +
Math.round(to[0] + (from[0] - to[0]) * (1 - pos)) + ',' +
Math.round(to[1] + (from[1] - to[1]) * (1 - pos)) + ',' +
Math.round(to[2] + (from[2] - to[2]) * (1 - pos)) +
(hasAlpha ? (',' + (to[3] + (from[3] - to[3]) * (1 - pos))) : '') + ')';
},
initDataClasses: function (userOptions) {
var axis = this,
chart = this.chart,
dataClasses,
colorCounter = 0,
options = this.options,
len = userOptions.dataClasses.length;
this.dataClasses = dataClasses = [];
this.legendItems = [];
each(userOptions.dataClasses, function (dataClass, i) {
var colors;
dataClass = merge(dataClass);
dataClasses.push(dataClass);
if (!dataClass.color) {
if (options.dataClassColor === 'category') {
colors = chart.options.colors;
dataClass.color = colors[colorCounter++];
// loop back to zero
if (colorCounter === colors.length) {
colorCounter = 0;
}
} else {
dataClass.color = axis.tweenColors(
Color(options.minColor),
Color(options.maxColor),
len < 2 ? 0.5 : i / (len - 1) // #3219
);
}
}
});
},
initStops: function (userOptions) {
this.stops = userOptions.stops || [
[0, this.options.minColor],
[1, this.options.maxColor]
];
each(this.stops, function (stop) {
stop.color = Color(stop[1]);
});
},
/**
* Extend the setOptions method to process extreme colors and color
* stops.
*/
setOptions: function (userOptions) {
Axis.prototype.setOptions.call(this, userOptions);
this.options.crosshair = this.options.marker;
this.coll = 'colorAxis';
},
setAxisSize: function () {
var symbol = this.legendSymbol,
chart = this.chart,
x,
y,
width,
height;
if (symbol) {
this.left = x = symbol.attr('x');
this.top = y = symbol.attr('y');
this.width = width = symbol.attr('width');
this.height = height = symbol.attr('height');
this.right = chart.chartWidth - x - width;
this.bottom = chart.chartHeight - y - height;
this.len = this.horiz ? width : height;
this.pos = this.horiz ? x : y;
}
},
/**
* Translate from a value to a color
*/
toColor: function (value, point) {
var pos,
stops = this.stops,
from,
to,
color,
dataClasses = this.dataClasses,
dataClass,
i;
if (dataClasses) {
i = dataClasses.length;
while (i--) {
dataClass = dataClasses[i];
from = dataClass.from;
to = dataClass.to;
if ((from === UNDEFINED || value >= from) && (to === UNDEFINED || value <= to)) {
color = dataClass.color;
if (point) {
point.dataClass = i;
}
break;
}
}
} else {
if (this.isLog) {
value = this.val2lin(value);
}
pos = 1 - ((this.max - value) / ((this.max - this.min) || 1));
i = stops.length;
while (i--) {
if (pos > stops[i][0]) {
break;
}
}
from = stops[i] || stops[i + 1];
to = stops[i + 1] || from;
// The position within the gradient
pos = 1 - (to[0] - pos) / ((to[0] - from[0]) || 1);
color = this.tweenColors(
from.color,
to.color,
pos
);
}
return color;
},
getOffset: function () {
var group = this.legendGroup,
sideOffset = this.chart.axisOffset[this.side];
if (group) {
Axis.prototype.getOffset.call(this);
if (!this.axisGroup.parentGroup) {
// Move the axis elements inside the legend group
this.axisGroup.add(group);
this.gridGroup.add(group);
this.labelGroup.add(group);
this.added = true;
this.labelLeft = 0;
this.labelRight = this.width;
}
// Reset it to avoid color axis reserving space
this.chart.axisOffset[this.side] = sideOffset;
}
},
/**
* Create the color gradient
*/
setLegendColor: function () {
var grad,
horiz = this.horiz,
options = this.options,
reversed = this.reversed;
grad = horiz ? [+reversed, 0, +!reversed, 0] : [0, +!reversed, 0, +reversed]; // #3190
this.legendColor = {
linearGradient: { x1: grad[0], y1: grad[1], x2: grad[2], y2: grad[3] },
stops: options.stops || [
[0, options.minColor],
[1, options.maxColor]
]
};
},
/**
* The color axis appears inside the legend and has its own legend symbol
*/
drawLegendSymbol: function (legend, item) {
var padding = legend.padding,
legendOptions = legend.options,
horiz = this.horiz,
box,
width = pick(legendOptions.symbolWidth, horiz ? 200 : 12),
height = pick(legendOptions.symbolHeight, horiz ? 12 : 200),
labelPadding = pick(legendOptions.labelPadding, horiz ? 16 : 30),
itemDistance = pick(legendOptions.itemDistance, 10);
this.setLegendColor();
// Create the gradient
item.legendSymbol = this.chart.renderer.rect(
0,
legend.baseline - 11,
width,
height
).attr({
zIndex: 1
}).add(item.legendGroup);
box = item.legendSymbol.getBBox();
// Set how much space this legend item takes up
this.legendItemWidth = width + padding + (horiz ? itemDistance : labelPadding);
this.legendItemHeight = height + padding + (horiz ? labelPadding : 0);
},
/**
* Fool the legend
*/
setState: noop,
visible: true,
setVisible: noop,
getSeriesExtremes: function () {
var series;
if (this.series.length) {
series = this.series[0];
this.dataMin = series.valueMin;
this.dataMax = series.valueMax;
}
},
drawCrosshair: function (e, point) {
var newCross = !this.cross,
plotX = point && point.plotX,
plotY = point && point.plotY,
crossPos,
axisPos = this.pos,
axisLen = this.len;
if (point) {
crossPos = this.toPixels(point[point.series.colorKey]);
if (crossPos < axisPos) {
crossPos = axisPos - 2;
} else if (crossPos > axisPos + axisLen) {
crossPos = axisPos + axisLen + 2;
}
point.plotX = crossPos;
point.plotY = this.len - crossPos;
Axis.prototype.drawCrosshair.call(this, e, point);
point.plotX = plotX;
point.plotY = plotY;
if (!newCross && this.cross) {
this.cross
.attr({
fill: this.crosshair.color
})
.add(this.legendGroup);
}
}
},
getPlotLinePath: function (a, b, c, d, pos) {
if (pos) { // crosshairs only
return this.horiz ?
['M', pos - 4, this.top - 6, 'L', pos + 4, this.top - 6, pos, this.top, 'Z'] :
['M', this.left, pos, 'L', this.left - 6, pos + 6, this.left - 6, pos - 6, 'Z'];
} else {
return Axis.prototype.getPlotLinePath.call(this, a, b, c, d);
}
},
update: function (newOptions, redraw) {
each(this.series, function (series) {
series.isDirtyData = true; // Needed for Axis.update when choropleth colors change
});
Axis.prototype.update.call(this, newOptions, redraw);
if (this.legendItem) {
this.setLegendColor();
this.chart.legend.colorizeItem(this, true);
}
},
/**
* Get the legend item symbols for data classes
*/
getDataClassLegendSymbols: function () {
var axis = this,
chart = this.chart,
legendItems = this.legendItems,
legendOptions = chart.options.legend,
valueDecimals = legendOptions.valueDecimals,
valueSuffix = legendOptions.valueSuffix || '',
name;
if (!legendItems.length) {
each(this.dataClasses, function (dataClass, i) {
var vis = true,
from = dataClass.from,
to = dataClass.to;
// Assemble the default name. This can be overridden by legend.options.labelFormatter
name = '';
if (from === UNDEFINED) {
name = '< ';
} else if (to === UNDEFINED) {
name = '> ';
}
if (from !== UNDEFINED) {
name += Highcharts.numberFormat(from, valueDecimals) + valueSuffix;
}
if (from !== UNDEFINED && to !== UNDEFINED) {
name += ' - ';
}
if (to !== UNDEFINED) {
name += Highcharts.numberFormat(to, valueDecimals) + valueSuffix;
}
// Add a mock object to the legend items
legendItems.push(extend({
chart: chart,
name: name,
options: {},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
visible: true,
setState: noop,
setVisible: function () {
vis = this.visible = !vis;
each(axis.series, function (series) {
each(series.points, function (point) {
if (point.dataClass === i) {
point.setVisible(vis);
}
});
});
chart.legend.colorizeItem(this, vis);
}
}, dataClass));
});
}
return legendItems;
},
name: '' // Prevents 'undefined' in legend in IE8
});
/**
* Handle animation of the color attributes directly
*/
each(['fill', 'stroke'], function (prop) {
HighchartsAdapter.addAnimSetter(prop, function (fx) {
fx.elem.attr(prop, ColorAxis.prototype.tweenColors(Color(fx.start), Color(fx.end), fx.pos));
});
});
/**
* Extend the chart getAxes method to also get the color axis
*/
wrap(Chart.prototype, 'getAxes', function (proceed) {
var options = this.options,
colorAxisOptions = options.colorAxis;
proceed.call(this);
this.colorAxis = [];
if (colorAxisOptions) {
proceed = new ColorAxis(this, colorAxisOptions); // Fake assignment for jsLint
}
});
/**
* Wrap the legend getAllItems method to add the color axis. This also removes the
* axis' own series to prevent them from showing up individually.
*/
wrap(Legend.prototype, 'getAllItems', function (proceed) {
var allItems = [],
colorAxis = this.chart.colorAxis[0];
if (colorAxis) {
// Data classes
if (colorAxis.options.dataClasses) {
allItems = allItems.concat(colorAxis.getDataClassLegendSymbols());
// Gradient legend
} else {
// Add this axis on top
allItems.push(colorAxis);
}
// Don't add the color axis' series
each(colorAxis.series, function (series) {
series.options.showInLegend = false;
});
}
return allItems.concat(proceed.call(this));
});/**
* Mixin for maps and heatmaps
*/
var colorSeriesMixin = {
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'borderColor',
'stroke-width': 'borderWidth',
fill: 'color',
dashstyle: 'dashStyle'
},
pointArrayMap: ['value'],
axisTypes: ['xAxis', 'yAxis', 'colorAxis'],
optionalAxis: 'colorAxis',
trackerGroups: ['group', 'markerGroup', 'dataLabelsGroup'],
getSymbol: noop,
parallelArrays: ['x', 'y', 'value'],
colorKey: 'value',
/**
* In choropleth maps, the color is a result of the value, so this needs translation too
*/
translateColors: function () {
var series = this,
nullColor = this.options.nullColor,
colorAxis = this.colorAxis,
colorKey = this.colorKey;
each(this.data, function (point) {
var value = point[colorKey],
color;
color = value === null ? nullColor : (colorAxis && value !== undefined) ? colorAxis.toColor(value, point) : point.color || series.color;
if (color) {
point.color = color;
}
});
}
};
// The vector-effect attribute is not supported in IE <= 11 (at least), so we need
// diffent logic (#3218)
var supportsVectorEffect = document.documentElement.style.vectorEffect !== undefined;
/**
* Extend the default options with map options
*/
defaultPlotOptions.map = merge(defaultPlotOptions.scatter, {
allAreas: true,
animation: false, // makes the complex shapes slow
nullColor: '#F8F8F8',
borderColor: 'silver',
borderWidth: 1,
marker: null,
stickyTracking: false,
dataLabels: {
formatter: function () { // #2945
return this.point.value;
},
inside: true, // for the color
verticalAlign: 'middle',
crop: false,
overflow: false,
padding: 0
},
turboThreshold: 0,
tooltip: {
followPointer: true,
pointFormat: '{point.name}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
brightness: 0.2,
halo: null
}
}
});
/**
* The MapAreaPoint object
*/
var MapAreaPoint = extendClass(Point, {
/**
* Extend the Point object to split paths
*/
applyOptions: function (options, x) {
var point = Point.prototype.applyOptions.call(this, options, x),
series = this.series,
joinBy = series.joinBy,
mapPoint;
if (series.mapData) {
mapPoint = point[joinBy[1]] !== undefined && series.mapMap[point[joinBy[1]]];
if (mapPoint) {
// This applies only to bubbles
if (series.xyFromShape) {
point.x = mapPoint._midX;
point.y = mapPoint._midY;
}
extend(point, mapPoint); // copy over properties
} else {
point.value = point.value || null;
}
}
return point;
},
/**
* Set the visibility of a single map area
*/
setVisible: function (vis) {
var point = this,
method = vis ? 'show' : 'hide';
// Show and hide associated elements
each(['graphic', 'dataLabel'], function (key) {
if (point[key]) {
point[key][method]();
}
});
},
/**
* Stop the fade-out
*/
onMouseOver: function (e) {
clearTimeout(this.colorInterval);
if (this.value !== null) {
Point.prototype.onMouseOver.call(this, e);
} else { //#3401 Tooltip doesn't hide when hovering over null points
this.series.onMouseOut(e);
}
},
/**
* Custom animation for tweening out the colors. Animation reduces blinking when hovering
* over islands and coast lines. We run a custom implementation of animation becuase we
* need to be able to run this independently from other animations like zoom redraw. Also,
* adding color animation to the adapters would introduce almost the same amount of code.
*/
onMouseOut: function () {
var point = this,
start = +new Date(),
normalColor = Color(point.color),
hoverColor = Color(point.pointAttr.hover.fill),
animation = point.series.options.states.normal.animation,
duration = animation && (animation.duration || 500),
fill;
if (duration && normalColor.rgba.length === 4 && hoverColor.rgba.length === 4 && point.state !== 'select') {
fill = point.pointAttr[''].fill;
delete point.pointAttr[''].fill; // avoid resetting it in Point.setState
clearTimeout(point.colorInterval);
point.colorInterval = setInterval(function () {
var pos = (new Date() - start) / duration,
graphic = point.graphic;
if (pos > 1) {
pos = 1;
}
if (graphic) {
graphic.attr('fill', ColorAxis.prototype.tweenColors.call(0, hoverColor, normalColor, pos));
}
if (pos >= 1) {
clearTimeout(point.colorInterval);
}
}, 13);
}
Point.prototype.onMouseOut.call(point);
if (fill) {
point.pointAttr[''].fill = fill;
}
},
/**
* Zoom the chart to view a specific area point
*/
zoomTo: function () {
var point = this,
series = point.series;
series.xAxis.setExtremes(
point._minX,
point._maxX,
false
);
series.yAxis.setExtremes(
point._minY,
point._maxY,
false
);
series.chart.redraw();
}
});
/**
* Add the series type
*/
seriesTypes.map = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, {
type: 'map',
pointClass: MapAreaPoint,
supportsDrilldown: true,
getExtremesFromAll: true,
useMapGeometry: true, // get axis extremes from paths, not values
forceDL: true,
searchPoint: noop,
/**
* Get the bounding box of all paths in the map combined.
*/
getBox: function (paths) {
var MAX_VALUE = Number.MAX_VALUE,
maxX = -MAX_VALUE,
minX = MAX_VALUE,
maxY = -MAX_VALUE,
minY = MAX_VALUE,
minRange = MAX_VALUE,
xAxis = this.xAxis,
yAxis = this.yAxis,
hasBox;
// Find the bounding box
each(paths || [], function (point) {
if (point.path) {
if (typeof point.path === 'string') {
point.path = Highcharts.splitPath(point.path);
}
var path = point.path || [],
i = path.length,
even = false, // while loop reads from the end
pointMaxX = -MAX_VALUE,
pointMinX = MAX_VALUE,
pointMaxY = -MAX_VALUE,
pointMinY = MAX_VALUE,
properties = point.properties;
// The first time a map point is used, analyze its box
if (!point._foundBox) {
while (i--) {
if (typeof path[i] === 'number' && !isNaN(path[i])) {
if (even) { // even = x
pointMaxX = Math.max(pointMaxX, path[i]);
pointMinX = Math.min(pointMinX, path[i]);
} else { // odd = Y
pointMaxY = Math.max(pointMaxY, path[i]);
pointMinY = Math.min(pointMinY, path[i]);
}
even = !even;
}
}
// Cache point bounding box for use to position data labels, bubbles etc
point._midX = pointMinX + (pointMaxX - pointMinX) *
(point.middleX || (properties && properties['hc-middle-x']) || 0.5); // pick is slower and very marginally needed
point._midY = pointMinY + (pointMaxY - pointMinY) *
(point.middleY || (properties && properties['hc-middle-y']) || 0.5);
point._maxX = pointMaxX;
point._minX = pointMinX;
point._maxY = pointMaxY;
point._minY = pointMinY;
point.labelrank = pick(point.labelrank, (pointMaxX - pointMinX) * (pointMaxY - pointMinY));
point._foundBox = true;
}
maxX = Math.max(maxX, point._maxX);
minX = Math.min(minX, point._minX);
maxY = Math.max(maxY, point._maxY);
minY = Math.min(minY, point._minY);
minRange = Math.min(point._maxX - point._minX, point._maxY - point._minY, minRange);
hasBox = true;
}
});
// Set the box for the whole series
if (hasBox) {
this.minY = Math.min(minY, pick(this.minY, MAX_VALUE));
this.maxY = Math.max(maxY, pick(this.maxY, -MAX_VALUE));
this.minX = Math.min(minX, pick(this.minX, MAX_VALUE));
this.maxX = Math.max(maxX, pick(this.maxX, -MAX_VALUE));
// If no minRange option is set, set the default minimum zooming range to 5 times the
// size of the smallest element
if (xAxis && xAxis.options.minRange === undefined) {
xAxis.minRange = Math.min(5 * minRange, (this.maxX - this.minX) / 5, xAxis.minRange || MAX_VALUE);
}
if (yAxis && yAxis.options.minRange === undefined) {
yAxis.minRange = Math.min(5 * minRange, (this.maxY - this.minY) / 5, yAxis.minRange || MAX_VALUE);
}
} else {
this.minY = UNDEFINED;
this.maxY = UNDEFINED;
this.minX = UNDEFINED;
this.maxX = UNDEFINED;
}
},
getExtremes: function () {
// Get the actual value extremes for colors
Series.prototype.getExtremes.call(this, this.valueData);
// Recalculate box on updated data
if (this.chart.hasRendered && this.isDirtyData) {
this.getBox(this.options.data);
}
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Extremes for the mock Y axis
this.dataMin = this.minY;
this.dataMax = this.maxY;
},
/**
* Translate the path so that it automatically fits into the plot area box
* @param {Object} path
*/
translatePath: function (path) {
var series = this,
even = false, // while loop reads from the end
xAxis = series.xAxis,
yAxis = series.yAxis,
xMin = xAxis.min,
xTransA = xAxis.transA,
xMinPixelPadding = xAxis.minPixelPadding,
yMin = yAxis.min,
yTransA = yAxis.transA,
yMinPixelPadding = yAxis.minPixelPadding,
i,
ret = []; // Preserve the original
// Do the translation
if (path) {
i = path.length;
while (i--) {
if (typeof path[i] === 'number') {
ret[i] = even ?
(path[i] - xMin) * xTransA + xMinPixelPadding :
(path[i] - yMin) * yTransA + yMinPixelPadding;
even = !even;
} else {
ret[i] = path[i];
}
}
}
return ret;
},
/**
* Extend setData to join in mapData. If the allAreas option is true, all areas
* from the mapData are used, and those that don't correspond to a data value
* are given null values.
*/
setData: function (data, redraw) {
var options = this.options,
mapData = options.mapData,
joinBy = options.joinBy,
joinByNull = joinBy === null,
dataUsed = [],
mapPoint,
transform,
mapTransforms,
props,
i;
if (joinByNull) {
joinBy = '_i';
}
joinBy = this.joinBy = Highcharts.splat(joinBy);
if (!joinBy[1]) {
joinBy[1] = joinBy[0];
}
// Pick up numeric values, add index
if (data) {
each(data, function (val, i) {
if (typeof val === 'number') {
data[i] = {
value: val
};
}
if (joinByNull) {
data[i]._i = i;
}
});
}
this.getBox(data);
if (mapData) {
if (mapData.type === 'FeatureCollection') {
if (mapData['hc-transform']) {
this.chart.mapTransforms = mapTransforms = mapData['hc-transform'];
// Cache cos/sin of transform rotation angle
for (transform in mapTransforms) {
if (mapTransforms.hasOwnProperty(transform) && transform.rotation) {
transform.cosAngle = Math.cos(transform.rotation);
transform.sinAngle = Math.sin(transform.rotation);
}
}
}
mapData = Highcharts.geojson(mapData, this.type, this);
}
this.getBox(mapData);
this.mapData = mapData;
this.mapMap = {};
for (i = 0; i < mapData.length; i++) {
mapPoint = mapData[i];
props = mapPoint.properties;
mapPoint._i = i;
// Copy the property over to root for faster access
if (joinBy[0] && props && props[joinBy[0]]) {
mapPoint[joinBy[0]] = props[joinBy[0]];
}
this.mapMap[mapPoint[joinBy[0]]] = mapPoint;
}
if (options.allAreas) {
data = data || [];
// Registered the point codes that actually hold data
if (joinBy[1]) {
each(data, function (point) {
dataUsed.push(point[joinBy[1]]);
});
}
// Add those map points that don't correspond to data, which will be drawn as null points
dataUsed = '|' + dataUsed.join('|') + '|'; // String search is faster than array.indexOf
each(mapData, function (mapPoint) {
if (!joinBy[0] || dataUsed.indexOf('|' + mapPoint[joinBy[0]] + '|') === -1) {
data.push(merge(mapPoint, { value: null }));
}
});
}
}
Series.prototype.setData.call(this, data, redraw);
},
/**
* No graph for the map series
*/
drawGraph: noop,
/**
* We need the points' bounding boxes in order to draw the data labels, so
* we skip it now and call it from drawPoints instead.
*/
drawDataLabels: noop,
/**
* Allow a quick redraw by just translating the area group. Used for zooming and panning
* in capable browsers.
*/
doFullTranslate: function () {
return this.isDirtyData || this.chart.isResizing || this.chart.renderer.isVML || !this.baseTrans;
},
/**
* Add the path option for data points. Find the max value for color calculation.
*/
translate: function () {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
doFullTranslate = series.doFullTranslate();
series.generatePoints();
each(series.data, function (point) {
// Record the middle point (loosely based on centroid), determined
// by the middleX and middleY options.
point.plotX = xAxis.toPixels(point._midX, true);
point.plotY = yAxis.toPixels(point._midY, true);
if (doFullTranslate) {
point.shapeType = 'path';
point.shapeArgs = {
d: series.translatePath(point.path)
};
if (supportsVectorEffect) {
point.shapeArgs['vector-effect'] = 'non-scaling-stroke';
}
}
});
series.translateColors();
},
/**
* Use the drawPoints method of column, that is able to handle simple shapeArgs.
* Extend it by assigning the tooltip position.
*/
drawPoints: function () {
var series = this,
xAxis = series.xAxis,
yAxis = series.yAxis,
group = series.group,
chart = series.chart,
renderer = chart.renderer,
scaleX,
scaleY,
translateX,
translateY,
baseTrans = this.baseTrans;
// Set a group that handles transform during zooming and panning in order to preserve clipping
// on series.group
if (!series.transformGroup) {
series.transformGroup = renderer.g()
.attr({
scaleX: 1,
scaleY: 1
})
.add(group);
}
// Draw the shapes again
if (series.doFullTranslate()) {
// Individual point actions
if (chart.hasRendered && series.pointAttrToOptions.fill === 'color') {
each(series.points, function (point) {
// Reset color on update/redraw
if (point.graphic) {
point.graphic.attr('fill', point.color);
}
});
}
// If vector-effect is not supported, we set the stroke-width on the group element
// and let all point graphics inherit. That way we don't have to iterate over all
// points to update the stroke-width on zooming.
if (!supportsVectorEffect) {
each(series.points, function (point) {
var attr = point.pointAttr[''];
if (attr['stroke-width'] === series.pointAttr['']['stroke-width']) {
attr['stroke-width'] = 'inherit';
}
});
}
// Draw them in transformGroup
series.group = series.transformGroup;
seriesTypes.column.prototype.drawPoints.apply(series);
series.group = group; // Reset
// Add class names
each(series.points, function (point) {
if (point.graphic) {
if (point.name) {
point.graphic.addClass('highcharts-name-' + point.name.replace(' ', '-').toLowerCase());
}
if (point.properties && point.properties['hc-key']) {
point.graphic.addClass('highcharts-key-' + point.properties['hc-key'].toLowerCase());
}
if (!supportsVectorEffect) {
point.graphic['stroke-widthSetter'] = noop;
}
}
});
// Set the base for later scale-zooming. The originX and originY properties are the
// axis values in the plot area's upper left corner.
this.baseTrans = {
originX: xAxis.min - xAxis.minPixelPadding / xAxis.transA,
originY: yAxis.min - yAxis.minPixelPadding / yAxis.transA + (yAxis.reversed ? 0 : yAxis.len / yAxis.transA),
transAX: xAxis.transA,
transAY: yAxis.transA
};
// Reset transformation in case we're doing a full translate (#3789)
this.transformGroup.animate({
translateX: 0,
translateY: 0,
scaleX: 1,
scaleY: 1
});
// Just update the scale and transform for better performance
} else {
scaleX = xAxis.transA / baseTrans.transAX;
scaleY = yAxis.transA / baseTrans.transAY;
translateX = xAxis.toPixels(baseTrans.originX, true);
translateY = yAxis.toPixels(baseTrans.originY, true);
// Handle rounding errors in normal view (#3789)
if (scaleX > 0.99 && scaleX < 1.01 && scaleY > 0.99 && scaleY < 1.01) {
scaleX = 1;
scaleY = 1;
translateX = Math.round(translateX);
translateY = Math.round(translateY);
}
this.transformGroup.animate({
translateX: translateX,
translateY: translateY,
scaleX: scaleX,
scaleY: scaleY
});
}
// Set the stroke-width directly on the group element so the children inherit it. We need to use
// setAttribute directly, because the stroke-widthSetter method expects a stroke color also to be
// set.
if (!supportsVectorEffect) {
series.group.element.setAttribute('stroke-width', series.options.borderWidth / (scaleX || 1));
}
this.drawMapDataLabels();
},
/**
* Draw the data labels. Special for maps is the time that the data labels are drawn (after points),
* and the clipping of the dataLabelsGroup.
*/
drawMapDataLabels: function () {
Series.prototype.drawDataLabels.call(this);
if (this.dataLabelsGroup) {
this.dataLabelsGroup.clip(this.chart.clipRect);
}
},
/**
* Override render to throw in an async call in IE8. Otherwise it chokes on the US counties demo.
*/
render: function () {
var series = this,
render = Series.prototype.render;
// Give IE8 some time to breathe.
if (series.chart.renderer.isVML && series.data.length > 3000) {
setTimeout(function () {
render.call(series);
});
} else {
render.call(series);
}
},
/**
* The initial animation for the map series. By default, animation is disabled.
* Animation of map shapes is not at all supported in VML browsers.
*/
animate: function (init) {
var chart = this.chart,
animation = this.options.animation,
group = this.group,
xAxis = this.xAxis,
yAxis = this.yAxis,
left = xAxis.pos,
top = yAxis.pos;
if (chart.renderer.isSVG) {
if (animation === true) {
animation = {
duration: 1000
};
}
// Initialize the animation
if (init) {
// Scale down the group and place it in the center
group.attr({
translateX: left + xAxis.len / 2,
translateY: top + yAxis.len / 2,
scaleX: 0.001, // #1499
scaleY: 0.001
});
// Run the animation
} else {
group.animate({
translateX: left,
translateY: top,
scaleX: 1,
scaleY: 1
}, animation);
// Delete this function to allow it only once
this.animate = null;
}
}
},
/**
* Animate in the new series from the clicked point in the old series.
* Depends on the drilldown.js module
*/
animateDrilldown: function (init) {
var toBox = this.chart.plotBox,
level = this.chart.drilldownLevels[this.chart.drilldownLevels.length - 1],
fromBox = level.bBox,
animationOptions = this.chart.options.drilldown.animation,
scale;
if (!init) {
scale = Math.min(fromBox.width / toBox.width, fromBox.height / toBox.height);
level.shapeArgs = {
scaleX: scale,
scaleY: scale,
translateX: fromBox.x,
translateY: fromBox.y
};
// TODO: Animate this.group instead
each(this.points, function (point) {
point.graphic
.attr(level.shapeArgs)
.animate({
scaleX: 1,
scaleY: 1,
translateX: 0,
translateY: 0
}, animationOptions);
});
this.animate = null;
}
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
/**
* When drilling up, pull out the individual point graphics from the lower series
* and animate them into the origin point in the upper series.
*/
animateDrillupFrom: function (level) {
seriesTypes.column.prototype.animateDrillupFrom.call(this, level);
},
/**
* When drilling up, keep the upper series invisible until the lower series has
* moved into place
*/
animateDrillupTo: function (init) {
seriesTypes.column.prototype.animateDrillupTo.call(this, init);
}
}));/**
* @license Highmaps JS v1.1.0 (2015-02-16)
* Highcharts module to hide overlapping data labels. This module is included by default in Highmaps.
*
* (c) 2010-2014 Torstein Honsi
*
* License: www.highcharts.com/license
*/
/*global Highcharts, HighchartsAdapter */
(function (H) {
var Chart = H.Chart,
each = H.each,
addEvent = HighchartsAdapter.addEvent;
// Collect potensial overlapping data labels. Stack labels probably don't need to be
// considered because they are usually accompanied by data labels that lie inside the columns.
Chart.prototype.callbacks.push(function (chart) {
function collectAndHide() {
var labels = [];
each(chart.series, function (series) {
var dlOptions = series.options.dataLabels;
if ((dlOptions.enabled || series._hasPointLabels) && !dlOptions.allowOverlap) {
each(series.points, function (point) {
if (point.dataLabel) {
point.dataLabel.labelrank = point.labelrank;
labels.push(point.dataLabel);
}
});
}
});
chart.hideOverlappingLabels(labels);
}
// Do it now ...
collectAndHide();
// ... and after each chart redraw
addEvent(chart, 'redraw', collectAndHide);
});
/**
* Hide overlapping labels. Labels are moved and faded in and out on zoom to provide a smooth
* visual imression.
*/
Chart.prototype.hideOverlappingLabels = function (labels) {
var len = labels.length,
label,
i,
j,
label1,
label2,
intersectRect = function (pos1, pos2, size1, size2) {
return !(
pos2.x > pos1.x + size1.width ||
pos2.x + size2.width < pos1.x ||
pos2.y > pos1.y + size1.height ||
pos2.y + size2.height < pos1.y
);
};
// Mark with initial opacity
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
label.oldOpacity = label.opacity;
label.newOpacity = 1;
}
}
// Detect overlapping labels
for (i = 0; i < len; i++) {
label1 = labels[i];
for (j = i + 1; j < len; ++j) {
label2 = labels[j];
if (label1 && label2 && label1.placed && label2.placed && label1.newOpacity !== 0 && label2.newOpacity !== 0 &&
intersectRect(label1.alignAttr, label2.alignAttr, label1, label2)) {
(label1.labelrank < label2.labelrank ? label1 : label2).newOpacity = 0;
}
}
}
// Hide or show
for (i = 0; i < len; i++) {
label = labels[i];
if (label) {
if (label.oldOpacity !== label.newOpacity && label.placed) {
label.alignAttr.opacity = label.newOpacity;
label[label.isOld && label.newOpacity ? 'animate' : 'attr'](label.alignAttr);
}
label.isOld = true;
}
}
};
}(Highcharts));
// Add events to the Chart object itself
extend(Chart.prototype, {
renderMapNavigation: function () {
var chart = this,
options = this.options.mapNavigation,
buttons = options.buttons,
n,
button,
buttonOptions,
attr,
states,
outerHandler = function () {
this.handler.call(chart);
};
if (pick(options.enableButtons, options.enabled) && !chart.renderer.forExport) {
for (n in buttons) {
if (buttons.hasOwnProperty(n)) {
buttonOptions = merge(options.buttonOptions, buttons[n]);
attr = buttonOptions.theme;
states = attr.states;
button = chart.renderer.button(
buttonOptions.text,
0,
0,
outerHandler,
attr,
states && states.hover,
states && states.select,
0,
n === 'zoomIn' ? 'topbutton' : 'bottombutton'
)
.attr({
width: buttonOptions.width,
height: buttonOptions.height,
title: chart.options.lang[n],
zIndex: 5
})
.css(buttonOptions.style)
.add();
button.handler = buttonOptions.onclick;
button.align(extend(buttonOptions, { width: button.width, height: 2 * button.height }), null, buttonOptions.alignTo);
}
}
}
},
/**
* Fit an inner box to an outer. If the inner box overflows left or right, align it to the sides of the
* outer. If it overflows both sides, fit it within the outer. This is a pattern that occurs more places
* in Highcharts, perhaps it should be elevated to a common utility function.
*/
fitToBox: function (inner, outer) {
each([['x', 'width'], ['y', 'height']], function (dim) {
var pos = dim[0],
size = dim[1];
if (inner[pos] + inner[size] > outer[pos] + outer[size]) { // right overflow
if (inner[size] > outer[size]) { // the general size is greater, fit fully to outer
inner[size] = outer[size];
inner[pos] = outer[pos];
} else { // align right
inner[pos] = outer[pos] + outer[size] - inner[size];
}
}
if (inner[size] > outer[size]) {
inner[size] = outer[size];
}
if (inner[pos] < outer[pos]) {
inner[pos] = outer[pos];
}
});
return inner;
},
/**
* Zoom the map in or out by a certain amount. Less than 1 zooms in, greater than 1 zooms out.
*/
mapZoom: function (howMuch, centerXArg, centerYArg, mouseX, mouseY) {
/*if (this.isMapZooming) {
this.mapZoomQueue = arguments;
return;
}*/
var chart = this,
xAxis = chart.xAxis[0],
xRange = xAxis.max - xAxis.min,
centerX = pick(centerXArg, xAxis.min + xRange / 2),
newXRange = xRange * howMuch,
yAxis = chart.yAxis[0],
yRange = yAxis.max - yAxis.min,
centerY = pick(centerYArg, yAxis.min + yRange / 2),
newYRange = yRange * howMuch,
fixToX = mouseX ? ((mouseX - xAxis.pos) / xAxis.len) : 0.5,
fixToY = mouseY ? ((mouseY - yAxis.pos) / yAxis.len) : 0.5,
newXMin = centerX - newXRange * fixToX,
newYMin = centerY - newYRange * fixToY,
newExt = chart.fitToBox({
x: newXMin,
y: newYMin,
width: newXRange,
height: newYRange
}, {
x: xAxis.dataMin,
y: yAxis.dataMin,
width: xAxis.dataMax - xAxis.dataMin,
height: yAxis.dataMax - yAxis.dataMin
});
// When mousewheel zooming, fix the point under the mouse
if (mouseX) {
xAxis.fixTo = [mouseX - xAxis.pos, centerXArg];
}
if (mouseY) {
yAxis.fixTo = [mouseY - yAxis.pos, centerYArg];
}
// Zoom
if (howMuch !== undefined) {
xAxis.setExtremes(newExt.x, newExt.x + newExt.width, false);
yAxis.setExtremes(newExt.y, newExt.y + newExt.height, false);
// Reset zoom
} else {
xAxis.setExtremes(undefined, undefined, false);
yAxis.setExtremes(undefined, undefined, false);
}
// Prevent zooming until this one is finished animating
/*chart.holdMapZoom = true;
setTimeout(function () {
chart.holdMapZoom = false;
}, 200);*/
/*delay = animation ? animation.duration || 500 : 0;
if (delay) {
chart.isMapZooming = true;
setTimeout(function () {
chart.isMapZooming = false;
if (chart.mapZoomQueue) {
chart.mapZoom.apply(chart, chart.mapZoomQueue);
}
chart.mapZoomQueue = null;
}, delay);
}*/
chart.redraw();
}
});
/**
* Extend the Chart.render method to add zooming and panning
*/
wrap(Chart.prototype, 'render', function (proceed) {
var chart = this,
mapNavigation = chart.options.mapNavigation;
// Render the plus and minus buttons. Doing this before the shapes makes getBBox much quicker, at least in Chrome.
chart.renderMapNavigation();
proceed.call(chart);
// Add the double click event
if (pick(mapNavigation.enableDoubleClickZoom, mapNavigation.enabled) || mapNavigation.enableDoubleClickZoomTo) {
addEvent(chart.container, 'dblclick', function (e) {
chart.pointer.onContainerDblClick(e);
});
}
// Add the mousewheel event
if (pick(mapNavigation.enableMouseWheelZoom, mapNavigation.enabled)) {
addEvent(chart.container, document.onmousewheel === undefined ? 'DOMMouseScroll' : 'mousewheel', function (e) {
chart.pointer.onContainerMouseWheel(e);
return false;
});
}
});
// Extend the Pointer
extend(Pointer.prototype, {
/**
* The event handler for the doubleclick event
*/
onContainerDblClick: function (e) {
var chart = this.chart;
e = this.normalize(e);
if (chart.options.mapNavigation.enableDoubleClickZoomTo) {
if (chart.pointer.inClass(e.target, 'highcharts-tracker')) {
chart.hoverPoint.zoomTo();
}
} else if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
0.5,
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
},
/**
* The event handler for the mouse scroll event
*/
onContainerMouseWheel: function (e) {
var chart = this.chart,
delta;
e = this.normalize(e);
// Firefox uses e.detail, WebKit and IE uses wheelDelta
delta = e.detail || -(e.wheelDelta / 120);
if (chart.isInsidePlot(e.chartX - chart.plotLeft, e.chartY - chart.plotTop)) {
chart.mapZoom(
//delta > 0 ? 2 : 0.5,
Math.pow(2, delta),
chart.xAxis[0].toValue(e.chartX),
chart.yAxis[0].toValue(e.chartY),
e.chartX,
e.chartY
);
}
}
});
// Implement the pinchType option
wrap(Pointer.prototype, 'init', function (proceed, chart, options) {
proceed.call(this, chart, options);
// Pinch status
if (pick(options.mapNavigation.enableTouchZoom, options.mapNavigation.enabled)) {
this.pinchX = this.pinchHor = this.pinchY = this.pinchVert = this.hasZoom = true;
}
});
// Extend the pinchTranslate method to preserve fixed ratio when zooming
wrap(Pointer.prototype, 'pinchTranslate', function (proceed, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch) {
var xBigger;
proceed.call(this, pinchDown, touches, transform, selectionMarker, clip, lastValidTouch);
// Keep ratio
if (this.chart.options.chart.type === 'map' && this.hasZoom) {
xBigger = transform.scaleX > transform.scaleY;
this.pinchTranslateDirection(
!xBigger,
pinchDown,
touches,
transform,
selectionMarker,
clip,
lastValidTouch,
xBigger ? transform.scaleX : transform.scaleY
);
}
});
// The mapline series type
defaultPlotOptions.mapline = merge(defaultPlotOptions.map, {
lineWidth: 1,
fillColor: 'none'
});
seriesTypes.mapline = extendClass(seriesTypes.map, {
type: 'mapline',
pointAttrToOptions: { // mapping between SVG attributes and the corresponding options
stroke: 'color',
'stroke-width': 'lineWidth',
fill: 'fillColor',
dashstyle: 'dashStyle'
},
drawLegendSymbol: seriesTypes.line.prototype.drawLegendSymbol
});
// The mappoint series type
defaultPlotOptions.mappoint = merge(defaultPlotOptions.scatter, {
dataLabels: {
enabled: true,
formatter: function () { // #2945
return this.point.name;
},
crop: false,
defer: false,
overflow: false,
style: {
color: '#000000'
}
}
});
seriesTypes.mappoint = extendClass(seriesTypes.scatter, {
type: 'mappoint',
forceDL: true,
pointClass: extendClass(Point, {
applyOptions: function (options, x) {
var point = Point.prototype.applyOptions.call(this, options, x);
if (options.lat !== undefined && options.lon !== undefined) {
point = extend(point, this.series.chart.fromLatLonToPoint(point));
}
return point;
}
})
});/* ****************************************************************************
* Start Bubble series code *
*****************************************************************************/
// 1 - set default options
defaultPlotOptions.bubble = merge(defaultPlotOptions.scatter, {
dataLabels: {
formatter: function () { // #2945
return this.point.z;
},
inside: true,
verticalAlign: 'middle'
},
// displayNegative: true,
marker: {
// fillOpacity: 0.5,
lineColor: null, // inherit from series.color
lineWidth: 1
},
minSize: 8,
maxSize: '20%',
// negativeColor: null,
// sizeBy: 'area'
states: {
hover: {
halo: {
size: 5
}
}
},
tooltip: {
pointFormat: '({point.x}, {point.y}), Size: {point.z}'
},
turboThreshold: 0,
zThreshold: 0,
zoneAxis: 'z'
});
var BubblePoint = extendClass(Point, {
haloPath: function () {
return Point.prototype.haloPath.call(this, this.shapeArgs.r + this.series.options.states.hover.halo.size);
},
ttBelow: false
});
// 2 - Create the series object
seriesTypes.bubble = extendClass(seriesTypes.scatter, {
type: 'bubble',
pointClass: BubblePoint,
pointArrayMap: ['y', 'z'],
parallelArrays: ['x', 'y', 'z'],
trackerGroups: ['group', 'dataLabelsGroup'],
bubblePadding: true,
zoneAxis: 'z',
/**
* Mapping between SVG attributes and the corresponding options
*/
pointAttrToOptions: {
stroke: 'lineColor',
'stroke-width': 'lineWidth',
fill: 'fillColor'
},
/**
* Apply the fillOpacity to all fill positions
*/
applyOpacity: function (fill) {
var markerOptions = this.options.marker,
fillOpacity = pick(markerOptions.fillOpacity, 0.5);
// When called from Legend.colorizeItem, the fill isn't predefined
fill = fill || markerOptions.fillColor || this.color;
if (fillOpacity !== 1) {
fill = Color(fill).setOpacity(fillOpacity).get('rgba');
}
return fill;
},
/**
* Extend the convertAttribs method by applying opacity to the fill
*/
convertAttribs: function () {
var obj = Series.prototype.convertAttribs.apply(this, arguments);
obj.fill = this.applyOpacity(obj.fill);
return obj;
},
/**
* Get the radius for each point based on the minSize, maxSize and each point's Z value. This
* must be done prior to Series.translate because the axis needs to add padding in
* accordance with the point sizes.
*/
getRadii: function (zMin, zMax, minSize, maxSize) {
var len,
i,
pos,
zData = this.zData,
radii = [],
sizeByArea = this.options.sizeBy !== 'width',
zRange;
// Set the shape type and arguments to be picked up in drawPoints
for (i = 0, len = zData.length; i < len; i++) {
zRange = zMax - zMin;
pos = zRange > 0 ? // relative size, a number between 0 and 1
(zData[i] - zMin) / (zMax - zMin) :
0.5;
if (sizeByArea && pos >= 0) {
pos = Math.sqrt(pos);
}
radii.push(math.ceil(minSize + pos * (maxSize - minSize)) / 2);
}
this.radii = radii;
},
/**
* Perform animation on the bubbles
*/
animate: function (init) {
var animation = this.options.animation;
if (!init) { // run the animation
each(this.points, function (point) {
var graphic = point.graphic,
shapeArgs = point.shapeArgs;
if (graphic && shapeArgs) {
// start values
graphic.attr('r', 1);
// animate
graphic.animate({
r: shapeArgs.r
}, animation);
}
});
// delete this function to allow it only once
this.animate = null;
}
},
/**
* Extend the base translate method to handle bubble size
*/
translate: function () {
var i,
data = this.data,
point,
radius,
radii = this.radii;
// Run the parent method
seriesTypes.scatter.prototype.translate.call(this);
// Set the shape type and arguments to be picked up in drawPoints
i = data.length;
while (i--) {
point = data[i];
radius = radii ? radii[i] : 0; // #1737
if (radius >= this.minPxSize / 2) {
// Shape arguments
point.shapeType = 'circle';
point.shapeArgs = {
x: point.plotX,
y: point.plotY,
r: radius
};
// Alignment box for the data label
point.dlBox = {
x: point.plotX - radius,
y: point.plotY - radius,
width: 2 * radius,
height: 2 * radius
};
} else { // below zThreshold
point.shapeArgs = point.plotY = point.dlBox = UNDEFINED; // #1691
}
}
},
/**
* Get the series' symbol in the legend
*
* @param {Object} legend The legend object
* @param {Object} item The series (this) or point
*/
drawLegendSymbol: function (legend, item) {
var radius = pInt(legend.itemStyle.fontSize) / 2;
item.legendSymbol = this.chart.renderer.circle(
radius,
legend.baseline - radius,
radius
).attr({
zIndex: 3
}).add(item.legendGroup);
item.legendSymbol.isMarker = true;
},
drawPoints: seriesTypes.column.prototype.drawPoints,
alignDataLabel: seriesTypes.column.prototype.alignDataLabel,
buildKDTree: noop,
applyZones: noop
});
/**
* Add logic to pad each axis with the amount of pixels
* necessary to avoid the bubbles to overflow.
*/
Axis.prototype.beforePadding = function () {
var axis = this,
axisLength = this.len,
chart = this.chart,
pxMin = 0,
pxMax = axisLength,
isXAxis = this.isXAxis,
dataKey = isXAxis ? 'xData' : 'yData',
min = this.min,
extremes = {},
smallestSize = math.min(chart.plotWidth, chart.plotHeight),
zMin = Number.MAX_VALUE,
zMax = -Number.MAX_VALUE,
range = this.max - min,
transA = axisLength / range,
activeSeries = [];
// Handle padding on the second pass, or on redraw
each(this.series, function (series) {
var seriesOptions = series.options,
zData;
if (series.bubblePadding && (series.visible || !chart.options.chart.ignoreHiddenSeries)) {
// Correction for #1673
axis.allowZoomOutside = true;
// Cache it
activeSeries.push(series);
if (isXAxis) { // because X axis is evaluated first
// For each series, translate the size extremes to pixel values
each(['minSize', 'maxSize'], function (prop) {
var length = seriesOptions[prop],
isPercent = /%$/.test(length);
length = pInt(length);
extremes[prop] = isPercent ?
smallestSize * length / 100 :
length;
});
series.minPxSize = extremes.minSize;
// Find the min and max Z
zData = series.zData;
if (zData.length) { // #1735
zMin = pick(seriesOptions.zMin, math.min(
zMin,
math.max(
arrayMin(zData),
seriesOptions.displayNegative === false ? seriesOptions.zThreshold : -Number.MAX_VALUE
)
));
zMax = pick(seriesOptions.zMax, math.max(zMax, arrayMax(zData)));
}
}
}
});
each(activeSeries, function (series) {
var data = series[dataKey],
i = data.length,
radius;
if (isXAxis) {
series.getRadii(zMin, zMax, extremes.minSize, extremes.maxSize);
}
if (range > 0) {
while (i--) {
if (typeof data[i] === 'number') {
radius = series.radii[i];
pxMin = Math.min(((data[i] - min) * transA) - radius, pxMin);
pxMax = Math.max(((data[i] - min) * transA) + radius, pxMax);
}
}
}
});
if (activeSeries.length && range > 0 && pick(this.options.min, this.userMin) === UNDEFINED && pick(this.options.max, this.userMax) === UNDEFINED) {
pxMax -= axisLength;
transA *= (axisLength + pxMin - pxMax) / axisLength;
this.min += pxMin / transA;
this.max += pxMax / transA;
}
};
/* ****************************************************************************
* End Bubble series code *
*****************************************************************************/
// The mapbubble series type
if (seriesTypes.bubble) {
defaultPlotOptions.mapbubble = merge(defaultPlotOptions.bubble, {
animationLimit: 500,
tooltip: {
pointFormat: '{point.name}: {point.z}'
}
});
seriesTypes.mapbubble = extendClass(seriesTypes.bubble, {
pointClass: extendClass(Point, {
applyOptions: function (options, x) {
var point;
if (options.lat !== undefined && options.lon !== undefined) {
point = Point.prototype.applyOptions.call(this, options, x);
point = extend(point, this.series.chart.fromLatLonToPoint(point));
} else {
point = MapAreaPoint.prototype.applyOptions.call(this, options, x);
}
return point;
},
ttBelow: false
}),
xyFromShape: true,
type: 'mapbubble',
pointArrayMap: ['z'], // If one single value is passed, it is interpreted as z
/**
* Return the map area identified by the dataJoinBy option
*/
getMapData: seriesTypes.map.prototype.getMapData,
getBox: seriesTypes.map.prototype.getBox,
setData: seriesTypes.map.prototype.setData
});
}
/**
* Test for point in polygon. Polygon defined as array of [x,y] points.
*/
function pointInPolygon(point, polygon) {
var i, j, rel1, rel2, c = false,
x = point.x,
y = point.y;
for (i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
rel1 = polygon[i][1] > y;
rel2 = polygon[j][1] > y;
if (rel1 !== rel2 && (x < (polygon[j][0] - polygon[i][0]) * (y - polygon[i][1]) / (polygon[j][1] - polygon[i][1]) + polygon[i][0])) {
c = !c;
}
}
return c;
}
/**
* Get point from latLon using specified transform definition
*/
Chart.prototype.transformFromLatLon = function (latLon, transform) {
if (window.proj4 === undefined) {
error(21);
return {
x: 0,
y: null
};
}
var projected = window.proj4(transform.crs, [latLon.lon, latLon.lat]),
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
rotated = transform.rotation ? [projected[0] * cosAngle + projected[1] * sinAngle, -projected[0] * sinAngle + projected[1] * cosAngle] : projected;
return {
x: ((rotated[0] - (transform.xoffset || 0)) * (transform.scale || 1) + (transform.xpan || 0)) * (transform.jsonres || 1) + (transform.jsonmarginX || 0),
y: (((transform.yoffset || 0) - rotated[1]) * (transform.scale || 1) + (transform.ypan || 0)) * (transform.jsonres || 1) - (transform.jsonmarginY || 0)
};
};
/**
* Get latLon from point using specified transform definition
*/
Chart.prototype.transformToLatLon = function (point, transform) {
if (window.proj4 === undefined) {
error(21);
return;
}
var normalized = {
x: ((point.x - (transform.jsonmarginX || 0)) / (transform.jsonres || 1) - (transform.xpan || 0)) / (transform.scale || 1) + (transform.xoffset || 0),
y: ((-point.y - (transform.jsonmarginY || 0)) / (transform.jsonres || 1) + (transform.ypan || 0)) / (transform.scale || 1) + (transform.yoffset || 0)
},
cosAngle = transform.cosAngle || (transform.rotation && Math.cos(transform.rotation)),
sinAngle = transform.sinAngle || (transform.rotation && Math.sin(transform.rotation)),
// Note: Inverted sinAngle to reverse rotation direction
projected = window.proj4(transform.crs, 'WGS84', transform.rotation ? {
x: normalized.x * cosAngle + normalized.y * -sinAngle,
y: normalized.x * sinAngle + normalized.y * cosAngle
} : normalized);
return {lat: projected.y, lon: projected.x};
};
Chart.prototype.fromPointToLatLon = function (point) {
var transforms = this.mapTransforms,
transform;
if (!transforms) {
error(22);
return;
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone && pointInPolygon({x: point.x, y: -point.y}, transforms[transform].hitZone.coordinates[0])) {
return this.transformToLatLon(point, transforms[transform]);
}
}
return this.transformToLatLon(point, transforms['default']);
};
Chart.prototype.fromLatLonToPoint = function (latLon) {
var transforms = this.mapTransforms,
transform,
coords;
if (!transforms) {
error(22);
return {
x: 0,
y: null
};
}
for (transform in transforms) {
if (transforms.hasOwnProperty(transform) && transforms[transform].hitZone) {
coords = this.transformFromLatLon(latLon, transforms[transform]);
if (pointInPolygon({x: coords.x, y: -coords.y}, transforms[transform].hitZone.coordinates[0])) {
return coords;
}
}
}
return this.transformFromLatLon(latLon, transforms['default']);
};
/**
* Convert a geojson object to map data of a given Highcharts type (map, mappoint or mapline).
*/
Highcharts.geojson = function (geojson, hType, series) {
var mapData = [],
path = [],
polygonToPath = function (polygon) {
var i = 0,
len = polygon.length;
path.push('M');
for (; i < len; i++) {
if (i === 1) {
path.push('L');
}
path.push(polygon[i][0], -polygon[i][1]);
}
};
hType = hType || 'map';
each(geojson.features, function (feature) {
var geometry = feature.geometry,
type = geometry.type,
coordinates = geometry.coordinates,
properties = feature.properties,
point;
path = [];
if (hType === 'map' || hType === 'mapbubble') {
if (type === 'Polygon') {
each(coordinates, polygonToPath);
path.push('Z');
} else if (type === 'MultiPolygon') {
each(coordinates, function (items) {
each(items, polygonToPath);
});
path.push('Z');
}
if (path.length) {
point = { path: path };
}
} else if (hType === 'mapline') {
if (type === 'LineString') {
polygonToPath(coordinates);
} else if (type === 'MultiLineString') {
each(coordinates, polygonToPath);
}
if (path.length) {
point = { path: path };
}
} else if (hType === 'mappoint') {
if (type === 'Point') {
point = {
x: coordinates[0],
y: -coordinates[1]
};
}
}
if (point) {
mapData.push(extend(point, {
name: properties.name || properties.NAME,
properties: properties
}));
}
});
// Create a credits text that includes map source, to be picked up in Chart.showCredits
if (series && geojson.copyrightShort) {
series.chart.mapCredits = '<a href="http://www.highcharts.com">Highcharts</a> \u00A9 ' +
'<a href="' + geojson.copyrightUrl + '">' + geojson.copyrightShort + '</a>';
series.chart.mapCreditsFull = geojson.copyright;
}
return mapData;
};
/**
* Override showCredits to include map source by default
*/
wrap(Chart.prototype, 'showCredits', function (proceed, credits) {
if (defaultOptions.credits.text === this.options.credits.text && this.mapCredits) { // default text and mapCredits is set
credits.text = this.mapCredits;
credits.href = null;
}
proceed.call(this, credits);
if (this.credits) {
this.credits.attr({
title: this.mapCreditsFull
});
}
});
// Add language
extend(defaultOptions.lang, {
zoomIn: 'Zoom in',
zoomOut: 'Zoom out'
});
// Set the default map navigation options
defaultOptions.mapNavigation = {
buttonOptions: {
alignTo: 'plotBox',
align: 'left',
verticalAlign: 'top',
x: 0,
width: 18,
height: 18,
style: {
fontSize: '15px',
fontWeight: 'bold',
textAlign: 'center'
},
theme: {
'stroke-width': 1
}
},
buttons: {
zoomIn: {
onclick: function () {
this.mapZoom(0.5);
},
text: '+',
y: 0
},
zoomOut: {
onclick: function () {
this.mapZoom(2);
},
text: '-',
y: 28
}
}
// enabled: false,
// enableButtons: null, // inherit from enabled
// enableTouchZoom: null, // inherit from enabled
// enableDoubleClickZoom: null, // inherit from enabled
// enableDoubleClickZoomTo: false
// enableMouseWheelZoom: null, // inherit from enabled
};
/**
* Utility for reading SVG paths directly.
*/
Highcharts.splitPath = function (path) {
var i;
// Move letters apart
path = path.replace(/([A-Za-z])/g, ' $1 ');
// Trim
path = path.replace(/^\s*/, "").replace(/\s*$/, "");
// Split on spaces and commas
path = path.split(/[ ,]+/);
// Parse numbers
for (i = 0; i < path.length; i++) {
if (!/[a-zA-Z]/.test(path[i])) {
path[i] = parseFloat(path[i]);
}
}
return path;
};
// A placeholder for map definitions
Highcharts.maps = {};
// Create symbols for the zoom buttons
function selectiveRoundedRect(attr, x, y, w, h, rTopLeft, rTopRight, rBottomRight, rBottomLeft) {
var normalize = (attr['stroke-width'] % 2 / 2);
x -= normalize;
y -= normalize;
return ['M', x + rTopLeft, y,
// top side
'L', x + w - rTopRight, y,
// top right corner
'C', x + w - rTopRight / 2, y, x + w, y + rTopRight / 2, x + w, y + rTopRight,
// right side
'L', x + w, y + h - rBottomRight,
// bottom right corner
'C', x + w, y + h - rBottomRight / 2, x + w - rBottomRight / 2, y + h, x + w - rBottomRight, y + h,
// bottom side
'L', x + rBottomLeft, y + h,
// bottom left corner
'C', x + rBottomLeft / 2, y + h, x, y + h - rBottomLeft / 2, x, y + h - rBottomLeft,
// left side
'L', x, y + rTopLeft,
// top left corner
'C', x, y + rTopLeft / 2, x + rTopLeft / 2, y, x + rTopLeft, y,
'Z'
];
}
SVGRenderer.prototype.symbols.topbutton = function (x, y, w, h, attr) {
return selectiveRoundedRect(attr, x, y, w, h, attr.r, attr.r, 0, 0);
};
SVGRenderer.prototype.symbols.bottombutton = function (x, y, w, h, attr) {
return selectiveRoundedRect(attr, x, y, w, h, 0, 0, attr.r, attr.r);
};
// The symbol callbacks are generated on the SVGRenderer object in all browsers. Even
// VML browsers need this in order to generate shapes in export. Now share
// them with the VMLRenderer.
if (Renderer === VMLRenderer) {
each(['topbutton', 'bottombutton'], function (shape) {
VMLRenderer.prototype.symbols[shape] = SVGRenderer.prototype.symbols[shape];
});
}
/**
* A wrapper for Chart with all the default values for a Map
*/
Highcharts.Map = function (options, callback) {
var hiddenAxis = {
endOnTick: false,
gridLineWidth: 0,
lineWidth: 0,
minPadding: 0,
maxPadding: 0,
startOnTick: false,
title: null,
tickPositions: []
},
seriesOptions;
/* For visual testing
hiddenAxis.gridLineWidth = 1;
hiddenAxis.gridZIndex = 10;
hiddenAxis.tickPositions = undefined;
// */
// Don't merge the data
seriesOptions = options.series;
options.series = null;
options = merge({
chart: {
panning: 'xy',
type: 'map'
},
xAxis: hiddenAxis,
yAxis: merge(hiddenAxis, { reversed: true })
},
options, // user's options
{ // forced options
chart: {
inverted: false,
alignTicks: false,
preserveAspectRatio: true
}
});
options.series = seriesOptions;
return new Chart(options, callback);
};
/**
* Extend the default options with map options
*/
defaultOptions.plotOptions.heatmap = merge(defaultOptions.plotOptions.scatter, {
animation: false,
borderWidth: 0,
nullColor: '#F8F8F8',
dataLabels: {
formatter: function () { // #2945
return this.point.value;
},
inside: true,
verticalAlign: 'middle',
crop: false,
overflow: false
},
marker: null,
tooltip: {
pointFormat: '{point.x}, {point.y}: {point.value}<br/>'
},
states: {
normal: {
animation: true
},
hover: {
halo: false, // #3406, halo is not required on heatmaps
brightness: 0.2
}
}
});
// The Heatmap series type
seriesTypes.heatmap = extendClass(seriesTypes.scatter, merge(colorSeriesMixin, {
type: 'heatmap',
pointArrayMap: ['y', 'value'],
hasPointSpecificOptions: true,
supportsDrilldown: true,
getExtremesFromAll: true,
init: function () {
seriesTypes.scatter.prototype.init.apply(this, arguments);
this.pointRange = this.options.colsize || 1;
this.yAxis.axisPointRange = this.options.rowsize || 1; // general point range
},
translate: function () {
var series = this,
options = series.options,
xAxis = series.xAxis,
yAxis = series.yAxis;
series.generatePoints();
each(series.points, function (point) {
var xPad = (options.colsize || 1) / 2,
yPad = (options.rowsize || 1) / 2,
x1 = Math.round(xAxis.len - xAxis.translate(point.x - xPad, 0, 1, 0, 1)),
x2 = Math.round(xAxis.len - xAxis.translate(point.x + xPad, 0, 1, 0, 1)),
y1 = Math.round(yAxis.translate(point.y - yPad, 0, 1, 0, 1)),
y2 = Math.round(yAxis.translate(point.y + yPad, 0, 1, 0, 1));
// Set plotX and plotY for use in K-D-Tree and more
point.plotX = (x1 + x2) / 2;
point.plotY = (y1 + y2) / 2;
point.shapeType = 'rect';
point.shapeArgs = {
x: Math.min(x1, x2),
y: Math.min(y1, y2),
width: Math.abs(x2 - x1),
height: Math.abs(y2 - y1)
};
});
series.translateColors();
// Make sure colors are updated on colorAxis update (#2893)
if (this.chart.hasRendered) {
each(series.points, function (point) {
point.shapeArgs.fill = point.options.color || point.color; // #3311
});
}
},
drawPoints: seriesTypes.column.prototype.drawPoints,
animate: noop,
getBox: noop,
drawLegendSymbol: LegendSymbolMixin.drawRectangle,
getExtremes: function () {
// Get the extremes from the value data
Series.prototype.getExtremes.call(this, this.valueData);
this.valueMin = this.dataMin;
this.valueMax = this.dataMax;
// Get the extremes from the y data
Series.prototype.getExtremes.call(this);
}
}));
/**
* TrackerMixin for points and graphs
*/
var TrackerMixin = Highcharts.TrackerMixin = {
drawTrackerPoint: function () {
var series = this,
chart = series.chart,
pointer = chart.pointer,
cursor = series.options.cursor,
css = cursor && { cursor: cursor },
onMouseOver = function (e) {
var target = e.target,
point;
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
while (target && !point) {
point = target.point;
target = target.parentNode;
}
if (point !== UNDEFINED && point !== chart.hoverPoint) { // undefined on graph in scatterchart
point.onMouseOver(e);
}
};
// Add reference to the point
each(series.points, function (point) {
if (point.graphic) {
point.graphic.element.point = point;
}
if (point.dataLabel) {
point.dataLabel.element.point = point;
}
});
// Add the event listeners, we need to do this only once
if (!series._hasTracking) {
each(series.trackerGroups, function (key) {
if (series[key]) { // we don't always have dataLabelsGroup
series[key]
.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
series[key].on('touchstart', onMouseOver);
}
}
});
series._hasTracking = true;
}
},
/**
* Draw the tracker object that sits above all data labels and markers to
* track mouse events on the graph or points. For the line type charts
* the tracker uses the same graphPath, but with a greater stroke width
* for better control.
*/
drawTrackerGraph: function () {
var series = this,
options = series.options,
trackByArea = options.trackByArea,
trackerPath = [].concat(trackByArea ? series.areaPath : series.graphPath),
trackerPathLength = trackerPath.length,
chart = series.chart,
pointer = chart.pointer,
renderer = chart.renderer,
snap = chart.options.tooltip.snap,
tracker = series.tracker,
cursor = options.cursor,
css = cursor && { cursor: cursor },
singlePoints = series.singlePoints,
singlePoint,
i,
onMouseOver = function () {
if (chart.hoverSeries !== series) {
series.onMouseOver();
}
},
/*
* Empirical lowest possible opacities for TRACKER_FILL for an element to stay invisible but clickable
* IE6: 0.002
* IE7: 0.002
* IE8: 0.002
* IE9: 0.00000000001 (unlimited)
* IE10: 0.0001 (exporting only)
* FF: 0.00000000001 (unlimited)
* Chrome: 0.000001
* Safari: 0.000001
* Opera: 0.00000000001 (unlimited)
*/
TRACKER_FILL = 'rgba(192,192,192,' + (hasSVG ? 0.0001 : 0.002) + ')';
// Extend end points. A better way would be to use round linecaps,
// but those are not clickable in VML.
if (trackerPathLength && !trackByArea) {
i = trackerPathLength + 1;
while (i--) {
if (trackerPath[i] === M) { // extend left side
trackerPath.splice(i + 1, 0, trackerPath[i + 1] - snap, trackerPath[i + 2], L);
}
if ((i && trackerPath[i] === M) || i === trackerPathLength) { // extend right side
trackerPath.splice(i, 0, L, trackerPath[i - 2] + snap, trackerPath[i - 1]);
}
}
}
// handle single points
for (i = 0; i < singlePoints.length; i++) {
singlePoint = singlePoints[i];
trackerPath.push(M, singlePoint.plotX - snap, singlePoint.plotY,
L, singlePoint.plotX + snap, singlePoint.plotY);
}
// draw the tracker
if (tracker) {
tracker.attr({ d: trackerPath });
} else { // create
series.tracker = renderer.path(trackerPath)
.attr({
'stroke-linejoin': 'round', // #1225
visibility: series.visible ? VISIBLE : HIDDEN,
stroke: TRACKER_FILL,
fill: trackByArea ? TRACKER_FILL : NONE,
'stroke-width' : options.lineWidth + (trackByArea ? 0 : 2 * snap),
zIndex: 2
})
.add(series.group);
// The tracker is added to the series group, which is clipped, but is covered
// by the marker group. So the marker group also needs to capture events.
each([series.tracker, series.markerGroup], function (tracker) {
tracker.addClass(PREFIX + 'tracker')
.on('mouseover', onMouseOver)
.on('mouseout', function (e) { pointer.onTrackerMouseOut(e); })
.css(css);
if (hasTouch) {
tracker.on('touchstart', onMouseOver);
}
});
}
}
};
/* End TrackerMixin */
/**
* Add tracking event listener to the series group, so the point graphics
* themselves act as trackers
*/
if (seriesTypes.column) {
ColumnSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.pie) {
seriesTypes.pie.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
if (seriesTypes.scatter) {
ScatterSeries.prototype.drawTracker = TrackerMixin.drawTrackerPoint;
}
/*
* Extend Legend for item events
*/
extend(Legend.prototype, {
setItemEvents: function (item, legendItem, useHTML, itemStyle, itemHiddenStyle) {
var legend = this;
// Set the events on the item group, or in case of useHTML, the item itself (#1249)
(useHTML ? legendItem : item.legendGroup).on('mouseover', function () {
item.setState(HOVER_STATE);
legendItem.css(legend.options.itemHoverStyle);
})
.on('mouseout', function () {
legendItem.css(item.visible ? itemStyle : itemHiddenStyle);
item.setState();
})
.on('click', function (event) {
var strLegendItemClick = 'legendItemClick',
fnLegendItemClick = function () {
item.setVisible();
};
// Pass over the click/touch event. #4.
event = {
browserEvent: event
};
// click the name or symbol
if (item.firePointEvent) { // point
item.firePointEvent(strLegendItemClick, event, fnLegendItemClick);
} else {
fireEvent(item, strLegendItemClick, event, fnLegendItemClick);
}
});
},
createCheckboxForItem: function (item) {
var legend = this;
item.checkbox = createElement('input', {
type: 'checkbox',
checked: item.selected,
defaultChecked: item.selected // required by IE7
}, legend.options.itemCheckboxStyle, legend.chart.container);
addEvent(item.checkbox, 'click', function (event) {
var target = event.target;
fireEvent(item.series || item, 'checkboxClick', { // #3712
checked: target.checked,
item: item
},
function () {
item.select();
}
);
});
}
});
/*
* Add pointer cursor to legend itemstyle in defaultOptions
*/
defaultOptions.legend.itemStyle.cursor = 'pointer';
/*
* Extend the Chart object with interaction
*/
extend(Chart.prototype, {
/**
* Display the zoom button
*/
showResetZoom: function () {
var chart = this,
lang = defaultOptions.lang,
btnOptions = chart.options.chart.resetZoomButton,
theme = btnOptions.theme,
states = theme.states,
alignTo = btnOptions.relativeTo === 'chart' ? null : 'plotBox';
this.resetZoomButton = chart.renderer.button(lang.resetZoom, null, null, function () { chart.zoomOut(); }, theme, states && states.hover)
.attr({
align: btnOptions.position.align,
title: lang.resetZoomTitle
})
.add()
.align(btnOptions.position, false, alignTo);
},
/**
* Zoom out to 1:1
*/
zoomOut: function () {
var chart = this;
fireEvent(chart, 'selection', { resetSelection: true }, function () {
chart.zoom();
});
},
/**
* Zoom into a given portion of the chart given by axis coordinates
* @param {Object} event
*/
zoom: function (event) {
var chart = this,
hasZoomed,
pointer = chart.pointer,
displayButton = false,
resetZoomButton;
// If zoom is called with no arguments, reset the axes
if (!event || event.resetSelection) {
each(chart.axes, function (axis) {
hasZoomed = axis.zoom();
});
} else { // else, zoom in on all axes
each(event.xAxis.concat(event.yAxis), function (axisData) {
var axis = axisData.axis,
isXAxis = axis.isXAxis;
// don't zoom more than minRange
if (pointer[isXAxis ? 'zoomX' : 'zoomY'] || pointer[isXAxis ? 'pinchX' : 'pinchY']) {
hasZoomed = axis.zoom(axisData.min, axisData.max);
if (axis.displayBtn) {
displayButton = true;
}
}
});
}
// Show or hide the Reset zoom button
resetZoomButton = chart.resetZoomButton;
if (displayButton && !resetZoomButton) {
chart.showResetZoom();
} else if (!displayButton && isObject(resetZoomButton)) {
chart.resetZoomButton = resetZoomButton.destroy();
}
// Redraw
if (hasZoomed) {
chart.redraw(
pick(chart.options.chart.animation, event && event.animation, chart.pointCount < 100) // animation
);
}
},
/**
* Pan the chart by dragging the mouse across the pane. This function is called
* on mouse move, and the distance to pan is computed from chartX compared to
* the first chartX position in the dragging operation.
*/
pan: function (e, panning) {
var chart = this,
hoverPoints = chart.hoverPoints,
doRedraw;
// remove active points for shared tooltip
if (hoverPoints) {
each(hoverPoints, function (point) {
point.setState();
});
}
each(panning === 'xy' ? [1, 0] : [1], function (isX) { // xy is used in maps
var mousePos = e[isX ? 'chartX' : 'chartY'],
axis = chart[isX ? 'xAxis' : 'yAxis'][0],
startPos = chart[isX ? 'mouseDownX' : 'mouseDownY'],
halfPointRange = (axis.pointRange || 0) / 2,
extremes = axis.getExtremes(),
newMin = axis.toValue(startPos - mousePos, true) + halfPointRange,
newMax = axis.toValue(startPos + chart[isX ? 'plotWidth' : 'plotHeight'] - mousePos, true) - halfPointRange,
goingLeft = startPos > mousePos; // #3613
if (axis.series.length &&
(goingLeft || newMin > mathMin(extremes.dataMin, extremes.min)) &&
(!goingLeft || newMax < mathMax(extremes.dataMax, extremes.max))) {
axis.setExtremes(newMin, newMax, false, false, { trigger: 'pan' });
doRedraw = true;
}
chart[isX ? 'mouseDownX' : 'mouseDownY'] = mousePos; // set new reference for next run
});
if (doRedraw) {
chart.redraw(false);
}
css(chart.container, { cursor: 'move' });
}
});
/*
* Extend the Point object with interaction
*/
extend(Point.prototype, {
/**
* Toggle the selection status of a point
* @param {Boolean} selected Whether to select or unselect the point.
* @param {Boolean} accumulate Whether to add to the previous selection. By default,
* this happens if the control key (Cmd on Mac) was pressed during clicking.
*/
select: function (selected, accumulate) {
var point = this,
series = point.series,
chart = series.chart;
selected = pick(selected, !point.selected);
// fire the event with the defalut handler
point.firePointEvent(selected ? 'select' : 'unselect', { accumulate: accumulate }, function () {
point.selected = point.options.selected = selected;
series.options.data[inArray(point, series.data)] = point.options;
point.setState(selected && SELECT_STATE);
// unselect all other points unless Ctrl or Cmd + click
if (!accumulate) {
each(chart.getSelectedPoints(), function (loopPoint) {
if (loopPoint.selected && loopPoint !== point) {
loopPoint.selected = loopPoint.options.selected = false;
series.options.data[inArray(loopPoint, series.data)] = loopPoint.options;
loopPoint.setState(NORMAL_STATE);
loopPoint.firePointEvent('unselect');
}
});
}
});
},
/**
* Runs on mouse over the point
*/
onMouseOver: function (e) {
var point = this,
series = point.series,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// set normal state to previous series
if (hoverPoint && hoverPoint !== point) {
hoverPoint.onMouseOut();
}
// trigger the event
point.firePointEvent('mouseOver');
// update the tooltip
if (tooltip && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.refresh(point, e);
}
// hover this
point.setState(HOVER_STATE);
chart.hoverPoint = point;
},
/**
* Runs on mouse out from the point
*/
onMouseOut: function () {
var chart = this.series.chart,
hoverPoints = chart.hoverPoints;
this.firePointEvent('mouseOut');
if (!hoverPoints || inArray(this, hoverPoints) === -1) { // #887, #2240
this.setState();
chart.hoverPoint = null;
}
},
/**
* Import events from the series' and point's options. Only do it on
* demand, to save processing time on hovering.
*/
importEvents: function () {
if (!this.hasImportedEvents) {
var point = this,
options = merge(point.series.options.point, point.options),
events = options.events,
eventType;
point.events = events;
for (eventType in events) {
addEvent(point, eventType, events[eventType]);
}
this.hasImportedEvents = true;
}
},
/**
* Set the point's state
* @param {String} state
*/
setState: function (state, move) {
var point = this,
plotX = point.plotX,
plotY = point.plotY,
series = point.series,
stateOptions = series.options.states,
markerOptions = defaultPlotOptions[series.type].marker && series.options.marker,
normalDisabled = markerOptions && !markerOptions.enabled,
markerStateOptions = markerOptions && markerOptions.states[state],
stateDisabled = markerStateOptions && markerStateOptions.enabled === false,
stateMarkerGraphic = series.stateMarkerGraphic,
pointMarker = point.marker || {},
chart = series.chart,
radius,
halo = series.halo,
haloOptions,
newSymbol,
pointAttr;
state = state || NORMAL_STATE; // empty string
pointAttr = point.pointAttr[state] || series.pointAttr[state];
if (
// already has this state
(state === point.state && !move) ||
// selected points don't respond to hover
(point.selected && state !== SELECT_STATE) ||
// series' state options is disabled
(stateOptions[state] && stateOptions[state].enabled === false) ||
// general point marker's state options is disabled
(state && (stateDisabled || (normalDisabled && markerStateOptions.enabled === false))) ||
// individual point marker's state options is disabled
(state && pointMarker.states && pointMarker.states[state] && pointMarker.states[state].enabled === false) // #1610
) {
return;
}
// apply hover styles to the existing point
if (point.graphic) {
radius = markerOptions && point.graphic.symbolName && pointAttr.r;
point.graphic.attr(merge(
pointAttr,
radius ? { // new symbol attributes (#507, #612)
x: plotX - radius,
y: plotY - radius,
width: 2 * radius,
height: 2 * radius
} : {}
));
// Zooming in from a range with no markers to a range with markers
if (stateMarkerGraphic) {
stateMarkerGraphic.hide();
}
} else {
// if a graphic is not applied to each point in the normal state, create a shared
// graphic for the hover state
if (state && markerStateOptions) {
radius = markerStateOptions.radius;
newSymbol = pointMarker.symbol || series.symbol;
// If the point has another symbol than the previous one, throw away the
// state marker graphic and force a new one (#1459)
if (stateMarkerGraphic && stateMarkerGraphic.currentSymbol !== newSymbol) {
stateMarkerGraphic = stateMarkerGraphic.destroy();
}
// Add a new state marker graphic
if (!stateMarkerGraphic) {
if (newSymbol) {
series.stateMarkerGraphic = stateMarkerGraphic = chart.renderer.symbol(
newSymbol,
plotX - radius,
plotY - radius,
2 * radius,
2 * radius
)
.attr(pointAttr)
.add(series.markerGroup);
stateMarkerGraphic.currentSymbol = newSymbol;
}
// Move the existing graphic
} else {
stateMarkerGraphic[move ? 'animate' : 'attr']({ // #1054
x: plotX - radius,
y: plotY - radius
});
}
}
if (stateMarkerGraphic) {
stateMarkerGraphic[state && chart.isInsidePlot(plotX, plotY, chart.inverted) ? 'show' : 'hide'](); // #2450
}
}
// Show me your halo
haloOptions = stateOptions[state] && stateOptions[state].halo;
if (haloOptions && haloOptions.size) {
if (!halo) {
series.halo = halo = chart.renderer.path()
.add(chart.seriesGroup);
}
halo.attr(extend({
fill: Color(point.color || series.color).setOpacity(haloOptions.opacity).get()
}, haloOptions.attributes))[move ? 'animate' : 'attr']({
d: point.haloPath(haloOptions.size)
});
} else if (halo) {
halo.attr({ d: [] });
}
point.state = state;
},
haloPath: function (size) {
var series = this.series,
chart = series.chart,
plotBox = series.getPlotBox(),
inverted = chart.inverted;
return chart.renderer.symbols.circle(
plotBox.translateX + (inverted ? series.yAxis.len - this.plotY : this.plotX) - size,
plotBox.translateY + (inverted ? series.xAxis.len - this.plotX : this.plotY) - size,
size * 2,
size * 2
);
}
});
/*
* Extend the Series object with interaction
*/
extend(Series.prototype, {
/**
* Series mouse over handler
*/
onMouseOver: function () {
var series = this,
chart = series.chart,
hoverSeries = chart.hoverSeries;
// set normal state to previous series
if (hoverSeries && hoverSeries !== series) {
hoverSeries.onMouseOut();
}
// trigger the event, but to save processing time,
// only if defined
if (series.options.events.mouseOver) {
fireEvent(series, 'mouseOver');
}
// hover this
series.setState(HOVER_STATE);
chart.hoverSeries = series;
},
/**
* Series mouse out handler
*/
onMouseOut: function () {
// trigger the event only if listeners exist
var series = this,
options = series.options,
chart = series.chart,
tooltip = chart.tooltip,
hoverPoint = chart.hoverPoint;
// trigger mouse out on the point, which must be in this series
if (hoverPoint) {
hoverPoint.onMouseOut();
}
// fire the mouse out event
if (series && options.events.mouseOut) {
fireEvent(series, 'mouseOut');
}
// hide the tooltip
if (tooltip && !options.stickyTracking && (!tooltip.shared || series.noSharedTooltip)) {
tooltip.hide();
}
// set normal state
series.setState();
chart.hoverSeries = null;
},
/**
* Set the state of the graph
*/
setState: function (state) {
var series = this,
options = series.options,
graph = series.graph,
graphNeg = series.graphNeg,
stateOptions = options.states,
lineWidth = options.lineWidth,
attribs;
state = state || NORMAL_STATE;
if (series.state !== state) {
series.state = state;
if (stateOptions[state] && stateOptions[state].enabled === false) {
return;
}
if (state) {
lineWidth = (stateOptions[state].lineWidth || lineWidth) + (stateOptions[state].lineWidthPlus || 0);
}
if (graph && !graph.dashstyle) { // hover is turned off for dashed lines in VML
attribs = {
'stroke-width': lineWidth
};
// use attr because animate will cause any other animation on the graph to stop
graph.attr(attribs);
if (graphNeg) {
graphNeg.attr(attribs);
}
}
}
},
/**
* Set the visibility of the graph
*
* @param vis {Boolean} True to show the series, false to hide. If UNDEFINED,
* the visibility is toggled.
*/
setVisible: function (vis, redraw) {
var series = this,
chart = series.chart,
legendItem = series.legendItem,
showOrHide,
ignoreHiddenSeries = chart.options.chart.ignoreHiddenSeries,
oldVisibility = series.visible;
// if called without an argument, toggle visibility
series.visible = vis = series.userOptions.visible = vis === UNDEFINED ? !oldVisibility : vis;
showOrHide = vis ? 'show' : 'hide';
// show or hide elements
each(['group', 'dataLabelsGroup', 'markerGroup', 'tracker'], function (key) {
if (series[key]) {
series[key][showOrHide]();
}
});
// hide tooltip (#1361)
if (chart.hoverSeries === series) {
series.onMouseOut();
}
if (legendItem) {
chart.legend.colorizeItem(series, vis);
}
// rescale or adapt to resized chart
series.isDirty = true;
// in a stack, all other series are affected
if (series.options.stacking) {
each(chart.series, function (otherSeries) {
if (otherSeries.options.stacking && otherSeries.visible) {
otherSeries.isDirty = true;
}
});
}
// show or hide linked series
each(series.linkedSeries, function (otherSeries) {
otherSeries.setVisible(vis, false);
});
if (ignoreHiddenSeries) {
chart.isDirtyBox = true;
}
if (redraw !== false) {
chart.redraw();
}
fireEvent(series, showOrHide);
},
/**
* Show the graph
*/
show: function () {
this.setVisible(true);
},
/**
* Hide the graph
*/
hide: function () {
this.setVisible(false);
},
/**
* Set the selected state of the graph
*
* @param selected {Boolean} True to select the series, false to unselect. If
* UNDEFINED, the selection state is toggled.
*/
select: function (selected) {
var series = this;
// if called without an argument, toggle
series.selected = selected = (selected === UNDEFINED) ? !series.selected : selected;
if (series.checkbox) {
series.checkbox.checked = selected;
}
fireEvent(series, selected ? 'select' : 'unselect');
},
drawTracker: TrackerMixin.drawTrackerGraph
});
// global variables
extend(Highcharts, {
// Constructors
Color: Color,
Point: Point,
Tick: Tick,
Renderer: Renderer,
SVGElement: SVGElement,
SVGRenderer: SVGRenderer,
// Various
arrayMin: arrayMin,
arrayMax: arrayMax,
charts: charts,
dateFormat: dateFormat,
error: error,
format: format,
pathAnim: pathAnim,
getOptions: getOptions,
hasBidiBug: hasBidiBug,
isTouchDevice: isTouchDevice,
setOptions: setOptions,
addEvent: addEvent,
removeEvent: removeEvent,
createElement: createElement,
discardElement: discardElement,
css: css,
each: each,
map: map,
merge: merge,
splat: splat,
extendClass: extendClass,
pInt: pInt,
svg: hasSVG,
canvas: useCanVG,
vml: !hasSVG && !useCanVG,
product: PRODUCT,
version: VERSION
});
}());
|
docs/bootstrap/docs/assets/js/jquery.js
|
kaltura/mwEmbed
|
/*! jQuery v1.7.1 jquery.com | jquery.org/license */
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.1",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
// A crude way of determining if an object is a window
isWindow: function( obj ) {
return obj && typeof obj === "object" && "setInterval" in obj;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
jQuery.access( elems, k, key[k], exec, fn, value );
}
return elems;
}
// Setting one attribute
if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = !pass && exec && jQuery.isFunction(value);
for ( var i = 0; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
return elems;
}
// Getting an attribute
return length ? fn( elems[0], key ) : undefined;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!memory;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
marginDiv,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
div.innerHTML = "";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for( i in {
submit: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = marginDiv = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
conMarginTop, ptlm, vb, style, html,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
ptlm = "position:absolute;top:0;left:0;width:1px;height:1px;margin:0;";
vb = "visibility:hidden;border:0;";
style = "style='" + ptlm + "border:5px solid #000;padding:0;'";
html = "<div " + style + "><div></div></div>" +
"<table " + style + " cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = vb + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Figure out if the W3C box model works as expected
div.innerHTML = "";
div.style.width = div.style.paddingLeft = "1px";
jQuery.boxModel = support.boxModel = div.offsetWidth === 2;
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 2 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "";
div.innerHTML = "<div style='width:4px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 2 );
}
div.style.cssText = ptlm + vb;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
body.removeChild( container );
div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, attr, name,
data = null;
if ( typeof key === "undefined" ) {
if ( this.length ) {
data = jQuery.data( this[0] );
if ( this[0].nodeType === 1 && !jQuery._data( this[0], "parsedAttrs" ) ) {
attr = this[0].attributes;
for ( var i = 0, l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( this[0], name, data[ name ] );
}
}
jQuery._data( this[0], "parsedAttrs", true );
}
}
return data;
} else if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split(".");
parts[1] = parts[1] ? "." + parts[1] : "";
if ( value === undefined ) {
data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
// Try to fetch any internally stored data first
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
data = dataAttr( this[0], key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.each(function() {
var self = jQuery( this ),
args = [ parts[0], value ];
self.triggerHandler( "setData" + parts[1] + "!", args );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + parts[1] + "!", args );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? parseFloat( data ) :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise();
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.attr );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, name, value, true, jQuery.prop );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.nodeName.toLowerCase() ] || jQuery.valHooks[ elem.type ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.nodeName.toLowerCase() ] || jQuery.valHooks[ this.type ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
// See #9699 for explanation of this approach (setting first, then removal)
jQuery.attr( elem, name, "" );
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( rboolean.test( name ) && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
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( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /\bhover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Determine handlers that should run if there are delegated events
// Avoid disabled elements in IE (#6911) and non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !event.target.disabled && !(event.button && event.type === "click") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
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( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on.call( this, types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace? handleObj.type + "." + handleObj.namespace : handleObj.type,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.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( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
var cur = a.nextSibling;
}
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.POS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
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, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery( this );
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, "<$1></$2>");
try {
for ( var i = 0, l = this.length; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
if ( this[i].nodeType === 1 ) {
jQuery.cleanData( this[i].getElementsByTagName("*") );
this[i].innerHTML = value;
}
}
// If using innerHTML throws an exception, use the fallback method
} catch(e) {
this.empty().append( value );
}
} else if ( jQuery.isFunction( value ) ) {
this.each(function(i){
var self = jQuery( this );
self.html( value.call(this, i, self.html()) );
});
} else {
this.empty().append( value );
}
return this;
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type + ( events[ type ][ i ].namespace ? "." : "" ) + events[ type ][ i ].namespace, events[ type ][ i ], events[ type ][ i ].data );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || !rnoshimcache.test( "<" + elem.nodeName ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType;
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [], j;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div");
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
var jsTags = jQuery.grep( ret[i].getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
function evalScript( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnumpx = /^-?\d+(?:px)?$/i,
rnum = /^-?\d/,
rrelNum = /^([\-+])=([\-+.\de]+)/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssWidth = [ "Left", "Right" ],
cssHeight = [ "Top", "Bottom" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
// Setting 'undefined' is a no-op
if ( arguments.length === 2 && value === undefined ) {
return this;
}
return jQuery.access( this, name, value, true, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
});
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity", "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {};
// Remember the old values, and insert the new ones
for ( var name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
}
});
// DEPRECATED, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
jQuery.each(["height", "width"], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
var val;
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWH( elem, name, extra );
} else {
jQuery.swap( elem, cssShow, function() {
val = getWH( elem, name, extra );
});
}
return val;
}
},
set: function( elem, value ) {
if ( rnumpx.test( value ) ) {
// ignore negative width and height values #1599
value = parseFloat( value );
if ( value >= 0 ) {
return value + "px";
}
} else {
return value;
}
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
var ret;
jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
ret = curCSS( elem, "margin-right", "marginRight" );
} else {
ret = elem.style.marginRight;
}
});
return ret;
}
};
}
});
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret === null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( !rnumpx.test( ret ) && rnum.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ( ret || 0 );
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWH( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
which = name === "width" ? cssWidth : cssHeight,
i = 0,
len = which.length;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i++ ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i++ ) {
val += parseFloat( jQuery.css( elem, "padding" + which[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + which[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + which[ i ] ) ) || 0;
}
}
}
return val + "px";
}
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefiler, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" || jQuery.isArray(v) ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = s.contentType === "application/x-www-form-urlencoded" &&
( typeof s.data === "string" );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
responses.text = xhr.responseText;
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( display === "" && jQuery.css(elem, "display") === "none" ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
for ( p in prop ) {
// property name normalization
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p, n, firstNum, diff ) {
return firstNum + diff * p;
},
swing: function( p, n, firstNum, diff ) {
return ( ( -Math.cos( p*Math.PI ) / 2 ) + 0.5 ) * diff + firstNum;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( self.options.hide && jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Adds width/height step functions
// Do not set anything below 0
jQuery.each([ "width", "height" ], function( i, prop ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( document.compatMode === "CSS1Compat" ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0], box;
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
try {
box = elem.getBoundingClientRect();
} catch(e) {}
var doc = elem.ownerDocument,
docElem = doc.documentElement;
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow(doc),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
doc = elem.ownerDocument,
docElem = doc.documentElement,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( ["Left", "Top"], function( i, name ) {
var method = "scroll" + name;
jQuery.fn[ method ] = function( val ) {
var elem, win;
if ( val === undefined ) {
elem = this[ 0 ];
if ( !elem ) {
return null;
}
win = getWindow( elem );
// Return the scroll offset
return win ? ("pageXOffset" in win) ? win[ i ? "pageYOffset" : "pageXOffset" ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
// Set the scroll offset
return this.each(function() {
win = getWindow( this );
if ( win ) {
win.scrollTo(
!i ? val : jQuery( win ).scrollLeft(),
i ? val : jQuery( win ).scrollTop()
);
} else {
this[ method ] = val;
}
});
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each([ "Height", "Width" ], function( i, name ) {
var type = name.toLowerCase();
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( size ) {
// Get window width or height
var elem = this[0];
if ( !elem ) {
return size == null ? null : this;
}
if ( jQuery.isFunction( size ) ) {
return this.each(function( i ) {
var self = jQuery( this );
self[ type ]( size.call( this, i, self[ type ]() ) );
});
}
if ( jQuery.isWindow( elem ) ) {
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
var docElemProp = elem.document.documentElement[ "client" + name ],
body = elem.document.body;
return elem.document.compatMode === "CSS1Compat" && docElemProp ||
body && body[ "client" + name ] || docElemProp;
// Get document width or height
} else if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
return Math.max(
elem.documentElement["client" + name],
elem.body["scroll" + name], elem.documentElement["scroll" + name],
elem.body["offset" + name], elem.documentElement["offset" + name]
);
// Get or set width or height on the element
} else if ( size === undefined ) {
var orig = jQuery.css( elem, type ),
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
// Set the width or height on the element (default to pixels if value is unitless)
} else {
return this.css( type, typeof size === "string" ? size : size + "px" );
}
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
|
docs/app/Examples/modules/Dropdown/Types/DropdownExampleMultipleSearchInMenu.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Dropdown, Input } from 'semantic-ui-react'
import { tagOptions } from '../common'
// tagOptions = [
// {
// text: 'Important',
// value: 'Important',
// label: { color: 'red', empty: true, circular: true },
// },
// ...
// ]
const DropdownExampleMultipleSearchInMenu = () => (
<Dropdown text='Filter Posts' multiple icon='filter'>
<Dropdown.Menu>
<Input icon='search' iconPosition='left' className='search' />
<Dropdown.Divider />
<Dropdown.Header icon='tags' content='Tag Label' />
<Dropdown.Menu scrolling>
{tagOptions.map((option) => <Dropdown.Item key={option.value} {...option} />)}
</Dropdown.Menu>
</Dropdown.Menu>
</Dropdown>
)
export default DropdownExampleMultipleSearchInMenu
|
src/svg-icons/action/dns.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDns = (props) => (
<SvgIcon {...props}>
<path d="M20 13H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1v-6c0-.55-.45-1-1-1zM7 19c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM20 3H4c-.55 0-1 .45-1 1v6c0 .55.45 1 1 1h16c.55 0 1-.45 1-1V4c0-.55-.45-1-1-1zM7 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
ActionDns = pure(ActionDns);
ActionDns.displayName = 'ActionDns';
ActionDns.muiName = 'SvgIcon';
export default ActionDns;
|
src/js/pages/register.js
|
daniel-madera/pijs
|
import React from 'react'
import { inject, observer } from 'mobx-react'
import { Grid, Row, Form, FormGroup, FormLabel, FormControl, ControlLabel, Button, Col, Glyphicon } from 'react-bootstrap'
import UsernameInput from '../components/register/username-input'
import PasswordInputs from '../components/register/password-inputs'
import SimpleInput from '../components/register/simple-text-input'
@inject('userStore', 'appStore', 'routerStore')
@observer
export default class Register extends React.Component {
constructor(props) {
super(props)
}
componentDidMount() {
const { userStore } = this.props
userStore.logout()
}
isFormValid() {
console.log(this.usernameInput.dataset.validation, this.passwordInput.dataset.validation, this.firstNameInput.dataset.validation, this.lastNameInput.dataset.validation)
if (this.usernameInput.dataset.validation !== 'true')
return false
if (this.passwordInput.dataset.validation !== 'true')
return false
if (this.firstNameInput.dataset.validation !== 'true')
return false
if (this.lastNameInput.dataset.validation !== 'true')
return false
return true
}
submit = e => {
const { appStore, userStore } = this.props
const { push } = this.props.routerStore
if (!this.isFormValid()) {
appStore.addMessage('danger',
"Formulář není validní. Prosím opravte zvýrazněné položky.")
return
}
let data = {
username: this.usernameInput.value,
password: this.passwordInput.value,
first_name: this.firstNameInput.value,
last_name: this.lastNameInput.value,
}
let success = () => {
push('/auth')
appStore.addMessage('success', "Uživatel byl úspěšně registrován. Nyní se můžete přihlásit.")
}
let failure = () => {
appStore.addMessage('danger', "Registrace selhala. Zkuste zvolit jiné uživatelské jméno.")
}
userStore.register(data, success, failure)
}
render() {
let validate = function(text) {
const re = /^[a-zA-Z\u00C0-\u017F]+$/
return re.test(text)
}
return <Grid fluid>
<Row>
<Col xs={3} md={3} />
<Col xs={12} md={6}>
<Form className="tiny">
<UsernameInput inputRef={ref => this.usernameInput = ref} />
<PasswordInputs inputRef={ref => this.passwordInput = ref} />
<SimpleInput inputRef={ref => this.firstNameInput = ref} validate={validate} label="Jméno" />
<SimpleInput inputRef={ref => this.lastNameInput = ref} validate={validate} label="Příjmení" />
<Button onClick={this.submit}>Odeslat</Button>
</Form>
</Col>
<Col xs={3} md={3} />
</Row>
</Grid>
}
}
|
rojak-ui-web/src/app/media/Media.js
|
rawgni/rojak
|
import React from 'react'
import { connect } from 'react-redux'
import { fetchMedia } from './actions'
import Card from '../kit/Card'
import SocialMedia from '../kit/SocialMedia'
import PairingSentiments from './PairingSentiments'
import LatestNews from './LatestNews'
class Media extends React.Component {
static propTypes = {
id: React.PropTypes.number.isRequired,
media: React.PropTypes.object.isRequired,
fetchMedia: React.PropTypes.func.isRequired
}
componentWillMount () {
const { id, fetchMedia } = this.props
fetchMedia(id)
}
componentWillReceiveProps (nextProps) {
const { id, fetchMedia } = nextProps
if (this.props.id !== id) {
fetchMedia(id)
}
}
render () {
const { media } = this.props
return (
<div>
<div>
<img alt={media.name} src={media.logo_url} style={{ maxWidth: '200px', marginBottom: '15px' }} />
<SocialMedia
instagram={media.instagram_username}
twitter={media.twitter_username}
facebook={media.fbpage_username}
style={{ float: 'right' }} />
</div>
<Card style={{ margin: '10px auto' }}>
<PairingSentiments sentiments={media.sentiments_on_pairings} />
</Card>
<Card style={{ margin: '10px auto' }}>
<LatestNews news={media.latest_news} />
</Card>
<br />
</div>
)
}
}
const mapStateProps = (state) => ({
media: state.medias.media
})
export default connect(mapStateProps, { fetchMedia })(Media)
|
ajax/libs/yui/3.14.0/datatable-body/datatable-body-debug.js
|
seogi1004/cdnjs
|
YUI.add('datatable-body', function (Y, NAME) {
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
@module datatable
@submodule datatable-body
@since 3.5.0
**/
var Lang = Y.Lang,
isArray = Lang.isArray,
isNumber = Lang.isNumber,
isString = Lang.isString,
fromTemplate = Lang.sub,
htmlEscape = Y.Escape.html,
toArray = Y.Array,
bind = Y.bind,
YObject = Y.Object,
valueRegExp = /\{value\}/g,
EV_CONTENT_UPDATE = 'contentUpdate';
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
Translates the provided `modelList` into a rendered `<tbody>` based on the data
in the constituent Models, altered or amended by any special column
configurations.
The `columns` configuration, passed to the constructor, determines which
columns will be rendered.
The rendering process involves constructing an HTML template for a complete row
of data, built by concatenating a customized copy of the instance's
`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is
then populated with values from each Model in the `modelList`, aggregating a
complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this
column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform any
custom modifications on the cell or row Node that could not be performed by
`formatter`s. Should be used sparingly for better performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a column.
A column `formatter` can be:
* a function, as described below.
* a string which can be:
* the name of a pre-defined formatter function
which can be located in the `Y.DataTable.BodyView.Formatters` hash using the
value of the `formatter` property as the index.
* A template that can use the `{value}` placeholder to include the value
for the current cell or the name of any field in the underlaying model
also enclosed in curly braces. Any number and type of these placeholders
can be used.
Column `formatter`s are passed an object (`o`) with the following properties:
* `value` - The current value of the column's associated attribute, if any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML content. A
returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`.
When adding content to the cell, prefer appending into this property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as
it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The DOM
elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@class BodyView
@namespace DataTable
@extends View
@since 3.5.0
**/
Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {
// -- Instance properties -------------------------------------------------
/**
HTML template used to create table cells.
@property CELL_TEMPLATE
@type {HTML}
@default '<td {headers} class="{className}">{content}</td>'
@since 3.5.0
**/
CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>',
/**
CSS class applied to even rows. This is assigned at instantiation.
For DataTable, this will be `yui3-datatable-even`.
@property CLASS_EVEN
@type {String}
@default 'yui3-table-even'
@since 3.5.0
**/
//CLASS_EVEN: null
/**
CSS class applied to odd rows. This is assigned at instantiation.
When used by DataTable instances, this will be `yui3-datatable-odd`.
@property CLASS_ODD
@type {String}
@default 'yui3-table-odd'
@since 3.5.0
**/
//CLASS_ODD: null
/**
HTML template used to create table rows.
@property ROW_TEMPLATE
@type {HTML}
@default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>'
@since 3.5.0
**/
ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',
/**
The object that serves as the source of truth for column and row data.
This property is assigned at instantiation from the `host` property of
the configuration object passed to the constructor.
@property host
@type {Object}
@default (initially unset)
@since 3.5.0
**/
//TODO: should this be protected?
//host: null,
/**
HTML templates used to create the `<tbody>` containing the table rows.
@property TBODY_TEMPLATE
@type {HTML}
@default '<tbody class="{className}">{content}</tbody>'
@since 3.6.0
**/
TBODY_TEMPLATE: '<tbody class="{className}"></tbody>',
// -- Public methods ------------------------------------------------------
/**
Returns the `<td>` Node from the given row and column index. Alternately,
the `seed` can be a Node. If so, the nearest ancestor cell is returned.
If the `seed` is a cell, it is returned. If there is no cell at the given
coordinates, `null` is returned.
Optionally, include an offset array or string to return a cell near the
cell identified by the `seed`. The offset can be an array containing the
number of rows to shift followed by the number of columns to shift, or one
of "above", "below", "next", or "previous".
<pre><code>// Previous cell in the previous row
var cell = table.getCell(e.target, [-1, -1]);
// Next cell
var cell = table.getCell(e.target, 'next');
var cell = table.getCell(e.target, [0, 1];</pre></code>
@method getCell
@param {Number[]|Node} seed Array of row and column indexes, or a Node that
is either the cell itself or a descendant of one.
@param {Number[]|String} [shift] Offset by which to identify the returned
cell Node
@return {Node}
@since 3.5.0
**/
getCell: function (seed, shift) {
var tbody = this.tbodyNode,
row, cell, index, rowIndexOffset;
if (seed && tbody) {
if (isArray(seed)) {
row = tbody.get('children').item(seed[0]);
cell = row && row.get('children').item(seed[1]);
} else if (Y.instanceOf(seed, Y.Node)) {
cell = seed.ancestor('.' + this.getClassName('cell'), true);
}
if (cell && shift) {
rowIndexOffset = tbody.get('firstChild.rowIndex');
if (isString(shift)) {
// TODO this should be a static object map
switch (shift) {
case 'above' : shift = [-1, 0]; break;
case 'below' : shift = [1, 0]; break;
case 'next' : shift = [0, 1]; break;
case 'previous': shift = [0, -1]; break;
}
}
if (isArray(shift)) {
index = cell.get('parentNode.rowIndex') +
shift[0] - rowIndexOffset;
row = tbody.get('children').item(index);
index = cell.get('cellIndex') + shift[1];
cell = row && row.get('children').item(index);
}
}
}
return cell || null;
},
/**
Returns the generated CSS classname based on the input. If the `host`
attribute is configured, it will attempt to relay to its `getClassName`
or use its static `NAME` property as a string base.
If `host` is absent or has neither method nor `NAME`, a CSS classname
will be generated using this class's `NAME`.
@method getClassName
@param {String} token* Any number of token strings to assemble the
classname from.
@return {String}
@protected
@since 3.5.0
**/
getClassName: function () {
var host = this.host,
args;
if (host && host.getClassName) {
return host.getClassName.apply(host, arguments);
} else {
args = toArray(arguments);
args.unshift(this.constructor.NAME);
return Y.ClassNameManager.getClassName
.apply(Y.ClassNameManager, args);
}
},
/**
Returns the Model associated to the row Node or id provided. Passing the
Node or id for a descendant of the row also works.
If no Model can be found, `null` is returned.
@method getRecord
@param {String|Node} seed Row Node or `id`, or one for a descendant of a row
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var modelList = this.get('modelList'),
tbody = this.tbodyNode,
row = null,
record;
if (tbody) {
if (isString(seed)) {
seed = tbody.one('#' + seed);
}
if (Y.instanceOf(seed, Y.Node)) {
row = seed.ancestor(function (node) {
return node.get('parentNode').compareTo(tbody);
}, true);
record = row &&
modelList.getByClientId(row.getData('yui3-record'));
}
}
return record || null;
},
/**
Returns the `<tr>` Node from the given row index, Model, or Model's
`clientId`. If the rows haven't been rendered yet, or if the row can't be
found by the input, `null` is returned.
@method getRow
@param {Number|String|Model} id Row index, Model instance, or clientId
@return {Node}
@since 3.5.0
**/
getRow: function (id) {
var tbody = this.tbodyNode,
row = null;
if (tbody) {
if (id) {
id = this._idMap[id.get ? id.get('clientId') : id] || id;
}
row = isNumber(id) ?
tbody.get('children').item(id) :
tbody.one('#' + id);
}
return row;
},
/**
Creates the table's `<tbody>` content by assembling markup generated by
populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content
from the `columns` and `modelList` attributes.
The rendering process happens in three stages:
1. A row template is assembled from the `columns` attribute (see
`_createRowTemplate`)
2. An HTML string is built up by concatenating the application of the data in
each Model in the `modelList` to the row template. For cells with
`formatter`s, the function is called to generate cell content. Cells
with `nodeFormatter`s are ignored. For all other cells, the data value
from the Model attribute for the given column key is used. The
accumulated row markup is then inserted into the container.
3. If any column is configured with a `nodeFormatter`, the `modelList` is
iterated again to apply the `nodeFormatter`s.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in
this column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform
any custom modifications on the cell or row Node that could not be
performed by `formatter`s. Should be used sparingly for better
performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a
column.
Column `formatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML
content. A returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the
`<td>`. When adding content to the cell, prefer appending into this
property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,
as it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The
DOM elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@method render
@return {BodyView} The instance
@chainable
@since 3.5.0
**/
render: function () {
var table = this.get('container'),
data = this.get('modelList'),
displayCols = this.get('columns'),
tbody = this.tbodyNode ||
(this.tbodyNode = this._createTBodyNode());
// Needed for mutation
this._createRowTemplate(displayCols);
if (data) {
tbody.setHTML(this._createDataHTML(displayCols));
this._applyNodeFormatters(tbody, displayCols);
}
if (tbody.get('parentNode') !== table) {
table.appendChild(tbody);
}
this.bindUI();
return this;
},
/**
Refreshes the provided row against the provided model and the Array of
columns to be updated.
@method refreshRow
@param {Y.Node} row
@param {Y.Model} model Y.Model representation of the row
@param {String[]} colKeys Array of column keys
@chainable
*/
refreshRow: function (row, model, colKeys) {
var col,
cell,
len = colKeys.length,
i;
for (i = 0; i < len; i++) {
col = this.getColumn(colKeys[i]);
if (col !== null) {
cell = row.one('.' + this.getClassName('col', col._id || col.key));
this.refreshCell(cell, model);
}
}
return this;
},
/**
Refreshes the given cell with the provided model data and the provided
column configuration.
Uses the provided column formatter if aviable.
@method refreshCell
@param {Y.Node} cell Y.Node pointer to the cell element to be updated
@param {Y.Model} [model] Y.Model representation of the row
@param {Object} [col] Column configuration object for the cell
@chainable
*/
refreshCell: function (cell, model, col) {
var content,
formatterFn,
formatterData,
data = model.toJSON();
cell = this.getCell(cell);
/* jshint -W030 */
model || (model = this.getRecord(cell));
col || (col = this.getColumn(cell));
/* jshint +W030 */
if (col.nodeFormatter) {
formatterData = {
cell: cell.one('.' + this.getClassName('liner')) || cell,
column: col,
data: data,
record: model,
rowIndex: this._getRowIndex(cell.ancestor('tr')),
td: cell,
value: data[col.key]
};
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
} else if (col.formatter) {
if (!col._formatterFn) {
col = this._setColumnsFormatterFn([col])[0];
}
formatterFn = col._formatterFn || null;
if (formatterFn) {
formatterData = {
value : data[col.key],
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : this._getRowIndex(cell.ancestor('tr'))
};
// Formatters can either return a value ...
content = formatterFn.call(this.get('host'), formatterData);
// ... or update the value property of the data obj passed
if (content === undefined) {
content = formatterData.value;
}
}
if (content === undefined || content === null || content === '') {
content = col.emptyCellValue || '';
}
} else {
content = data[col.key] || col.emptyCellValue || '';
}
cell.setHTML(col.allowHTML ? content : Y.Escape.html(content));
return this;
},
/**
Returns column data from this.get('columns'). If a Y.Node is provided as
the key, will try to determine the key from the classname
@method getColumn
@param {String|Y.Node} name
@return {Object} Returns column configuration
*/
getColumn: function (name) {
if (Y.instanceOf(name, Y.Node)) {
// get column name from node
name = name.get('className').match(
new RegExp( this.getClassName('col') +'-([^ ]*)' )
)[1];
}
if (this.host) {
return this.host._columnMap[name] || null;
}
var displayCols = this.get('columns'),
col = null;
Y.Array.some(displayCols, function (_col) {
if ((_col._id || _col.key) === name) {
col = _col;
return true;
}
});
return col;
},
// -- Protected and private methods ---------------------------------------
/**
Handles changes in the source's columns attribute. Redraws the table data.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
// TODO: Preserve existing DOM
// This will involve parsing and comparing the old and new column configs
// and reacting to four types of changes:
// 1. formatter, nodeFormatter, emptyCellValue changes
// 2. column deletions
// 3. column additions
// 4. column moves (preserve cells)
_afterColumnsChange: function () {
this.render();
},
/**
Handles modelList changes, including additions, deletions, and updates.
Modifies the existing table DOM accordingly.
@method _afterDataChange
@param {EventFacade} e The `change` event from the ModelList
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
var type = (e.type.match(/:(add|change|remove)$/) || [])[1],
index = e.index,
displayCols = this.get('columns'),
col,
changed = e.changed && Y.Object.keys(e.changed),
key,
row,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++ ) {
col = displayCols[i];
// since nodeFormatters typcially make changes outside of it's
// cell, we need to see if there are any columns that have a
// nodeFormatter and if so, we need to do a full render() of the
// tbody
if (col.hasOwnProperty('nodeFormatter')) {
this.render();
this.fire(EV_CONTENT_UPDATE);
return;
}
}
// TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping?
switch (type) {
case 'change':
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
key = col.key;
if (col.formatter && !e.changed[key]) {
changed.push(key);
}
}
this.refreshRow(this.getRow(e.target), e.target, changed);
break;
case 'add':
// we need to make sure we don't have an index larger than the data we have
index = Math.min(index, this.get('modelList').size() - 1);
// updates the columns with formatter functions
this._setColumnsFormatterFn(displayCols);
row = Y.Node.create(this._createRowHTML(e.model, index, displayCols));
this.tbodyNode.insert(row, index);
this._restripe(index);
break;
case 'remove':
this.getRow(index).remove(true);
// we removed a row, so we need to back up our index to stripe
this._restripe(index - 1);
break;
default:
this.render();
}
// Event fired to tell users when we are done updating after the data
// was changed
this.fire(EV_CONTENT_UPDATE);
},
/**
Toggles the odd/even classname of the row after the given index. This method
is used to update rows after a row is inserted into or removed from the table.
Note this event is delayed so the table is only restriped once when multiple
rows are updated at one time.
@protected
@method _restripe
@param {Number} [index] Index of row to start restriping after
@since 3.11.0
*/
_restripe: function (index) {
var task = this._restripeTask,
self;
// index|0 to force int, avoid NaN. Math.max() to avoid neg indexes.
index = Math.max((index|0), 0);
if (!task) {
self = this;
this._restripeTask = {
timer: setTimeout(function () {
// Check for self existence before continuing
if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) {
self._restripeTask = null;
return;
}
var odd = [self.CLASS_ODD, self.CLASS_EVEN],
even = [self.CLASS_EVEN, self.CLASS_ODD],
index = self._restripeTask.index;
self.tbodyNode.get('childNodes')
.slice(index)
.each(function (row, i) { // TODO: each vs batch
row.replaceClass.apply(row, (index + i) % 2 ? even : odd);
});
self._restripeTask = null;
}, 0),
index: index
};
} else {
task.index = Math.min(task.index, index);
}
},
/**
Handles replacement of the modelList.
Rerenders the `<tbody>` contents.
@method _afterModelListChange
@param {EventFacade} e The `modelListChange` event
@protected
@since 3.6.0
**/
_afterModelListChange: function () {
var handles = this._eventHandles;
if (handles.dataChange) {
handles.dataChange.detach();
delete handles.dataChange;
this.bindUI();
}
if (this.tbodyNode) {
this.render();
}
},
/**
Iterates the `modelList`, and calls any `nodeFormatter`s found in the
`columns` param on the appropriate cell Nodes in the `tbody`.
@method _applyNodeFormatters
@param {Node} tbody The `<tbody>` Node whose columns to update
@param {Object[]} displayCols The column configurations
@protected
@since 3.5.0
**/
_applyNodeFormatters: function (tbody, displayCols) {
var host = this.host || this,
data = this.get('modelList'),
formatters = [],
linerQuery = '.' + this.getClassName('liner'),
rows, i, len;
// Only iterate the ModelList again if there are nodeFormatters
for (i = 0, len = displayCols.length; i < len; ++i) {
if (displayCols[i].nodeFormatter) {
formatters.push(i);
}
}
if (data && formatters.length) {
rows = tbody.get('childNodes');
data.each(function (record, index) {
var formatterData = {
data : record.toJSON(),
record : record,
rowIndex : index
},
row = rows.item(index),
i, len, col, key, cells, cell, keep;
if (row) {
cells = row.get('childNodes');
for (i = 0, len = formatters.length; i < len; ++i) {
cell = cells.item(formatters[i]);
if (cell) {
col = formatterData.column = displayCols[formatters[i]];
key = col.key || col.id;
formatterData.value = record.get(key);
formatterData.td = cell;
formatterData.cell = cell.one(linerQuery) || cell;
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
}
}
}
});
}
},
/**
Binds event subscriptions from the UI and the host (if assigned).
@method bindUI
@protected
@since 3.5.0
**/
bindUI: function () {
var handles = this._eventHandles,
modelList = this.get('modelList'),
changeEvent = modelList.model.NAME + ':change';
if (!handles.columnsChange) {
handles.columnsChange = this.after('columnsChange',
bind('_afterColumnsChange', this));
}
if (modelList && !handles.dataChange) {
handles.dataChange = modelList.after(
['add', 'remove', 'reset', changeEvent],
bind('_afterDataChange', this));
}
},
/**
Iterates the `modelList` and applies each Model to the `_rowTemplate`,
allowing any column `formatter` or `emptyCellValue` to override cell
content for the appropriate column. The aggregated HTML string is
returned.
@method _createDataHTML
@param {Object[]} displayCols The column configurations to customize the
generated cell content or class names
@return {HTML} The markup for all Models in the `modelList`, each applied
to the `_rowTemplate`
@protected
@since 3.5.0
**/
_createDataHTML: function (displayCols) {
var data = this.get('modelList'),
html = '';
if (data) {
data.each(function (model, index) {
html += this._createRowHTML(model, index, displayCols);
}, this);
}
return html;
},
/**
Applies the data of a given Model, modified by any column formatters and
supplemented by other template values to the instance's `_rowTemplate` (see
`_createRowTemplate`). The generated string is then returned.
The data from Model's attributes is fetched by `toJSON` and this data
object is appended with other properties to supply values to {placeholders}
in the template. For a template generated from a Model with 'foo' and 'bar'
attributes, the data object would end up with the following properties
before being used to populate the `_rowTemplate`:
* `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute.
* `foo` - The value to populate the 'foo' column cell content. This
value will be the value stored in the Model's `foo` attribute, or the
result of the column's `formatter` if assigned. If the value is '',
`null`, or `undefined`, and the column's `emptyCellValue` is assigned,
that value will be used.
* `bar` - Same for the 'bar' column cell content.
* `foo-className` - String of CSS classes to apply to the `<td>`.
* `bar-className` - Same.
* `rowClass` - String of CSS classes to apply to the `<tr>`. This
will be the odd/even class per the specified index plus any additional
classes assigned by column formatters (via `o.rowClass`).
Because this object is available to formatters, any additional properties
can be added to fill in custom {placeholders} in the `_rowTemplate`.
@method _createRowHTML
@param {Model} model The Model instance to apply to the row template
@param {Number} index The index the row will be appearing
@param {Object[]} displayCols The column configurations
@return {HTML} The markup for the provided Model, less any `nodeFormatter`s
@protected
@since 3.5.0
**/
_createRowHTML: function (model, index, displayCols) {
var data = model.toJSON(),
clientId = model.get('clientId'),
values = {
rowId : this._getRowId(clientId),
clientId: clientId,
rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN
},
host = this.host || this,
i, len, col, token, value, formatterData;
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
value = data[col.key];
token = col._id || col.key;
values[token + '-className'] = '';
if (col._formatterFn) {
formatterData = {
value : value,
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : index
};
// Formatters can either return a value
value = col._formatterFn.call(host, formatterData);
// or update the value property of the data obj passed
if (value === undefined) {
value = formatterData.value;
}
values[token + '-className'] = formatterData.className;
values.rowClass += ' ' + formatterData.rowClass;
}
// if the token missing OR is the value a legit value
if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) {
if (value === undefined || value === null || value === '') {
value = col.emptyCellValue || '';
}
values[token] = col.allowHTML ? value : htmlEscape(value);
}
}
// replace consecutive whitespace with a single space
values.rowClass = values.rowClass.replace(/\s+/g, ' ');
return fromTemplate(this._rowTemplate, values);
},
/**
Locates the row within the tbodyNode and returns the found index, or Null
if it is not found in the tbodyNode
@param {Y.Node} row
@return {Number} Index of row in tbodyNode
*/
_getRowIndex: function (row) {
var tbody = this.tbodyNode,
index = 1;
if (tbody && row) {
//if row is not in the tbody, return
if (row.ancestor('tbody') !== tbody) {
return null;
}
// increment until we no longer have a previous node
/*jshint boss: true*/
while (row = row.previous()) { // NOTE: assignment
/*jshint boss: false*/
index++;
}
}
return index;
},
/**
Creates a custom HTML template string for use in generating the markup for
individual table rows with {placeholder}s to capture data from the Models
in the `modelList` attribute or from column `formatter`s.
Assigns the `_rowTemplate` property.
@method _createRowTemplate
@param {Object[]} displayCols Array of column configuration objects
@protected
@since 3.5.0
**/
_createRowTemplate: function (displayCols) {
var html = '',
cellTemplate = this.CELL_TEMPLATE,
i, len, col, key, token, headers, tokenValues, formatter;
this._setColumnsFormatterFn(displayCols);
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
key = col.key;
token = col._id || key;
formatter = col._formatterFn;
// Only include headers if there are more than one
headers = (col._headers || []).length > 1 ?
'headers="' + col._headers.join(' ') + '"' : '';
tokenValues = {
content : '{' + token + '}',
headers : headers,
className: this.getClassName('col', token) + ' ' +
(col.className || '') + ' ' +
this.getClassName('cell') +
' {' + token + '-className}'
};
if (!formatter && col.formatter) {
tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content);
}
if (col.nodeFormatter) {
// Defer all node decoration to the formatter
tokenValues.content = '';
}
html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);
}
this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {
content: html
});
},
/**
Parses the columns array and defines the column's _formatterFn if there
is a formatter available on the column
@protected
@method _setColumnsFormatterFn
@param {Object[]} displayCols Array of column configuration objects
@return {Object[]} Returns modified displayCols configuration Array
*/
_setColumnsFormatterFn: function (displayCols) {
var Formatters = Y.DataTable.BodyView.Formatters,
formatter,
col,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
formatter = col.formatter;
if (!col._formatterFn && formatter) {
if (Lang.isFunction(formatter)) {
col._formatterFn = formatter;
} else if (formatter in Formatters) {
col._formatterFn = Formatters[formatter].call(this.host || this, col);
}
}
}
return displayCols;
},
/**
Creates the `<tbody>` node that will store the data rows.
@method _createTBodyNode
@return {Node}
@protected
@since 3.6.0
**/
_createTBodyNode: function () {
return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {
className: this.getClassName('data')
}));
},
/**
Destroys the instance.
@method destructor
@protected
@since 3.5.0
**/
destructor: function () {
(new Y.EventHandle(YObject.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_eventHandles: null,
/**
Returns the row ID associated with a Model's clientId.
@method _getRowId
@param {String} clientId The Model clientId
@return {String}
@protected
**/
_getRowId: function (clientId) {
return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());
},
/**
Map of Model clientIds to row ids.
@property _idMap
@type {Object}
@protected
**/
//_idMap,
/**
Initializes the instance. Reads the following configuration properties in
addition to the instance attributes:
* `columns` - (REQUIRED) The initial column information
* `host` - The object to serve as source of truth for column info and
for generating class names
@method initializer
@param {Object} config Configuration data
@protected
@since 3.5.0
**/
initializer: function (config) {
this.host = config.host;
this._eventHandles = {
modelListChange: this.after('modelListChange',
bind('_afterModelListChange', this))
};
this._idMap = {};
this.CLASS_ODD = this.getClassName('odd');
this.CLASS_EVEN = this.getClassName('even');
}
/**
The HTML template used to create a full row of markup for a single Model in
the `modelList` plus any customizations defined in the column
configurations.
@property _rowTemplate
@type {HTML}
@default (initially unset)
@protected
@since 3.5.0
**/
//_rowTemplate: null
},{
/**
Hash of formatting functions for cell contents.
This property can be populated with a hash of formatting functions by the developer
or a set of pre-defined functions can be loaded via the `datatable-formatters` module.
See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html)
@property Formatters
@type Object
@since 3.8.0
@static
**/
Formatters: {}
});
}, '@VERSION@', {"requires": ["datatable-core", "view", "classnamemanager"]});
|
src/ui/quark/ToolbarSeparator/index.js
|
jkubos/tickator-ide
|
import React from 'react'
import styles from './style.less'
export class ToolbarSeparator extends React.Component {
render() {
return <div className={styles.main}>
</div>
}
}
|
src/containers/Root.js
|
RafaelDelboni/todo-react-redux
|
import React from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'react-redux';
import routes from '../routes';
import { Router } from 'react-router';
export default class Root extends React.Component {
render() {
const { store, history } = this.props;
return (
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
);
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
|
node_modules/native-base/Components/Widgets/H2.js
|
aspanu/threeSeaShells
|
/* @flow */
'use strict';
import React from 'react';
import Text from './Text';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
export default class H2NB extends NativeBaseComponent {
propTypes: {
style : React.PropTypes.object
}
prepareRootProps() {
var type = {
color: this.getTheme().textColor,
fontSize: this.getTheme().fontSizeH2
}
var defaultProps = {
style: type
}
return computeProps(this.props, defaultProps);
}
render() {
return(
<Text {...this.prepareRootProps()}>{this.props.children}</Text>
);
}
}
|
node_modules/react-icons/io/android-color-palette.js
|
bengimbel/Solstice-React-Contacts-Project
|
import React from 'react'
import Icon from 'react-icon-base'
const IoAndroidColorPalette = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m20 5c8.3 0 15 6 15 13.4 0 4.6-3.7 8.2-8.4 8.2h-2.9c-1.4 0-2.5 1.1-2.5 2.5 0 0.7 0.2 1.4 0.6 1.8s0.7 0.9 0.7 1.6c0 1.4-1.1 2.5-2.5 2.5-8.3 0-15-6.7-15-15s6.7-15 15-15z m-9.1 15c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m5-6.6c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m8.2 0c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z m5 6.6c1.4 0 2.5-1.1 2.5-2.5s-1.1-2.5-2.5-2.5-2.5 1.1-2.5 2.5 1.1 2.5 2.5 2.5z"/></g>
</Icon>
)
export default IoAndroidColorPalette
|
node_modules/react-bootstrap/es/ModalBody.js
|
cmccandless/SolRFrontEnd
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var ModalBody = function (_React$Component) {
_inherits(ModalBody, _React$Component);
function ModalBody() {
_classCallCheck(this, ModalBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalBody.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ModalBody;
}(React.Component);
export default bsClass('modal-body', ModalBody);
|
src/svg-icons/av/movie.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMovie = (props) => (
<SvgIcon {...props}>
<path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"/>
</SvgIcon>
);
AvMovie = pure(AvMovie);
AvMovie.displayName = 'AvMovie';
AvMovie.muiName = 'SvgIcon';
export default AvMovie;
|
src/mui/form/Toolbar.js
|
epwqice/admin-on-rest-old-man
|
import React from 'react';
import { Toolbar as MuiToolbar, ToolbarGroup } from 'material-ui/Toolbar';
import Responsive from '../layout/Responsive';
import { SaveButton } from '../button';
const styles = {
mobileToolbar: {
position: 'fixed',
bottom: 0,
width: '100%',
backgroundColor: 'white',
justifyContent: 'flex-end',
zIndex: 2,
},
};
const Toolbar = ({ invalid }) => (
<Responsive
small={
<MuiToolbar style={styles.mobileToolbar} noGutter>
<ToolbarGroup>
<SaveButton invalid={invalid} raised={false} />
</ToolbarGroup>
</MuiToolbar>
}
medium={
<MuiToolbar>
<ToolbarGroup>
<SaveButton invalid={invalid} />
</ToolbarGroup>
</MuiToolbar>
}
/>
);
export default Toolbar;
|
src/js/components/icons/base/Lounge.js
|
linde12/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}-lounge`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'lounge');
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="M5,5.99703014 C5,5.4463856 5.44994876,5 6.00684547,5 L17.9931545,5 C18.5492199,5 19,5.45303631 19,5.99703014 L19,13 L5,13 L5,5.99703014 Z M22,8 L22,15.0029699 C22,15.5536144 21.5446944,16 21.0081969,16 L2.99180311,16 C2.44404538,16 2,15.5469637 2,15.0029699 L2,8 M5,16 L5,18 L5,16 Z M19,16 L19,18 L19,16 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Lounge';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
packages/material-ui-icons/src/BackspaceOutlined.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="M22 3H7c-.69 0-1.23.35-1.59.88L0 12l5.41 8.11c.36.53.9.89 1.59.89h15c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H7.07L2.4 12l4.66-7H22v14z" /><path d="M10.41 17L14 13.41 17.59 17 19 15.59 15.41 12 19 8.41 17.59 7 14 10.59 10.41 7 9 8.41 12.59 12 9 15.59z" /></React.Fragment>
, 'BackspaceOutlined');
|
ajax/libs/F2/1.3.3/f2.js
|
mikesir87/cdnjs
|
;(function(exports) {
if (exports.F2 && !exports.F2_TESTING_MODE) {
return;
}
/*!
JSON.org requires the following notice to accompany json2:
Copyright (c) 2002 JSON.org
http://json.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 shall be used for Good, not Evil.
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.
*/
/*
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
/*!
* jQuery JavaScript Library v1.8.3
* The jQuery Foundation and other contributors require the following notice to accompany jQuery:
*
* Copyright (c) 2013 jQuery Foundation and other contributors
*
* http://jquery.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.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%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
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( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
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( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.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( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
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, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/*! =========================================================
* bootstrap-modal.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#modals
* =========================================================
* Twitter, Inc. require the following notice to accompany Bootstrap:
*
* Copyright (c) 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work
* except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or 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 ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
}
Modal.prototype = {
constructor: Modal
, toggle: function () {
return this[!this.isShown ? 'show' : 'hide']()
}
, show: function () {
var that = this
, e = $.Event('show')
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) //don't move modals dom position
}
that.$element
.show()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
transition ?
that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) :
that.$element.focus().trigger('shown')
})
}
, hide: function (e) {
e && e.preventDefault()
var that = this
e = $.Event('hide')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal()
}
, enforceFocus: function () {
var that = this
$(document).on('focusin.modal', function (e) {
if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
that.$element.focus()
}
})
}
, escape: function () {
var that = this
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.modal', function ( e ) {
e.which == 27 && that.hide()
})
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
}
, hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end)
that.hideModal()
}, 500)
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout)
that.hideModal()
})
}
, hideModal: function (that) {
this.$element
.hide()
.trigger('hidden')
this.backdrop()
}
, removeBackdrop: function () {
this.$backdrop.remove()
this.$backdrop = null
}
, backdrop: function (callback) {
var that = this
, animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$backdrop.click(
this.options.backdrop == 'static' ?
$.proxy(this.$element[0].focus, this.$element[0])
: $.proxy(this.hide, this)
)
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
doAnimate ?
this.$backdrop.one($.support.transition.end, callback) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade')?
this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) :
this.removeBackdrop()
} else if (callback) {
callback()
}
}
}
/* MODAL PLUGIN DEFINITION
* ======================= */
var old = $.fn.modal
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.modal.defaults = {
backdrop: true
, keyboard: true
, show: true
}
$.fn.modal.Constructor = Modal
/* MODAL NO CONFLICT
* ================= */
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
/* MODAL DATA-API
* ============== */
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
, href = $this.attr('href')
, $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option)
.one('hide', function () {
$this.focus()
})
})
}(window.jQuery);
/*!
* This file creates $ and jQuery variables within the F2 closure scope
*/
var $, jQuery = $ = window.jQuery.noConflict(true);
/*!
* Hij1nx requires the following notice to accompany EventEmitter:
*
* Copyright (c) 2011 hij1nx
*
* http://www.twitter.com/hij1nx
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the 'Software'), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
!function(exports, undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = new Object;
}
function configure(conf) {
if (conf) {
conf.delimiter && (this.delimiter = conf.delimiter);
conf.wildcard && (this.wildcard = conf.wildcard);
if (this.wildcard) {
this.listenerTree = new Object;
}
}
}
function EventEmitter(conf) {
this._events = new Object;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = new Object;
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
};
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
};
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener') {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || this._all;
}
else {
return this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if(!this._all) {
this._all = [];
}
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
return this;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1)
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
// if (typeof define === 'function' && define.amd) {
// define('EventEmitter2', [], function() {
// return EventEmitter;
// });
// } else {
exports.EventEmitter2 = EventEmitter;
// }
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window);
/*!
* Øyvind Sean Kinsey and others require the following notice to accompany easyXDM:
*
* http://easyxdm.net/
* Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) {
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */
var global = this;
var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded
var emptyFn = Function.prototype;
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression
var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global)
var easyXDM = {};
var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite
var IFRAME_PREFIX = "easyXDM_";
var HAS_NAME_PROPERTY_BUG;
var useHash = false; // whether to use the hash over the query
var flashVersion; // will be set if using flash
var HAS_FLASH_THROTTLED_BUG;
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
// end
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
// end
function hasFlash(){
try {
var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1);
HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0;
activeX = null;
return true;
}
catch (notSupportedException) {
return false;
}
}
/*
* Cross Browser implementation for adding and removing event listeners.
*/
var on, un;
if (isHostMethod(window, "addEventListener")) {
on = function(target, type, listener){
target.addEventListener(type, listener, false);
};
un = function(target, type, listener){
target.removeEventListener(type, listener, false);
};
}
else if (isHostMethod(window, "attachEvent")) {
on = function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
un = function(object, sEvent, fpNotify){
object.detachEvent("on" + sEvent, fpNotify);
};
}
else {
throw new Error("Browser not supported");
}
/*
* Cross Browser implementation of DOMContentLoaded.
*/
var domIsReady = false, domReadyQueue = [], readyState;
if ("readyState" in document) {
// If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and
// 'interactive' (HTML5 specs, recent WebKit builds) states.
// https://bugs.webkit.org/show_bug.cgi?id=45119
readyState = document.readyState;
domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive"));
}
else {
// If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately
// when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not.
// We only need a body to add elements to, so the existence of document.body is enough for us.
domIsReady = !!document.body;
}
function dom_onReady(){
if (domIsReady) {
return;
}
domIsReady = true;
for (var i = 0; i < domReadyQueue.length; i++) {
domReadyQueue[i]();
}
domReadyQueue.length = 0;
}
if (!domIsReady) {
if (isHostMethod(window, "addEventListener")) {
on(document, "DOMContentLoaded", dom_onReady);
}
else {
on(document, "readystatechange", function(){
if (document.readyState == "complete") {
dom_onReady();
}
});
if (document.documentElement.doScroll && window === top) {
var doScrollCheck = function(){
if (domIsReady) {
return;
}
// http://javascript.nwbox.com/IEContentLoaded/
try {
document.documentElement.doScroll("left");
}
catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
dom_onReady();
};
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
on(window, "load", dom_onReady);
}
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {Object} scope An optional scope for the function to be called with.
*/
function whenReady(fn, scope){
if (domIsReady) {
fn.call(scope);
return;
}
domReadyQueue.push(function(){
fn.call(scope);
});
}
/**
* Returns an instance of easyXDM from the parent window with
* respect to the namespace.
*
* @return An instance of easyXDM (in the parent window)
*/
function getParentObject(){
var obj = parent;
if (namespace !== "") {
for (var i = 0, ii = namespace.split("."); i < ii.length; i++) {
obj = obj[ii[i]];
}
}
return obj.easyXDM;
}
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
function noConflict(ns){
window.easyXDM = _easyXDM;
namespace = ns;
if (namespace) {
IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_";
}
return easyXDM;
}
/*
* Methods for working with URLs
*/
/**
* Get the domain name from a url.
* @param {String} url The url to extract the domain from.
* @return The domain part of the url.
* @type {String}
*/
function getDomainName(url){
return url.match(reURI)[3];
}
/**
* Get the port for a given URL, or "" if none
* @param {String} url The url to extract the port from.
* @return The port part of the url.
* @type {String}
*/
function getPort(url){
return url.match(reURI)[4] || "";
}
/**
* Returns a string containing the schema, domain and if present the port
* @param {String} url The url to extract the location from
* @return {String} The location part of the url
*/
function getLocation(url){
var m = url.toLowerCase().match(reURI);
var proto = m[2], domain = m[3], port = m[4] || "";
if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) {
port = "";
}
return proto + "//" + domain + port;
}
/**
* Resolves a relative url into an absolute one.
* @param {String} url The path to resolve.
* @return {String} The resolved url.
*/
function resolveUrl(url){
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
url = location.protocol + "//" + location.host + path + url;
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
/**
* Appends the parameters to the given url.<br/>
* The base url can contain existing query parameters.
* @param {String} url The base url.
* @param {Object} parameters The parameters to add.
* @return {String} A new valid url with the parameters appended.
*/
function appendQueryParameters(url, parameters){
var hash = "", indexOf = url.indexOf("#");
if (indexOf !== -1) {
hash = url.substring(indexOf);
url = url.substring(0, indexOf);
}
var q = [];
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
q.push(key + "=" + encodeURIComponent(parameters[key]));
}
}
return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash;
}
// build the query object either from location.query, if it contains the xdm_e argument, or from location.hash
var query = (function(input){
input = input.substring(1).split("&");
var data = {}, pair, i = input.length;
while (i--) {
pair = input[i].split("=");
data[pair[0]] = decodeURIComponent(pair[1]);
}
return data;
}(/xdm_e=/.test(location.search) ? location.search : location.hash));
/*
* Helper methods
*/
/**
* Helper for checking if a variable/property is undefined
* @param {Object} v The variable to test
* @return {Boolean} True if the passed variable is undefined
*/
function undef(v){
return typeof v === "undefined";
}
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
var getJSON = function(){
var cached = {};
var obj = {
a: [1, 2, 3]
}, json = "{\"a\":[1,2,3]}";
if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) {
// this is a working JSON instance
return JSON;
}
if (Object.toJSON) {
if (Object.toJSON(obj).replace((/\s/g), "") === json) {
// this is a working stringify method
cached.stringify = Object.toJSON;
}
}
if (typeof String.prototype.evalJSON === "function") {
obj = json.evalJSON();
if (obj.a && obj.a.length === 3 && obj.a[2] === 3) {
// this is a working parse method
cached.parse = function(str){
return str.evalJSON();
};
}
}
if (cached.stringify && cached.parse) {
// Only memoize the result if we have valid instance
getJSON = function(){
return cached;
};
return cached;
}
return null;
};
/**
* Applies properties from the source object to the target object.<br/>
* @param {Object} target The target of the properties.
* @param {Object} source The source of the properties.
* @param {Boolean} noOverwrite Set to True to only set non-existing properties.
*/
function apply(destination, source, noOverwrite){
var member;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in destination) {
member = source[prop];
if (typeof member === "object") {
apply(destination[prop], member, noOverwrite);
}
else if (!noOverwrite) {
destination[prop] = source[prop];
}
}
else {
destination[prop] = source[prop];
}
}
}
return destination;
}
// This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName].
function testForNamePropertyBug(){
var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input"));
input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues
HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name];
document.body.removeChild(form);
}
/**
* Creates a frame and appends it to the DOM.
* @param config {object} This object can have the following properties
* <ul>
* <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li>
* <li> {object} attr The attributes that should be set on the frame.</li>
* <li> {DOMElement} container Its parent element (Optional).</li>
* <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li>
* </ul>
* @return The frames DOMElement
* @type DOMElement
*/
function createFrame(config){
if (undef(HAS_NAME_PROPERTY_BUG)) {
testForNamePropertyBug();
}
var frame;
// This is to work around the problems in IE6/7 with setting the name property.
// Internally this is set as 'submitName' instead when using 'iframe.name = ...'
// This is not required by easyXDM itself, but is to facilitate other use cases
if (HAS_NAME_PROPERTY_BUG) {
frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>");
}
else {
frame = document.createElement("IFRAME");
frame.name = config.props.name;
}
frame.id = frame.name = config.props.name;
delete config.props.name;
if (config.onLoad) {
on(frame, "load", config.onLoad);
}
if (typeof config.container == "string") {
config.container = document.getElementById(config.container);
}
if (!config.container) {
// This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers.
apply(frame.style, {
position: "absolute",
top: "-2000px"
});
config.container = document.body;
}
// HACK for some reason, IE needs the source set
// after the frame has been appended into the DOM
// so remove the src, and set it afterwards
var src = config.props.src;
delete config.props.src;
// transfer properties to the frame
apply(frame, config.props);
frame.border = frame.frameBorder = 0;
frame.allowTransparency = true;
config.container.appendChild(frame);
// HACK see above
frame.src = src;
config.props.src = src;
return frame;
}
/**
* Check whether a domain is allowed using an Access Control List.
* The ACL can contain * and ? as wildcards, or can be regular expressions.
* If regular expressions they need to begin with ^ and end with $.
* @param {Array/String} acl The list of allowed domains
* @param {String} domain The domain to test.
* @return {Boolean} True if the domain is allowed, false if not.
*/
function checkAcl(acl, domain){
// normalize into an array
if (typeof acl == "string") {
acl = [acl];
}
var re, i = acl.length;
while (i--) {
re = acl[i];
re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$"));
if (re.test(domain)) {
return true;
}
}
return false;
}
/*
* Functions related to stacks
*/
/**
* Prepares an array of stack-elements suitable for the current configuration
* @param {Object} config The Transports configuration. See easyXDM.Socket for more.
* @return {Array} An array of stack-elements with the TransportElement at index 0.
*/
function prepareTransportStack(config){
var protocol = config.protocol, stackEls;
config.isHost = config.isHost || undef(query.xdm_p);
useHash = config.hash || false;
if (!config.props) {
config.props = {};
}
if (!config.isHost) {
config.channel = query.xdm_c;
config.secret = query.xdm_s;
config.remote = query.xdm_e;
protocol = query.xdm_p;
if (config.acl && !checkAcl(config.acl, config.remote)) {
throw new Error("Access denied for " + config.remote);
}
}
else {
config.remote = resolveUrl(config.remote);
config.channel = config.channel || "default" + channelId++;
config.secret = Math.random().toString(16).substring(2);
if (undef(protocol)) {
if (getLocation(location.href) == getLocation(config.remote)) {
/*
* Both documents has the same origin, lets use direct access.
*/
protocol = "4";
}
else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) {
/*
* This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+
*/
protocol = "1";
}
else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) {
/*
* The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS
*/
protocol = "6";
}
else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) {
/*
* This is supported in Gecko (Firefox 1+)
*/
protocol = "5";
}
else if (config.remoteHelper) {
/*
* This is supported in all browsers that retains the value of window.name when
* navigating from one domain to another, and where parent.frames[foo] can be used
* to get access to a frame from the same domain
*/
config.remoteHelper = resolveUrl(config.remoteHelper);
protocol = "2";
}
else {
/*
* This is supported in all browsers where [window].location is writable for all
* The resize event will be used if resize is supported and the iframe is not put
* into a container, else polling will be used.
*/
protocol = "0";
}
}
}
config.protocol = protocol; // for conditional branching
switch (protocol) {
case "0":// 0 = HashTransport
apply(config, {
interval: 100,
delay: 2000,
useResize: true,
useParent: false,
usePolling: false
}, true);
if (config.isHost) {
if (!config.local) {
// If no local is set then we need to find an image hosted on the current domain
var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image;
var i = images.length;
while (i--) {
image = images[i];
if (image.src.substring(0, domain.length) === domain) {
config.local = image.src;
break;
}
}
if (!config.local) {
// If no local was set, and we are unable to find a suitable file, then we resort to using the current window
config.local = window;
}
}
var parameters = {
xdm_c: config.channel,
xdm_p: 0
};
if (config.local === window) {
// We are using the current window to listen to
config.usePolling = true;
config.useParent = true;
config.local = location.protocol + "//" + location.host + location.pathname + location.search;
parameters.xdm_e = config.local;
parameters.xdm_pa = 1; // use parent
}
else {
parameters.xdm_e = resolveUrl(config.local);
}
if (config.container) {
config.useResize = false;
parameters.xdm_po = 1; // use polling
}
config.remote = appendQueryParameters(config.remote, parameters);
}
else {
apply(config, {
channel: query.xdm_c,
remote: query.xdm_e,
useParent: !undef(query.xdm_pa),
usePolling: !undef(query.xdm_po),
useResize: config.useParent ? false : config.useResize
});
}
stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({
encode: true,
maxLength: 4000 - config.remote.length
}), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "1":
stackEls = [new easyXDM.stack.PostMessageTransport(config)];
break;
case "2":
stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "3":
stackEls = [new easyXDM.stack.NixTransport(config)];
break;
case "4":
stackEls = [new easyXDM.stack.SameOriginTransport(config)];
break;
case "5":
stackEls = [new easyXDM.stack.FrameElementTransport(config)];
break;
case "6":
if (!flashVersion) {
hasFlash();
}
stackEls = [new easyXDM.stack.FlashTransport(config)];
break;
}
// this behavior is responsible for buffering outgoing messages, and for performing lazy initialization
stackEls.push(new easyXDM.stack.QueueBehavior({
lazy: config.lazy,
remove: true
}));
return stackEls;
}
/**
* Chains all the separate stack elements into a single usable stack.<br/>
* If an element is missing a necessary method then it will have a pass-through method applied.
* @param {Array} stackElements An array of stack elements to be linked.
* @return {easyXDM.stack.StackElement} The last element in the chain.
*/
function chainStack(stackElements){
var stackEl, defaults = {
incoming: function(message, origin){
this.up.incoming(message, origin);
},
outgoing: function(message, recipient){
this.down.outgoing(message, recipient);
},
callback: function(success){
this.up.callback(success);
},
init: function(){
this.down.init();
},
destroy: function(){
this.down.destroy();
}
};
for (var i = 0, len = stackElements.length; i < len; i++) {
stackEl = stackElements[i];
apply(stackEl, defaults, true);
if (i !== 0) {
stackEl.down = stackElements[i - 1];
}
if (i !== len - 1) {
stackEl.up = stackElements[i + 1];
}
}
return stackEl;
}
/**
* This will remove a stackelement from its stack while leaving the stack functional.
* @param {Object} element The elment to remove from the stack.
*/
function removeFromStack(element){
element.up.down = element.down;
element.down.up = element.up;
element.up = element.down = null;
}
/*
* Export the main object and any other methods applicable
*/
/**
* @class easyXDM
* A javascript library providing cross-browser, cross-domain messaging/RPC.
* @version 2.4.15.118
* @singleton
*/
apply(easyXDM, {
/**
* The version of the library
* @type {string}
*/
version: "2.4.15.118",
/**
* This is a map containing all the query parameters passed to the document.
* All the values has been decoded using decodeURIComponent.
* @type {object}
*/
query: query,
/**
* @private
*/
stack: {},
/**
* Applies properties from the source object to the target object.<br/>
* @param {object} target The target of the properties.
* @param {object} source The source of the properties.
* @param {boolean} noOverwrite Set to True to only set non-existing properties.
*/
apply: apply,
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
getJSONObject: getJSON,
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {object} scope An optional scope for the function to be called with.
*/
whenReady: whenReady,
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
noConflict: noConflict
});
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.DomHelper
* Contains methods for dealing with the DOM
* @singleton
*/
easyXDM.DomHelper = {
/**
* Provides a consistent interface for adding eventhandlers
* @param {Object} target The target to add the event to
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
on: on,
/**
* Provides a consistent interface for removing eventhandlers
* @param {Object} target The target to remove the event from
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
un: un,
/**
* Checks for the presence of the JSON object.
* If it is not present it will use the supplied path to load the JSON2 library.
* This should be called in the documents head right after the easyXDM script tag.
* http://json.org/json2.js
* @param {String} path A valid path to json2.js
*/
requiresJSON: function(path){
if (!isHostObject(window, "JSON")) {
// we need to encode the < in order to avoid an illegal token error
// when the script is inlined in a document.
document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>');
}
}
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
(function(){
// The map containing the stored functions
var _map = {};
/**
* @class easyXDM.Fn
* This contains methods related to function handling, such as storing callbacks.
* @singleton
* @namespace easyXDM
*/
easyXDM.Fn = {
/**
* Stores a function using the given name for reference
* @param {String} name The name that the function should be referred by
* @param {Function} fn The function to store
* @namespace easyXDM.fn
*/
set: function(name, fn){
_map[name] = fn;
},
/**
* Retrieves the function referred to by the given name
* @param {String} name The name of the function to retrieve
* @param {Boolean} del If the function should be deleted after retrieval
* @return {Function} The stored function
* @namespace easyXDM.fn
*/
get: function(name, del){
var fn = _map[name];
if (del) {
delete _map[name];
}
return fn;
}
};
}());
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Socket
* This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/>
* The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/>
* Internally different stacks will be used depending on the browsers features and the available parameters.
* <h2>How to set up</h2>
* Setting up the provider:
* <pre><code>
* var socket = new easyXDM.Socket({
* local: "name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* Setting up the consumer:
* <pre><code>
* var socket = new easyXDM.Socket({
* remote: "http://remotedomain/page.html",
* remoteHelper: "http://remotedomain/name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property
* and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports.
* @namespace easyXDM
* @constructor
* @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window.
* @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed.
* @cfg {String} remote (Consumer only) The url to the providers document.
* @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000.
* @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300.
* @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional.
* @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional.
* @cfg {Function} onReady A method that should be called when the transport is ready. Optional.
* @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional.
* @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/>
* This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $.
* If none of the patterns match an Error will be thrown.
* @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>.
* Properties such as 'name' and 'src' will be overrided. Optional.
*/
easyXDM.Socket = function(config){
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([{
incoming: function(message, origin){
config.onMessage(message, origin);
},
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}])), recipient = getLocation(config.remote);
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
/**
* Posts a message to the remote end of the channel
* @param {String} message The message to send
*/
this.postMessage = function(message){
stack.outgoing(message, recipient);
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Rpc
* Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation
* of methods to be called from the remote end.<br/>
* The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/>
* This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods.
* <h2>How to set up</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* // this configuration is equal to that used by the Socket.
* remote: "http://remotedomain/...",
* onReady: function(){
* // you need to wait for the onReady callback before using the proxy
* rpc.foo(...
* }
* },{
* local: {..},
* remote: {..}
* });
* </code></pre>
*
* <h2>Exposing functions (procedures)</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {
* nameOfMethod: {
* method: function(arg1, arg2, success, error){
* ...
* }
* },
* // with shorthand notation
* nameOfAnotherMethod: function(arg1, arg2, success, error){
* }
* },
* remote: {...}
* });
* </code></pre>
* The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/>
* To send a successfull result back you can use
* <pre><code>
* return foo;
* </pre></code>
* or
* <pre><code>
* success(foo);
* </pre></code>
* To return an error you can use
* <pre><code>
* throw new Error("foo error");
* </code></pre>
* or
* <pre><code>
* error("foo error");
* </code></pre>
*
* <h2>Defining remotely exposed methods (procedures/notifications)</h2>
* The definition of the remote end is quite similar:
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {
* nameOfMethod: {}
* }
* });
* </code></pre>
* To call a remote method use
* <pre><code>
* rpc.nameOfMethod("arg1", "arg2", function(value) {
* alert("success: " + value);
* }, function(message) {
* alert("error: " + message + );
* });
* </code></pre>
* Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/>
* When called with no callback a JSON-RPC 2.0 notification will be executed.
* Be aware that you will not be notified of any errors with this method.
* <br/>
* <h2>Specifying a custom serializer</h2>
* If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library
* then you can specify a custom serializer using <code>serializer: foo</code>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {...},
* serializer : {
* parse: function(string){ ... },
* stringify: function(object) {...}
* }
* });
* </code></pre>
* If <code>serializer</code> is set then the class will not attempt to use the native implementation.
* @namespace easyXDM
* @constructor
* @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters.
* @param {Object} jsonRpcConfig The description of the interface to implement.
*/
easyXDM.Rpc = function(config, jsonRpcConfig){
// expand shorthand notation
if (jsonRpcConfig.local) {
for (var method in jsonRpcConfig.local) {
if (jsonRpcConfig.local.hasOwnProperty(method)) {
var member = jsonRpcConfig.local[method];
if (typeof member === "function") {
jsonRpcConfig.local[method] = {
method: member
};
}
}
}
}
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), {
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}]));
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.SameOriginTransport
* SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/>
* This can be useful for testing and for when the main application supports both internal and external sources.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.SameOriginTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send(message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: location.protocol + "//" + location.host + location.pathname,
xdm_c: config.channel,
xdm_p: 4 // 4 = SameOriginTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
easyXDM.Fn.set(config.channel, function(sendFn){
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
});
}
else {
send = getParentObject().Fn.get(config.channel, true)(function(msg){
pub.up.incoming(msg, targetOrigin);
});
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FlashTransport
* FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
* @cfg {String} secret the pre-shared secret used to secure the communication.
* @cfg {String} swf The path to the swf file
* @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden.
* @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed
*/
easyXDM.stack.FlashTransport = function(config){
var pub, // the public interface
frame, send, targetOrigin, swf, swfContainer;
function onMessage(message, origin){
setTimeout(function(){
pub.up.incoming(message, targetOrigin);
}, 0);
}
/**
* This method adds the SWF to the DOM and prepares the initialization of the channel
*/
function addSwf(domain){
// the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.
var url = config.swf + "?host=" + config.isHost;
var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
// prepare the init function that will fire once the swf is ready
easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){
easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;
var queue = easyXDM.stack.FlashTransport[domain].queue;
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
});
if (config.swfContainer) {
swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer;
}
else {
// create the container that will hold the swf
swfContainer = document.createElement('div');
// http://bugs.adobe.com/jira/browse/FP-4796
// http://tech.groups.yahoo.com/group/flexcoders/message/162365
// https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc
apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {
height: "20px",
width: "20px",
position: "fixed",
right: 0,
top: 0
} : {
height: "1px",
width: "1px",
position: "absolute",
overflow: "hidden",
right: 0,
top: 0
});
document.body.appendChild(swfContainer);
}
// create the object/embed
var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace;
swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
"<param name='allowScriptAccess' value='always'></param>" +
"<param name='wmode' value='transparent'>" +
"<param name='movie' value='" +
url +
"'></param>" +
"<param name='flashvars' value='" +
flashVars +
"'></param>" +
"<embed type='application/x-shockwave-flash' FlashVars='" +
flashVars +
"' allowScriptAccess='always' wmode='transparent' src='" +
url +
"' height='1' width='1'></embed>" +
"</object>";
}
return (pub = {
outgoing: function(message, domain, fn){
swf.postMessage(config.channel, message.toString());
if (fn) {
fn();
}
},
destroy: function(){
try {
swf.destroyChannel(config.channel);
}
catch (e) {
}
swf = null;
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = config.remote;
// Prepare the code that will be run after the swf has been intialized
easyXDM.Fn.set("flash_" + config.channel + "_init", function(){
setTimeout(function(){
pub.up.callback(true);
});
});
// set up the omMessage handler
easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths
var swfdomain = getDomainName(config.swf);
var fn = function(){
// set init to true in case the fn was called was invoked from a separate instance
easyXDM.stack.FlashTransport[swfdomain].init = true;
swf = easyXDM.stack.FlashTransport[swfdomain].swf;
// create the channel
swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost);
if (config.isHost) {
// if Flash is going to be throttled and we want to avoid this
if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) {
apply(config.props, {
position: "fixed",
right: 0,
top: 0,
height: "20px",
width: "20px"
});
}
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 6, // 6 = FlashTransport
xdm_s: config.secret
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
};
if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) {
// if the swf is in place and we are the consumer
fn();
}
else {
// if the swf does not yet exist
if (!easyXDM.stack.FlashTransport[swfdomain]) {
// add the queue to hold the init fn's
easyXDM.stack.FlashTransport[swfdomain] = {
queue: [fn]
};
addSwf(swfdomain);
}
else {
easyXDM.stack.FlashTransport[swfdomain].queue.push(fn);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.PostMessageTransport
* PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/>
* <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
*/
easyXDM.stack.PostMessageTransport = function(config){
var pub, // the public interface
frame, // the remote frame, if any
callerWindow, // the window that we will call with
targetOrigin; // the domain to communicate with
/**
* Resolves the origin from the event object
* @private
* @param {Object} event The messageevent
* @return {String} The scheme, host and port of the origin
*/
function _getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return getLocation(event.origin);
}
if (event.uri) {
// From earlier implementations
return getLocation(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
/**
* This is the main implementation for the onMessage event.<br/>
* It checks the validity of the origin and passes the message on if appropriate.
* @private
* @param {Object} event The messageevent
*/
function _window_onMessage(event){
var origin = _getOrigin(event);
if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin);
if (fn) {
fn();
}
},
destroy: function(){
un(window, "message", _window_onMessage);
if (frame) {
callerWindow = null;
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// add the event handler for listening
var waitForReady = function(event){
if (event.data == config.channel + "-ready") {
// replace the eventlistener
callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document;
un(window, "message", waitForReady);
on(window, "message", _window_onMessage);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
};
on(window, "message", waitForReady);
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 1 // 1 = PostMessage
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
else {
// add the event handler for listening
on(window, "message", _window_onMessage);
callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document;
callerWindow.postMessage(config.channel + "-ready", targetOrigin);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FrameElementTransport
* FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/>
* Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.FrameElementTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send.call(this, message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 5 // 5 = FrameElementTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
frame.fn = function(sendFn){
delete frame.fn;
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
// remove the function so that it cannot be used to overwrite the send function later on
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
};
}
else {
// This is to mitigate origin-spoofing
if (document.referrer && getLocation(document.referrer) != query.xdm_e) {
window.top.location = query.xdm_e;
}
send = window.frameElement.fn(function(msg){
pub.up.incoming(msg, targetOrigin);
});
pub.up.callback(true);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.NameTransport
* NameTransport uses the window.name property to relay data.
* The <code>local</code> parameter needs to be set on both the consumer and provider,<br/>
* and the <code>remoteHelper</code> parameter needs to be set on the consumer.
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host.
* @namespace easyXDM.stack
*/
easyXDM.stack.NameTransport = function(config){
var pub; // the public interface
var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl;
function _sendMessage(message){
var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel;
callerWindow.contentWindow.sendMessage(message, url);
}
function _onReady(){
if (isHost) {
if (++readyCount === 2 || !isHost) {
pub.up.callback(true);
}
}
else {
_sendMessage("ready");
pub.up.callback(true);
}
}
function _onMessage(message){
pub.up.incoming(message, remoteOrigin);
}
function _onLoad(){
if (callback) {
setTimeout(function(){
callback(true);
}, 0);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callback = fn;
_sendMessage(message);
},
destroy: function(){
callerWindow.parentNode.removeChild(callerWindow);
callerWindow = null;
if (isHost) {
remoteWindow.parentNode.removeChild(remoteWindow);
remoteWindow = null;
}
},
onDOMReady: function(){
isHost = config.isHost;
readyCount = 0;
remoteOrigin = getLocation(config.remote);
config.local = resolveUrl(config.local);
if (isHost) {
// Register the callback
easyXDM.Fn.set(config.channel, function(message){
if (isHost && message === "ready") {
// Replace the handler
easyXDM.Fn.set(config.channel, _onMessage);
_onReady();
}
});
// Set up the frame that points to the remote instance
remoteUrl = appendQueryParameters(config.remote, {
xdm_e: config.local,
xdm_c: config.channel,
xdm_p: 2
});
apply(config.props, {
src: remoteUrl + '#' + config.channel,
name: IFRAME_PREFIX + config.channel + "_provider"
});
remoteWindow = createFrame(config);
}
else {
config.remoteHelper = config.remote;
easyXDM.Fn.set(config.channel, _onMessage);
}
// Set up the iframe that will be used for the transport
callerWindow = createFrame({
props: {
src: config.local + "#_4" + config.channel
},
onLoad: function onLoad(){
// Remove the handler
var w = callerWindow || this;
un(w, "load", onLoad);
easyXDM.Fn.set(config.channel + "_load", _onLoad);
(function test(){
if (typeof w.contentWindow.sendMessage == "function") {
_onReady();
}
else {
setTimeout(test, 50);
}
}());
}
});
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.HashTransport
* HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
* @cfg {Number} interval The interval used when polling for messages.
*/
easyXDM.stack.HashTransport = function(config){
var pub;
var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
var useParent, _remoteOrigin;
function _sendMessage(message){
if (!_callerWindow) {
return;
}
var url = config.remote + "#" + (_msgNr++) + "_" + message;
((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url;
}
function _handleHash(hash){
_lastMsg = hash;
pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
}
/**
* Checks location.hash for a new message and relays this to the receiver.
* @private
*/
function _pollHash(){
if (!_listenerWindow) {
return;
}
var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#");
if (indexOf != -1) {
hash = href.substring(indexOf);
}
if (hash && hash != _lastMsg) {
_handleHash(hash);
}
}
function _attachListeners(){
_timer = setInterval(_pollHash, pollInterval);
}
return (pub = {
outgoing: function(message, domain){
_sendMessage(message);
},
destroy: function(){
window.clearInterval(_timer);
if (isHost || !useParent) {
_callerWindow.parentNode.removeChild(_callerWindow);
}
_callerWindow = null;
},
onDOMReady: function(){
isHost = config.isHost;
pollInterval = config.interval;
_lastMsg = "#" + config.channel;
_msgNr = 0;
useParent = config.useParent;
_remoteOrigin = getLocation(config.remote);
if (isHost) {
config.props = {
src: config.remote,
name: IFRAME_PREFIX + config.channel + "_provider"
};
if (useParent) {
config.onLoad = function(){
_listenerWindow = window;
_attachListeners();
pub.up.callback(true);
};
}
else {
var tries = 0, max = config.delay / 50;
(function getRef(){
if (++tries > max) {
throw new Error("Unable to reference listenerwindow");
}
try {
_listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"];
}
catch (ex) {
}
if (_listenerWindow) {
_attachListeners();
pub.up.callback(true);
}
else {
setTimeout(getRef, 50);
}
}());
}
_callerWindow = createFrame(config);
}
else {
_listenerWindow = window;
_attachListeners();
if (useParent) {
_callerWindow = parent;
pub.up.callback(true);
}
else {
apply(config, {
props: {
src: config.remote + "#" + config.channel + new Date(),
name: IFRAME_PREFIX + config.channel + "_consumer"
},
onLoad: function(){
pub.up.callback(true);
}
});
_callerWindow = createFrame(config);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.ReliableBehavior
* This is a behavior that tries to make the underlying transport reliable by using acknowledgements.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
*/
easyXDM.stack.ReliableBehavior = function(config){
var pub, // the public interface
callback; // the callback to execute when we have a confirmed success/failure
var idOut = 0, idIn = 0, currentMessage = "";
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(",");
message = message.substring(indexOf + 1);
if (ack[0] == idOut) {
currentMessage = "";
if (callback) {
callback(true);
}
}
if (message.length > 0) {
pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin);
if (idIn != ack[1]) {
idIn = ack[1];
pub.up.incoming(message, origin);
}
}
},
outgoing: function(message, origin, fn){
currentMessage = message;
callback = fn;
pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.QueueBehavior
* This is a behavior that enables queueing of messages. <br/>
* It will buffer incoming messages and dispach these as fast as the underlying transport allows.
* This will also fragment/defragment messages so that the outgoing message is never bigger than the
* set length.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration. Optional.
* @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation.
*/
easyXDM.stack.QueueBehavior = function(config){
var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false;
function dispatch(){
if (config.remove && queue.length === 0) {
removeFromStack(pub);
return;
}
if (waiting || queue.length === 0 || destroying) {
return;
}
waiting = true;
var message = queue.shift();
pub.down.outgoing(message.data, message.origin, function(success){
waiting = false;
if (message.callback) {
setTimeout(function(){
message.callback(success);
}, 0);
}
dispatch();
});
}
return (pub = {
init: function(){
if (undef(config)) {
config = {};
}
if (config.maxLength) {
maxLength = config.maxLength;
doFragment = true;
}
if (config.lazy) {
lazy = true;
}
else {
pub.down.init();
}
},
callback: function(success){
waiting = false;
var up = pub.up; // in case dispatch calls removeFromStack
dispatch();
up.callback(success);
},
incoming: function(message, origin){
if (doFragment) {
var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10);
incoming += message.substring(indexOf + 1);
if (seq === 0) {
if (config.encode) {
incoming = decodeURIComponent(incoming);
}
pub.up.incoming(incoming, origin);
incoming = "";
}
}
else {
pub.up.incoming(message, origin);
}
},
outgoing: function(message, origin, fn){
if (config.encode) {
message = encodeURIComponent(message);
}
var fragments = [], fragment;
if (doFragment) {
// fragment into chunks
while (message.length !== 0) {
fragment = message.substring(0, maxLength);
message = message.substring(fragment.length);
fragments.push(fragment);
}
// enqueue the chunks
while ((fragment = fragments.shift())) {
queue.push({
data: fragments.length + "_" + fragment,
origin: origin,
callback: fragments.length === 0 ? fn : null
});
}
}
else {
queue.push({
data: message,
origin: origin,
callback: fn
});
}
if (lazy) {
pub.down.init();
}
else {
dispatch();
}
},
destroy: function(){
destroying = true;
pub.down.destroy();
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.VerifyBehavior
* This behavior will verify that communication with the remote end is possible, and will also sign all outgoing,
* and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
* @cfg {Boolean} initiate If the verification should be initiated from this end.
*/
easyXDM.stack.VerifyBehavior = function(config){
var pub, mySecret, theirSecret, verified = false;
function startVerification(){
mySecret = Math.random().toString(16).substring(2);
pub.down.outgoing(mySecret);
}
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_");
if (indexOf === -1) {
if (message === mySecret) {
pub.up.callback(true);
}
else if (!theirSecret) {
theirSecret = message;
if (!config.initiate) {
startVerification();
}
pub.down.outgoing(message);
}
}
else {
if (message.substring(0, indexOf) === theirSecret) {
pub.up.incoming(message.substring(indexOf + 1), origin);
}
}
},
outgoing: function(message, origin, fn){
pub.down.outgoing(mySecret + "_" + message, origin, fn);
},
callback: function(success){
if (config.initiate) {
startVerification();
}
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.RpcBehavior
* This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/>
* Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything.
* @namespace easyXDM.stack
* @constructor
* @param {Object} proxy The object to apply the methods to.
* @param {Object} config The definition of the local and remote interface to implement.
* @cfg {Object} local The local interface to expose.
* @cfg {Object} remote The remote methods to expose through the proxy.
* @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON.
*/
easyXDM.stack.RpcBehavior = function(proxy, config){
var pub, serializer = config.serializer || getJSON();
var _callbackCounter = 0, _callbacks = {};
/**
* Serializes and sends the message
* @private
* @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
*/
function _send(data){
data.jsonrpc = "2.0";
pub.down.outgoing(serializer.stringify(data));
}
/**
* Creates a method that implements the given definition
* @private
* @param {Object} The method configuration
* @param {String} method The name of the method
* @return {Function} A stub capable of proxying the requested method call
*/
function _createMethod(definition, method){
var slice = Array.prototype.slice;
return function(){
var l = arguments.length, callback, message = {
method: method
};
if (l > 0 && typeof arguments[l - 1] === "function") {
//with callback, procedure
if (l > 1 && typeof arguments[l - 2] === "function") {
// two callbacks, success and error
callback = {
success: arguments[l - 2],
error: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 2);
}
else {
// single callback, success
callback = {
success: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 1);
}
_callbacks["" + (++_callbackCounter)] = callback;
message.id = _callbackCounter;
}
else {
// no callbacks, a notification
message.params = slice.call(arguments, 0);
}
if (definition.namedParams && message.params.length === 1) {
message.params = message.params[0];
}
// Send the method request
_send(message);
};
}
/**
* Executes the exposed method
* @private
* @param {String} method The name of the method
* @param {Number} id The callback id to use
* @param {Function} method The exposed implementation
* @param {Array} params The parameters supplied by the remote end
*/
function _executeMethod(method, id, fn, params){
if (!fn) {
if (id) {
_send({
id: id,
error: {
code: -32601,
message: "Procedure not found."
}
});
}
return;
}
var success, error;
if (id) {
success = function(result){
success = emptyFn;
_send({
id: id,
result: result
});
};
error = function(message, data){
error = emptyFn;
var msg = {
id: id,
error: {
code: -32099,
message: message
}
};
if (data) {
msg.error.data = data;
}
_send(msg);
};
}
else {
success = error = emptyFn;
}
// Call local method
if (!isArray(params)) {
params = [params];
}
try {
var result = fn.method.apply(fn.scope, params.concat([success, error]));
if (!undef(result)) {
success(result);
}
}
catch (ex1) {
error(ex1.message);
}
}
return (pub = {
incoming: function(message, origin){
var data = serializer.parse(message);
if (data.method) {
// A method call from the remote end
if (config.handle) {
config.handle(data, _send);
}
else {
_executeMethod(data.method, data.id, config.local[data.method], data.params);
}
}
else {
// A method response from the other end
var callback = _callbacks[data.id];
if (data.error) {
if (callback.error) {
callback.error(data.error);
}
}
else if (callback.success) {
callback.success(data.result);
}
delete _callbacks[data.id];
}
},
init: function(){
if (config.remote) {
// Implement the remote sides exposed methods
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method)) {
proxy[method] = _createMethod(config.remote[method], method);
}
}
}
pub.down.init();
},
destroy: function(){
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
delete proxy[method];
}
}
pub.down.destroy();
}
});
};
global.easyXDM = easyXDM;
})(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent);
/*!
* F2 v1.3.3 04-07-2014
* Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org
*
* "F2" is 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.
*
* Please note that F2 ("Software") may contain third party material that Markit
* On Demand Inc. has a license to use and include within the Software (the
* "Third Party Material"). A list of the software comprising the Third Party Material
* and the terms and conditions under which such Third Party Material is distributed
* are reproduced in the ThirdPartyMaterial.md file available at:
*
* https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md
*
* The inclusion of the Third Party Material in the Software does not grant, provide
* nor result in you having acquiring any rights whatsoever, other than as stipulated
* in the terms and conditions related to the specific Third Party Material, if any.
*
*/
var F2;
/**
* Open F2
* @module f2
* @main f2
*/
F2 = (function() {
/**
* Abosolutizes a relative URL
* @method _absolutizeURI
* @private
* @param {e.g., location.href} base
* @param {URL to absolutize} href
* @returns {string} URL
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _absolutizeURI = function(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = _parseURI(href || '');
base = _parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
};
/**
* Parses URI
* @method _parseURI
* @private
* @param {The URL to parse} url
* @returns {Parsed URL} string
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _parseURI = function(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
};
return {
/**
* A function to pass into F2.stringify which will prevent circular
* reference errors when serializing objects
* @method appConfigReplacer
*/
appConfigReplacer: function(key, value) {
if (key == 'root' || key == 'ui' || key == 'height') {
return undefined;
} else {
return value;
}
},
/**
* The apps namespace is a place for app developers to put the javascript
* class that is used to initialize their app. The javascript classes should
* be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId.
* It is recommended that the code be placed in a closure to help keep the
* global namespace clean.
*
* If the class has an 'init' function, that function will be called
* automatically by F2.
* @property Apps
* @type object
* @example
* F2.Apps["com_example_helloworld"] = (function() {
* var App_Class = function(appConfig, appContent, root) {
* this._app = appConfig; // the F2.AppConfig object
* this._appContent = appContent // the F2.AppManifest.AppContent object
* this.$root = $(root); // the root DOM Element that contains this app
* }
*
* App_Class.prototype.init = function() {
* // perform init actions
* }
*
* return App_Class;
* })();
* @example
* F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) {
* return {
* init:function() {
* // perform init actions
* }
* };
* };
* @for F2
*/
Apps: {},
/**
* Creates a namespace on F2 and copies the contents of an object into
* that namespace optionally overwriting existing properties.
* @method extend
* @param {string} ns The namespace to create. Pass a falsy value to
* add properties to the F2 namespace directly.
* @param {object} obj The object to copy into the namespace.
* @param {bool} overwrite True if object properties should be overwritten
* @return {object} The created object
*/
extend: function (ns, obj, overwrite) {
var isFunc = typeof obj === 'function';
var parts = ns ? ns.split('.') : [];
var parent = this;
obj = obj || {};
// ignore leading global
if (parts[0] === 'F2') {
parts = parts.slice(1);
}
// create namespaces
for (var i = 0, len = parts.length; i < len; i++) {
if (!parent[parts[i]]) {
parent[parts[i]] = isFunc && i + 1 == len ? obj : {};
}
parent = parent[parts[i]];
}
// copy object into namespace
if (!isFunc) {
for (var prop in obj) {
if (typeof parent[prop] === 'undefined' || overwrite) {
parent[prop] = obj[prop];
}
}
}
return parent;
},
/**
* Generates a somewhat random id
* @method guid
* @return {string} A random id
* @for F2
*/
guid: function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4());
},
/**
* Search for a value within an array.
* @method inArray
* @param {object} value The value to search for
* @param {Array} array The array to search
* @return {bool} True if the item is in the array
*/
inArray: function(value, array) {
return jQuery.inArray(value, array) > -1;
},
/**
* Tests a URL to see if it's on the same domain (local) or not
* @method isLocalRequest
* @param {URL to test} url
* @returns {bool} Whether the URL is local or not
* Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js
*/
isLocalRequest: function(url){
var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
urlLower = url.toLowerCase(),
parts = rurl.exec( urlLower ),
ajaxLocation,
ajaxLocParts;
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement('a');
ajaxLocation.href = '';
ajaxLocation = ajaxLocation.href;
}
ajaxLocation = ajaxLocation.toLowerCase();
// uh oh, the url must be relative
// make it fully qualified and re-regex url
if (!parts){
urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase();
parts = rurl.exec( urlLower );
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation ) || [];
// do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain)
var matched = !(parts &&
(parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
(parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !==
(ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443'))));
return matched;
},
/**
* Utility method to determine whether or not the argument passed in is or is not a native dom node.
* @method isNativeDOMNode
* @param {object} testObject The object you want to check as native dom node.
* @return {bool} Returns true if the object passed is a native dom node.
*/
isNativeDOMNode: function(testObject) {
var bIsNode = (
typeof Node === 'object' ? testObject instanceof Node :
testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string'
);
var bIsElement = (
typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2
testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string'
);
return (bIsNode || bIsElement);
},
/**
* A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console).
* @method log
* @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api).
* @param {object} [obj2]* An object to be logged
* @example
//Pass any object (string, int, array, object, bool) to .log()
F2.log('foo');
F2.log(myArray);
//Use a console method name as the first argument.
F2.log('error', err);
F2.log('info', 'The session ID is ' + sessionId);
* Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js)
*/
log: function() {
var _log;
var _logMethod = 'log';
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
var args;
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
//if first arg is a console function, use it.
//defaults to console.log()
if (arguments && arguments.length > 1 && arguments[0] == method){
_logMethod = method;
//remove console func from args
args = Array.prototype.slice.call(arguments, 1);
}
}
if (Function.prototype.bind) {
_log = Function.prototype.bind.call(console[_logMethod], console);
} else {
_log = function() {
Function.prototype.apply.call(console[_logMethod], console, (args || arguments));
};
}
_log.apply(this, (args || arguments));
},
/**
* Wrapper to convert a JSON string to an object
* @method parse
* @param {string} str The JSON string to convert
* @return {object} The parsed object
*/
parse: function(str) {
return JSON.parse(str);
},
/**
* Wrapper to convert an object to JSON
*
* **Note: When using F2.stringify on an F2.AppConfig object, it is
* recommended to pass F2.appConfigReplacer as the replacer function in
* order to prevent circular serialization errors.**
* @method stringify
* @param {object} value The object to convert
* @param {function|Array} replacer An optional parameter that determines
* how object values are stringified for objects. It can be a function or an
* array of strings.
* @param {int|string} space An optional parameter that specifies the
* indentation of nested structures. If it is omitted, the text will be
* packed without extra whitespace. If it is a number, it will specify the
* number of spaces to indent at each level. If it is a string (such as '\t'
* or ' '), it contains the characters used to indent at each level.
* @return {string} The JSON string
*/
stringify: function(value, replacer, space) {
return JSON.stringify(value, replacer, space);
},
/**
* Function to get the F2 version number
* @method version
* @return {string} F2 version number
*/
version: function() { return '1.3.3'; }
};
})();
/**
* The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction.
*
*<p class="alert alert-block alert-warning">
*The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated—but not removed—in version 1.2. They will be permanently removed in a future version of F2.
*</p>
*
*<p class="alert alert-block alert-info">
*Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout.
*</p>
*
* ### Order of Execution
*
* **App Rendering**
*
* 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed.
* 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached.
* 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached.
* 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired.
* 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached.
* 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached.
*
*
* **App Removal**
* 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run.
* 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached.
* 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached.
* 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached.
*
* **Error Handling**
* 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached.
*
* @class F2.AppHandlers
*/
F2.extend('AppHandlers', (function() {
// the hidden token that we will check against every time someone tries to add, remove, fire handler
var _ct = F2.guid();
var _f2t = F2.guid();
var _handlerCollection = {
appCreateRoot: [],
appRenderBefore: [],
appDestroyBefore: [],
appRenderAfter: [],
appDestroyAfter: [],
appRender: [],
appDestroy: [],
appScriptLoadFailed: []
};
var _defaultMethods = {
appRender: function(appConfig, appHtml)
{
var $root = null;
// if no app root is defined use the app's outer most node
if(!F2.isNativeDOMNode(appConfig.root))
{
appConfig.root = jQuery(appHtml).get(0);
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
}
else
{
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
// append the app html to the root
$root.append(appHtml);
}
// append the root to the body by default.
jQuery('body').append($root);
},
appDestroy: function(appInstance)
{
// call the apps destroy method, if it has one
if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
{
appInstance.app.destroy();
}
// warn the Container and App Developer that even though they have a destroy method it hasn't been
else if(appInstance && appInstance.app && appInstance.app.destroy)
{
F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
}
// fade out and remove the root
jQuery(appInstance.config.root).fadeOut(500, function() {
jQuery(this).remove();
});
}
};
var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(token);
// create handler structure. Not all arguments properties will be populated/used.
var handler = {
func: (typeof(func_or_element)) ? func_or_element : null,
namespace: sNamespace,
domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null
};
if(!handler.func && !handler.domNode)
{
throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.');
}
if(handler.domNode && !bDomNodeAppropriate)
{
throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.');
}
return handler;
};
var _validateToken = function(sToken)
{
// check token against F2 and container
if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); }
};
var _removeHandler = function(sToken, eventKey, sNamespace)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(sToken);
if(!sNamespace && !eventKey)
{
return;
}
// remove by event key
else if(!sNamespace && eventKey)
{
_handlerCollection[eventKey] = [];
}
// remove by namespace only
else if(sNamespace && !eventKey)
{
sNamespace = sNamespace.toLowerCase();
for(var currentEventKey in _handlerCollection)
{
var eventCollection = _handlerCollection[currentEventKey];
var newEvents = [];
for(var i = 0, ec = eventCollection.length; i < ec; i++)
{
var currentEventHandler = eventCollection[i];
if(currentEventHandler)
{
if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace)
{
newEvents.push(currentEventHandler);
}
}
}
eventCollection = newEvents;
}
}
else if(sNamespace && _handlerCollection[eventKey])
{
sNamespace = sNamespace.toLowerCase();
var newHandlerCollection = [];
for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++)
{
var currentHandler = _handlerCollection[eventKey][iCounter];
if(currentHandler)
{
if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace)
{
newHandlerCollection.push(currentHandler);
}
}
}
_handlerCollection[eventKey] = newHandlerCollection;
}
};
return {
/**
* Allows Container Developer to retrieve a unique token which must be passed to
* all `on` and `off` methods. This function will self destruct and can only be called
* one time. Container Developers must store the return value inside of a closure.
* @method getToken
**/
getToken: function()
{
// delete this method for security that way only the container has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.getToken;
// return the token, which we validate against.
return _ct;
},
/**
* Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}.
* This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}
* and additional internal methods.
* @method __f2GetToken
* @private
**/
__f2GetToken: function()
{
// delete this method for security that way only the F2 internally has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.__f2GetToken;
// return the token, which we validate against.
return _f2t;
},
/**
* Allows F2 to trigger specific events internally.
* @method __trigger
* @private
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}.
* @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
**/
__trigger: function(token, eventKey) // additional arguments will likely be passed
{
// will throw an exception and stop execution if the token is invalid
if(token != _f2t)
{
throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().');
}
if(_handlerCollection && _handlerCollection[eventKey])
{
// create a collection of arguments that are safe to pass to the callback.
var passableArgs = [];
// populate that collection with all arguments except token and eventKey
for(var i = 2, j = arguments.length; i < j; i++)
{
passableArgs.push(arguments[i]);
}
if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey])
{
_defaultMethods[eventKey].apply(F2, passableArgs);
return this;
}
else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey])
{
return this;
}
// fire all event listeners in the order that they were added.
for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++)
{
var handler = _handlerCollection[eventKey][iCounter];
// appRender where root is already defined
if (handler.domNode && arguments[2] && arguments[2].root && arguments[3])
{
var $appRoot = jQuery(arguments[2].root).append(arguments[3]);
jQuery(handler.domNode).append($appRoot);
}
else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3])
{
// set the root to the actual HTML of the app
arguments[2].root = jQuery(arguments[3]).get(0);
// appends the root to the dom node specified
jQuery(handler.domNode).append(arguments[2].root);
}
else
{
handler.func.apply(F2, passableArgs);
}
}
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {HTMLElement} element Specific DOM element to which app gets appended.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRender',
* document.getElementById('my_app')
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRender.myNamespace',
* document.getElementById('my_app')
* );
**/
/**
* Allows Container Developer to add listener method that will be triggered when a specific event occurs.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore'
* function() { F2.log('before app rendered!'); }
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore.myNamespace',
* function() { F2.log('before app rendered!'); }
* );
**/
on: function(token, eventKey, func_or_element)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_handlerCollection[eventKey].push(
_createHandler(
token,
sNamespace,
func_or_element,
(eventKey == 'appRender')
)
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to remove listener methods for specific events
* @method off
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all
* listeners for the specified event type will be removed.
* Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.off(_token,'appRenderBefore');
*
**/
off: function(token, eventKey)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_removeHandler(
token,
eventKey,
sNamespace
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
}
};
})());
F2.extend('Constants', {
/**
* A convenient collection of all available appHandler events.
* @class F2.Constants.AppHandlers
**/
AppHandlers: (function()
{
return {
/**
* Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_CREATE_ROOT
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_CREATE_ROOT,
* function(appConfig)
* {
* // If you want to create a custom root. By default F2 uses the app's outermost HTML element.
* // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER
* appConfig.root = jQuery('<section></section>').get(0);
* }
* );
*/
APP_CREATE_ROOT: 'appCreateRoot',
/**
* Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_BEFORE,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_BEFORE: 'appRenderBefore',
/**
* Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) )
* @property APP_RENDER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER,
* function(appConfig, appHtml)
* {
* var $root = null;
*
* // if no app root is defined use the app's outer most node
* if(!F2.isNativeDOMNode(appConfig.root))
* {
* appConfig.root = jQuery(appHtml).get(0);
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
* }
* else
* {
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
*
* // append the app html to the root
* $root.append(appHtml);
* }
*
* // append the root to the body by default.
* jQuery('body').append($root);
* }
* );
*/
APP_RENDER: 'appRender',
/**
* Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_AFTER,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_AFTER: 'appRenderAfter',
/**
* Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_BEFORE: 'appDestroyBefore',
/**
* Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY,
* function(appInstance)
* {
* // call the apps destroy method, if it has one
* if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
* {
* appInstance.app.destroy();
* }
* else if(appInstance && appInstance.app && appInstance.app.destroy)
* {
* F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
* }
*
* // fade out and remove the root
* jQuery(appInstance.config.root).fadeOut(500, function() {
* jQuery(this).remove();
* });
* }
* );
*/
APP_DESTROY: 'appDestroy',
/**
* Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_AFTER,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_AFTER: 'appDestroyAfter',
/**
* Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo )
* @property APP_SCRIPT_LOAD_FAILED
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
* function(appConfig, scriptInfo)
* {
* F2.log(appConfig.appId);
* }
* );
*/
APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed'
};
})()
});
/**
* Class stubs for documentation purposes
* @main F2
*/
F2.extend('', {
/**
* The App Class is an optional class that can be namespaced onto the
* {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
* [F2 Docs](../../app-development.html#app-class)
* has more information on the usage of the App Class.
* @class F2.App
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object for the app
* @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent
* object
* @param {Element} root The root DOM Element for the app
*/
App: function(appConfig, appContent, root) {
return {
/**
* An optional init function that will automatically be called when
* F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called.
* @method init
* @optional
*/
init:function() {}
};
},
/**
* The AppConfig object represents an app's meta data
* @class F2.AppConfig
*/
AppConfig: {
/**
* The unique ID of the app. More information can be found
* [here](../../app-development.html#f2-appid)
* @property appId
* @type string
* @required
*/
appId: '',
/**
* An object that represents the context of an app
* @property context
* @type object
*/
context: {},
/**
* True if the app should be requested in a single request with other apps.
* @property enableBatchRequests
* @type bool
* @default false
*/
enableBatchRequests: false,
/**
* The height of the app. The initial height will be pulled from
* the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later
* modified by calling
* F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used
* for secure apps to be able to set the initial height of the iframe.
* @property height
* @type int
*/
height: 0,
/**
* The unique runtime ID of the app.
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property instanceId
* @type string
*/
instanceId: '',
/**
* True if the app will be loaded in an iframe. This property
* will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object
* sets isSecure = true. It will also be true if the
* [container](../../container-development.html) has made the decision to
* run apps in iframes.
* @property isSecure
* @type bool
* @default false
*/
isSecure: false,
/**
* The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* object.
* @property manifestUrl
* @type string
* @required
*/
manifestUrl: '',
/**
* The recommended maximum width in pixels that this app should be run.
* **It is up to the [container](../../container-development.html) to
* implement the logic to prevent an app from being run when the maxWidth
* requirements are not met.**
* @property maxWidth
* @type int
*/
maxWidth: 0,
/**
* The recommended minimum grid size that this app should be run. This
* value corresponds to the 12-grid system that is used by the
* [container](../../container-development.html). This property should be
* set by apps that require a certain number of columns in their layout.
* @property minGridSize
* @type int
* @default 4
*/
minGridSize: 4,
/**
* The recommended minimum width in pixels that this app should be run. **It
* is up to the [container](../../container-development.html) to implement
* the logic to prevent an app from being run when the minWidth requirements
* are not met.
* @property minWidth
* @type int
* @default 300
*/
minWidth: 300,
/**
* The name of the app
* @property name
* @type string
* @required
*/
name: '',
/**
* The root DOM element that contains the app
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property root
* @type Element
*/
root: undefined,
/**
* The instance of F2.UI providing easy access to F2.UI methods
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property ui
* @type F2.UI
*/
ui: undefined,
/**
* The views that this app supports. Available views
* are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The
* presence of a view can be checked via
* F2.{{#crossLink "F2/inArray"}}{{/crossLink}}:
*
* F2.inArray(F2.Constants.Views.SETTINGS, app.views)
*
* @property views
* @type Array
*/
views: []
},
/**
* The assets needed to render an app on the page
* @class F2.AppManifest
*/
AppManifest: {
/**
* The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}}
* objects
* @property apps
* @type Array
* @required
*/
apps: [],
/**
* Any inline javascript tha should initially be run
* @property inlineScripts
* @type Array
* @optional
*/
inlineScripts: [],
/**
* Urls to javascript files required by the app
* @property scripts
* @type Array
* @optional
*/
scripts: [],
/**
* Urls to CSS files required by the app
* @property styles
* @type Array
* @optional
*/
styles: []
},
/**
* The AppContent object
* @class F2.AppManifest.AppContent
**/
AppContent: {
/**
* Arbitrary data to be passed along with the app
* @property data
* @type object
* @optional
*/
data: {},
/**
* The string of HTML representing the app
* @property html
* @type string
* @required
*/
html: '',
/**
* A status message
* @property status
* @type string
* @optional
*/
status: ''
},
/**
* An object containing configuration information for the
* [container](../../container-development.html)
* @class F2.ContainerConfig
*/
ContainerConfig: {
/**
* Allows the [container](../../container-development.html) to override how
* an app's html is inserted into the page. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html
* @method afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
* @return {Element} The DOM Element surrounding the app
*/
afterAppRender: function(appConfig, html) {},
/**
* Allows the [container](../../container-development.html) to wrap an app
* in extra html. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html. The extra html can provide links to edit app settings and remove an
* app from the container. See
* {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that
* should be applied to elements.
* @method appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
*/
appRender: function(appConfig, html) {},
/**
* Allows the container to render html for an app before the AppManifest for
* an app has loaded. This can be useful if the design calls for loading
* icons to appear for each app before each app is loaded and rendered to
* the page.
* @method beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
beforeAppRender: function(appConfig) {},
/**
* True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc.
* @property debugMode
* @type bool
* @default false
*/
debugMode: false,
/**
* Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire.
* @property scriptErrorTimeout
* @type milliseconds
* @default 7000 (7 seconds)
*/
scriptErrorTimeout: 7000,
/**
* Tells the container that it is currently running within
* a secure app page
* @property isSecureAppPage
* @type bool
*/
isSecureAppPage: false,
/**
* Allows the container to specify which page is used when
* loading a secure app. The page must reside on a different domain than the
* container
* @property secureAppPagePath
* @type string
* @for F2.ContainerConfig
*/
secureAppPagePath: '',
/**
* Specifies what views a container will provide buttons
* or links to. Generally, the views will be switched via buttons or links
* in the app's header.
* @property supportedViews
* @type Array
* @required
*/
supportedViews: [],
/**
* An object containing configuration defaults for F2.UI
* @class F2.ContainerConfig.UI
*/
UI: {
/**
* An object containing configuration defaults for the
* F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and
* F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods.
* @class F2.ContainerConfig.UI.Mask
*/
Mask: {
/**
* The backround color of the overlay
* @property backgroundColor
* @type string
* @default #FFF
*/
backgroundColor: '#FFF',
/**
* The path to the loading icon
* @property loadingIcon
* @type string
*/
loadingIcon: '',
/**
* The opacity of the background overlay
* @property opacity
* @type int
* @default 0.6
*/
opacity: 0.6,
/**
* Do not use inline styles for mask functinality. Instead classes will
* be applied to the elements and it is up to the container provider to
* implement the class definitions.
* @property useClasses
* @type bool
* @default false
*/
useClasses: false,
/**
* The z-index to use for the overlay
* @property zIndex
* @type int
* @default 2
*/
zIndex: 2
}
},
/**
* Allows the container to fully override how the AppManifest request is
* made inside of F2.
*
* @method xhr
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {function} success The function to be called if the request
* succeeds
* @param {function} error The function to be called if the request fails
* @param {function} complete The function to be called when the request
* finishes (after success and error callbacks have been executed)
* @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has
* an `abort` function (such as the jqXHR object in jQuery) to abort the
* request)
*
* @example
* F2.init({
* xhr: function(url, appConfigs, success, error, complete) {
* $.ajax({
* url: url,
* type: 'POST',
* data: {
* params: F2.stringify(appConfigs, F2.appConfigReplacer)
* },
* jsonp: false, // do not put 'callback=' in the query string
* jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name
* dataType: 'json',
* success: function(appManifest) {
* // custom success logic
* success(appManifest); // fire success callback
* },
* error: function() {
* // custom error logic
* error(); // fire error callback
* },
* complete: function() {
* // custom complete logic
* complete(); // fire complete callback
* }
* });
* }
* });
*
* @for F2.ContainerConfig
*/
//xhr: function(url, appConfigs, success, error, complete) {},
/**
* Allows the container to override individual parts of the AppManifest
* request. See properties and methods with the `xhr.` prefix.
* @property xhr
* @type Object
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
xhr: {
/**
* Allows the container to override the request data type (JSON or JSONP)
* that is used for the request
* @method xhr.dataType
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request data type that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
dataType: function(url, appConfigs) {},
/**
* Allows the container to override the request method that is used (just
* like the `type` parameter to `jQuery.ajax()`.
* @method xhr.type
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request method that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
type: function(url, appConfigs) {},
/**
* Allows the container to override the url that is used to request an
* app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}}
* @method xhr.url
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The url that should be used for the request
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
url: function(url, appConfigs) {}
},
/**
* Allows the container to override the script loader which requests
* dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}.
* @property loadScripts
* @type function
*
* @example
* F2.init({
* loadScripts: function(scripts,inlines,callback){
* //load scripts using $.load() for each script or require(scripts)
* callback();
* }
* });
*/
loadScripts: function(scripts,inlines,callback){},
/**
* Allows the container to override the stylesheet loader which requests
* dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}.
* @property loadStyles
* @type function
*
* @example
* F2.init({
* loadStyles: function(styles,callback){
* //load styles using $.load() for each stylesheet or another method
* callback();
* }
* });
*/
loadStyles: function(styles,callback){}
}
});
/**
* Constants used throughout the Open Financial Framework
* @class F2.Constants
* @static
*/
F2.extend('Constants', {
/**
* CSS class constants
* @class F2.Constants.Css
*/
Css: (function() {
/** @private */
var _PREFIX = 'f2-';
return {
/**
* The APP class should be applied to the DOM Element that surrounds the
* entire app, including any extra html that surrounds the APP\_CONTAINER
* that is inserted by the container. See the
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object.
* @property APP
* @type string
* @static
* @final
*/
APP: _PREFIX + 'app',
/**
* The APP\_CONTAINER class should be applied to the outermost DOM Element
* of the app.
* @property APP_CONTAINER
* @type string
* @static
* @final
*/
APP_CONTAINER: _PREFIX + 'app-container',
/**
* The APP\_TITLE class should be applied to the DOM Element that contains
* the title for an app. If this class is not present, then
* F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function.
* @property APP_TITLE
* @type string
* @static
* @final
*/
APP_TITLE: _PREFIX + 'app-title',
/**
* The APP\_VIEW class should be applied to the DOM Element that contains
* a view for an app. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is.
* @property APP_VIEW
* @type string
* @static
* @final
*/
APP_VIEW: _PREFIX + 'app-view',
/**
* APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that
* trigger an
* {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE
* event. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger.
* @property APP_VIEW_TRIGGER
* @type string
* @static
* @final
*/
APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger',
/**
* The MASK class is applied to the overlay element that is created
* when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is
* fired.
* @property MASK
* @type string
* @static
* @final
*/
MASK: _PREFIX + 'mask',
/**
* The MASK_CONTAINER class is applied to the Element that is passed into
* the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method.
* @property MASK_CONTAINER
* @type string
* @static
* @final
*/
MASK_CONTAINER: _PREFIX + 'mask-container'
};
})(),
/**
* Events constants
* @class F2.Constants.Events
*/
Events: (function() {
/** @private */
var _APP_EVENT_PREFIX = 'App.';
/** @private */
var _CONTAINER_EVENT_PREFIX = 'Container.';
return {
/**
* The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an
* app. It is up to the app developer to fire this event.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property APP_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange',
/**
* The APP\_WIDTH\_CHANGE event will be fired by the container when the
* width of an app is changed. The app's instanceId should be concatenated
* to this constant.
* Returns an object with the gridSize and width in pixels:
*
* { gridSize:8, width:620 }
*
* @property APP_WIDTH_CHANGE
* @type string
* @static
* @final
*/
APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.',
/**
* The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed
* at the container level. This event should only be fired by the
* container or container provider.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property CONTAINER_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange',
/**
* The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when
* the width of the container has changed.
* @property CONTAINER_WIDTH_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange'
};
})(),
JSONP_CALLBACK: 'F2_jsonpCallback_',
/**
* Constants for use with cross-domain sockets
* @class F2.Constants.Sockets
* @protected
*/
Sockets: {
/**
* The EVENT message is sent whenever
* F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired
* @property EVENT
* @type string
* @static
* @final
*/
EVENT: '__event__',
/**
* The LOAD message is sent when an iframe socket initially loads.
* Returns a JSON string that represents:
*
* [ App, AppManifest]
*
* @property LOAD
* @type string
* @static
* @final
*/
LOAD: '__socketLoad__',
/**
* The RPC message is sent when a method is passed up from within a secure
* app page.
* @property RPC
* @type string
* @static
* @final
*/
RPC: '__rpc__',
/**
* The RPC\_CALLBACK message is sent when a call back from an RPC method is
* fired.
* @property RPC_CALLBACK
* @type string
* @static
* @final
*/
RPC_CALLBACK: '__rpcCallback__',
/**
* The UI\_RPC message is sent when a UI method called.
* @property UI_RPC
* @type string
* @static
* @final
*/
UI_RPC: '__uiRpc__'
},
/**
* The available view types to apps. The view should be specified by applying
* the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the
* containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the
* Element as well which defines what view type is represented.
* The `hide` class can be applied to views that should be hidden by default.
* @class F2.Constants.Views
*/
Views: {
/**
* The DATA_ATTRIBUTE should be placed on the DOM Element that contains the
* view.
* @property DATA_ATTRIBUTE
* @type string
* @static
* @final
*/
DATA_ATTRIBUTE: 'data-f2-view',
/**
* The ABOUT view gives details about the app.
* @property ABOUT
* @type string
* @static
* @final
*/
ABOUT: 'about',
/**
* The HELP view provides users with help information for using an app.
* @property HELP
* @type string
* @static
* @final
*/
HELP: 'help',
/**
* The HOME view is the main view for an app. This view should always
* be provided by an app.
* @property HOME
* @type string
* @static
* @final
*/
HOME: 'home',
/**
* The REMOVE view is a special view that handles the removal of an app
* from the container.
* @property REMOVE
* @type string
* @static
* @final
*/
REMOVE: 'remove',
/**
* The SETTINGS view provides users the ability to modify advanced settings
* for an app.
* @property SETTINGS
* @type string
* @static
* @final
*/
SETTINGS: 'settings'
}
});
/**
* Handles [Context](../../app-development.html#context) passing from
* containers to apps and apps to apps.
* @class F2.Events
*/
F2.extend('Events', (function() {
// init EventEmitter
var _events = new EventEmitter2({
wildcard:true
});
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
return {
/**
* Same as F2.Events.emit except that it will not send the event
* to all sockets.
* @method _socketEmit
* @private
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
_socketEmit: function() {
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Execute each of the listeners that may be listening for the specified
* event name in order with the list of arguments.
* @method emit
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
emit: function() {
F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments));
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Adds a listener that will execute n times for the event before being
* removed. The listener is invoked only the first time the event is
* fired, after which it is removed.
* @method many
* @param {string} event The event name
* @param {int} timesToListen The number of times to execute the event
* before being removed
* @param {function} listener The function to be fired when the event is
* emitted
*/
many: function(event, timesToListen, listener) {
return _events.many(event, timesToListen, listener);
},
/**
* Remove a listener for the specified event.
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
*/
off: function(event, listener) {
return _events.off(event, listener);
},
/**
* Adds a listener for the specified event
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
on: function(event, listener){
return _events.on(event, listener);
},
/**
* Adds a one time listener for the event. The listener is invoked only
* the first time the event is fired, after which it is removed.
* @method once
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
once: function(event, listener) {
return _events.once(event, listener);
}
};
})());
/**
* Handles socket communication between the container and secure apps
* @class F2.Rpc
*/
F2.extend('Rpc', (function(){
var _callbacks = {};
var _secureAppPagePath = '';
var _apps = {};
var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT);
var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC);
var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK);
var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD);
var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC);
/**
* Creates a socket connection from the app to the container using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createAppToContainerSocket
* @private
*/
var _createAppToContainerSocket = function() {
var appConfig; // socket closure
var isLoaded = false;
// its possible for messages to be received before the socket load event has
// happened. We'll save off these messages and replay them once the socket
// is ready
var messagePlayback = [];
var socket = new easyXDM.Socket({
onMessage: function(message, origin){
// handle Socket Load
if (!isLoaded && _rSocketLoad.test(message)) {
message = message.replace(_rSocketLoad, '');
var appParts = F2.parse(message);
// make sure we have the AppConfig and AppManifest
if (appParts.length == 2) {
appConfig = appParts[0];
// save socket
_apps[appConfig.instanceId] = {
config:appConfig,
socket:socket
};
// register app
F2.registerApps([appConfig], [appParts[1]]);
// socket message playback
jQuery.each(messagePlayback, function(i, e) {
_onMessage(appConfig, message, origin);
});
isLoaded = true;
}
} else if (isLoaded) {
// pass everyting else to _onMessage
_onMessage(appConfig, message, origin);
} else {
//F2.log('socket not ready, queuing message', message);
messagePlayback.push(message);
}
}
});
};
/**
* Creates a socket connection from the container to the app using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createContainerToAppSocket
* @private
* @param {appConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The F2.AppManifest object
*/
var _createContainerToAppSocket = function(appConfig, appManifest) {
var container = jQuery(appConfig.root);
if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) {
container.find('.' + F2.Constants.Css.APP_CONTAINER);
}
if (!container.length) {
F2.log('Unable to locate app in order to establish secure connection.');
return;
}
var iframeProps = {
scrolling:'no',
style:{
width:'100%'
}
};
if (appConfig.height) {
iframeProps.style.height = appConfig.height + 'px';
}
var socket = new easyXDM.Socket({
remote: _secureAppPagePath,
container: container.get(0),
props:iframeProps,
onMessage: function(message, origin) {
// pass everything to _onMessage
_onMessage(appConfig, message, origin);
},
onReady: function() {
socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer));
}
});
return socket;
};
/**
* @method _createRpcCallback
* @private
* @param {string} instanceId The app's Instance ID
* @param {function} callbackId The callback ID
* @return {function} A function to make the RPC call
*/
var _createRpcCallback = function(instanceId, callbackId) {
return function() {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC_CALLBACK,
callbackId,
[].slice.call(arguments).slice(2)
);
};
};
/**
* Handles messages that come across the sockets
* @method _onMessage
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} message The socket message
* @param {string} origin The originator
*/
var _onMessage = function(appConfig, message, origin) {
var obj, func;
function parseFunction(parent, functionName) {
var path = String(functionName).split('.');
for (var i = 0; i < path.length; i++) {
if (parent[path[i]] === undefined) {
parent = undefined;
break;
}
parent = parent[path[i]];
}
return parent;
}
function parseMessage(regEx, message, instanceId) {
var o = F2.parse(message.replace(regEx, ''));
// if obj.callbacks
// for each callback
// for each params
// if callback matches param
// replace param with _createRpcCallback(app.instanceId, callback)
if (o.params && o.params.length && o.callbacks && o.callbacks.length) {
jQuery.each(o.callbacks, function(i, c) {
jQuery.each(o.params, function(i, p) {
if (c == p) {
o.params[i] = _createRpcCallback(instanceId, c);
}
});
});
}
return o;
}
// handle UI Call
if (_rUiCall.test(message)) {
obj = parseMessage(_rUiCall, message, appConfig.instanceId);
func = parseFunction(appConfig.ui, obj.functionName);
// if we found the function, call it
if (func !== undefined) {
func.apply(appConfig.ui, obj.params);
} else {
F2.log('Unable to locate UI RPC function: ' + obj.functionName);
}
// handle RPC
} else if (_rRpc.test(message)) {
obj = parseMessage(_rRpc, message, appConfig.instanceId);
func = parseFunction(window, obj.functionName);
if (func !== undefined) {
func.apply(func, obj.params);
} else {
F2.log('Unable to locate RPC function: ' + obj.functionName);
}
// handle RPC Callback
} else if (_rRpcCallback.test(message)) {
obj = parseMessage(_rRpcCallback, message, appConfig.instanceId);
if (_callbacks[obj.functionName] !== undefined) {
_callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params);
delete _callbacks[obj.functionName];
}
// handle Events
} else if (_rEvents.test(message)) {
obj = parseMessage(_rEvents, message, appConfig.instanceId);
F2.Events._socketEmit.apply(F2.Events, obj);
}
};
/**
* Registers a callback function
* @method _registerCallback
* @private
* @param {function} callback The callback function
* @return {string} The callback ID
*/
var _registerCallback = function(callback) {
var callbackId = F2.guid();
_callbacks[callbackId] = callback;
return callbackId;
};
return {
/**
* Broadcast an RPC function to all sockets
* @method broadcast
* @param {string} messageType The message type
* @param {Array} params The parameters to broadcast
*/
broadcast: function(messageType, params) {
// check valid messageType
var message = messageType + F2.stringify(params);
jQuery.each(_apps, function(i, a) {
a.socket.postMessage(message);
});
},
/**
* Calls a remote function
* @method call
* @param {string} instanceId The app's Instance ID
* @param {string} messageType The message type
* @param {string} functionName The name of the remote function
* @param {Array} params An array of parameters to pass to the remote
* function. Any functions found within the params will be treated as a
* callback function.
*/
call: function(instanceId, messageType, functionName, params) {
// loop through params and find functions and convert them to callbacks
var callbacks = [];
jQuery.each(params, function(i, e) {
if (typeof e === 'function') {
var cid = _registerCallback(e);
params[i] = cid;
callbacks.push(cid);
}
});
// check valid messageType
_apps[instanceId].socket.postMessage(
messageType + F2.stringify({
functionName:functionName,
params:params,
callbacks:callbacks
})
);
},
/**
* Init function which tells F2.Rpc whether it is running at the container-
* level or the app-level. This method is generally called by
* F2.{{#crossLink "F2/init"}}{{/crossLink}}
* @method init
* @param {string} [secureAppPagePath] The
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath
* property
*/
init: function(secureAppPagePath) {
_secureAppPagePath = secureAppPagePath;
if (!_secureAppPagePath) {
_createAppToContainerSocket();
}
},
/**
* Determines whether the Instance ID is considered to be 'remote'. This is
* determined by checking if 1) the app has an open socket and 2) whether
* F2.Rpc is running inside of an iframe
* @method isRemote
* @param {string} instanceId The Instance ID
* @return {bool} True if there is an open socket
*/
isRemote: function(instanceId) {
return (
// we have an app
_apps[instanceId] !== undefined &&
// the app is secure
_apps[instanceId].config.isSecure &&
// we can't access the iframe
jQuery(_apps[instanceId].config.root).find('iframe').length === 0
);
},
/**
* Creates a container-to-app or app-to-container socket for communication
* @method register
* @param {F2.AppConfig} [appConfig] The F2.AppConfig object
* @param {F2.AppManifest} [appManifest] The F2.AppManifest object
*/
register: function(appConfig, appManifest) {
if (!!appConfig && !!appManifest) {
_apps[appConfig.instanceId] = {
config:appConfig,
socket:_createContainerToAppSocket(appConfig, appManifest)
};
} else {
F2.log('Unable to register socket connection. Please check container configuration.');
}
}
};
})());
F2.extend('UI', (function(){
var _containerConfig;
/**
* UI helper methods
* @class F2.UI
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object
*/
var UI_Class = function(appConfig) {
var _appConfig = appConfig;
var $root = jQuery(appConfig.root);
var _updateHeight = function(height) {
height = height || jQuery(_appConfig.root).outerHeight();
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'updateHeight',
[
height
]
);
} else {
_appConfig.height = height;
$root.find('iframe').height(_appConfig.height);
}
};
return {
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
*/
hideMask: function(selector) {
F2.UI.hideMask(_appConfig.instanceId, selector);
},
/**
* Helper methods for creating and using Modals
* @class F2.UI.Modals
* @for F2.UI
*/
Modals: (function(){
var _renderAlert = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Alert!</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button class="btn btn-primary btn-ok">OK</button>',
'</div>',
'</div>'
].join('');
};
var _renderConfirm = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Confirm</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-primary btn-ok">OK</button>',
'<button type="button" class="btn btn-cancel">Cancel</button">',
'</div>',
'</div>'
].join('');
};
return {
/**
* Display an alert message on the page
* @method alert
* @param {string} message The message to be displayed
* @param {function} [callback] The callback to be fired when the user
* closes the dialog
* @for F2.UI.Modals
*/
alert: function(message, callback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.alert()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.alert',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderAlert(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-primary').on('click', function() {
jQuery(modal).modal('hide').remove();
(callback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
},
/**
* Display a confirm message on the page
* @method confirm
* @param {string} message The message to be displayed
* @param {function} okCallback The function that will be called when the OK
* button is pressed
* @param {function} cancelCallback The function that will be called when
* the Cancel button is pressed
* @for F2.UI.Modals
*/
confirm: function(message, okCallback, cancelCallback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.confirm()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.confirm',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderConfirm(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-ok').on('click', function() {
jQuery(modal).modal('hide').remove();
(okCallback || jQuery.noop)();
});
jQuery(modal).find('.btn-cancel').on('click', function() {
jQuery(modal).modal('hide').remove();
(cancelCallback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
}
};
})(),
/**
* Sets the title of the app as shown in the browser. Depending on the
* container HTML, this method may do nothing if the container has not been
* configured properly or else the container provider does not allow Title's
* to be set.
* @method setTitle
* @params {string} title The title of the app
* @for F2.UI
*/
setTitle: function(title) {
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'setTitle',
[
title
]
);
} else {
jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title);
}
},
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
showMask: function(selector, showLoader) {
F2.UI.showMask(_appConfig.instanceId, selector, showLoader);
},
/**
* For secure apps, this method updates the size of the iframe that
* contains the app. **Note: It is recommended that app developers call
* this method anytime Elements are added or removed from the DOM**
* @method updateHeight
* @params {int} height The height of the app
*/
updateHeight: _updateHeight,
/**
* Helper methods for creating and using Views
* @class F2.UI.Views
* @for F2.UI
*/
Views: (function(){
var _events = new EventEmitter2();
var _rValidEvents = /change/i;
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
var _isValid = function(eventName) {
if (_rValidEvents.test(eventName)) {
return true;
} else {
F2.log('"' + eventName + '" is not a valid F2.UI.Views event name');
return false;
}
};
return {
/**
* Change the current view for the app or add an event listener
* @method change
* @param {string|function} [input] If a string is passed in, the view
* will be changed for the app. If a function is passed in, a change
* event listener will be added.
* @for F2.UI.Views
*/
change: function(input) {
if (typeof input === 'function') {
this.on('change', input);
} else if (typeof input === 'string') {
if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Views.change',
[].slice.call(arguments)
);
} else if (F2.inArray(input, _appConfig.views)) {
jQuery('.' + F2.Constants.Css.APP_VIEW, $root)
.addClass('hide')
.filter('[data-f2-view="' + input + '"]', $root)
.removeClass('hide');
_updateHeight();
_events.emit('change', input);
}
}
},
/**
* Removes a view event listener
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
* @for F2.UI.Views
*/
off: function(event, listener) {
if (_isValid(event)) {
_events.off(event, listener);
}
},
/**
* Adds a view event listener
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
* @for F2.UI.Views
*/
on: function(event, listener) {
if (_isValid(event)) {
_events.on(event, listener);
}
}
};
})()
};
};
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
* @for F2.UI
*/
UI_Class.hideMask = function(instanceId, selector) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.hideMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.hideMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector
]
);
} else {
var container = jQuery(selector);
container.find('> .' + F2.Constants.Css.MASK).remove();
container.removeClass(F2.Constants.Css.MASK_CONTAINER);
// if the element contains this data property, we need to reset static
// position
if (container.data(F2.Constants.Css.MASK_CONTAINER)) {
container.css({'position':'static'});
}
}
};
/**
*
* @method init
* @static
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
UI_Class.init = function(containerConfig) {
_containerConfig = containerConfig;
// set defaults
_containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {});
};
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
UI_Class.showMask = function(instanceId, selector, showLoading) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.showMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.showMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector,
showLoading
]
);
} else {
if (showLoading && !_containerConfig.UI.Mask.loadingIcon) {
F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();');
}
var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER);
var mask = jQuery('<div>')
.height('100%' /*container.outerHeight()*/)
.width('100%' /*container.outerWidth()*/)
.addClass(F2.Constants.Css.MASK);
// set inline styles if useClasses is false
if (!_containerConfig.UI.Mask.useClasses) {
mask.css({
'background-color':_containerConfig.UI.Mask.backgroundColor,
'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '',
'background-position':'50% 50%',
'background-repeat':'no-repeat',
'display':'block',
'left':0,
'min-height':30,
'padding':0,
'position':'absolute',
'top':0,
'z-index':_containerConfig.UI.Mask.zIndex,
'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')',
'opacity':_containerConfig.UI.Mask.opacity
});
}
// only set the position if the container is currently static
if (container.css('position') === 'static') {
container.css({'position':'relative'});
// setting this data property tells hideMask to set the position
// back to static
container.data(F2.Constants.Css.MASK_CONTAINER, true);
}
// add the mask to the container
container.append(mask);
}
};
return UI_Class;
})());
/**
* Root namespace of the F2 SDK
* @module f2
* @class F2
*/
F2.extend('', (function() {
var _apps = {};
var _config = false;
var _bUsesAppHandlers = false;
var _sAppHandlerToken = F2.AppHandlers.__f2GetToken();
/**
* Appends the app's html to the DOM
* @method _afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
* @return {Element} The DOM Element that contains the app
*/
var _afterAppRender = function(appConfig, html) {
var handler = _config.afterAppRender || function(appConfig, html) {
return jQuery(html).appendTo('body');
};
var appContainer = handler(appConfig, html);
if ( !! _config.afterAppRender && !appContainer) {
F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app');
return;
}
else {
// apply APP class and Instance ID
jQuery(appContainer).addClass(F2.Constants.Css.APP);
return appContainer.get(0);
}
};
/**
* Renders the html for an app.
* @method _appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
*/
var _appRender = function(appConfig, html) {
// apply APP_CONTAINER class
html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId));
// optionally apply wrapper html
if (_config.appRender) {
html = _config.appRender(appConfig, html);
}
// apply APP class and instanceId
return _outerHtml(html);
};
/**
* Rendering hook to allow containers to render some html prior to an app
* loading
* @method _beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
var _beforeAppRender = function(appConfig) {
var handler = _config.beforeAppRender || jQuery.noop;
return handler(appConfig);
};
/**
* Handler to inform the container that a script failed to load
* @method _onScriptLoadFailure
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param scriptInfo The path of the script that failed to load or the exception info
* for the inline script that failed to execute
*/
var _appScriptLoadFailed = function(appConfig, scriptInfo) {
var handler = _config.appScriptLoadFailed || jQuery.noop;
return handler(appConfig, scriptInfo);
};
/**
* Adds properties to the AppConfig object
* @method _createAppConfig
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with
* necessary properties
*/
var _createAppConfig = function(appConfig) {
// make a copy of the app config to ensure that the original is not modified
appConfig = jQuery.extend(true, {}, appConfig);
// create the instanceId for the app
appConfig.instanceId = appConfig.instanceId || F2.guid();
// default the views if not provided
appConfig.views = appConfig.views || [];
if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) {
appConfig.views.push(F2.Constants.Views.HOME);
}
return appConfig;
};
/**
* Adds properties to the ContainerConfig object to take advantage of defaults
* @method _hydrateContainerConfig
* @private
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
var _hydrateContainerConfig = function(containerConfig) {
if (!containerConfig.scriptErrorTimeout) {
containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout;
}
if (containerConfig.debugMode !== true) {
containerConfig.debugMode = F2.ContainerConfig.debugMode;
}
};
/**
* Attach app events
* @method _initAppEvents
* @private
*/
var _initAppEvents = function(appConfig) {
jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) {
event.preventDefault();
var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();
// handle the special REMOVE view
if (view == F2.Constants.Views.REMOVE) {
F2.removeApp(appConfig.instanceId);
}
else {
appConfig.ui.Views.change(view);
}
});
};
/**
* Attach container Events
* @method _initContainerEvents
* @private
*/
var _initContainerEvents = function() {
var resizeTimeout;
var resizeHandler = function() {
F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE);
};
jQuery(window).on('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeHandler, 100);
});
};
/**
* Has the container been init?
* @method _isInit
* @private
* @return {bool} True if the container has been init
*/
var _isInit = function() {
return !!_config;
};
/**
* Instantiates each app from it's appConfig and stores that in a local private collection
* @method _createAppInstance
* @private
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
*/
var _createAppInstance = function(appConfig, appContent) {
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// instantiate F2.App
if (F2.Apps[appConfig.appId] !== undefined) {
if (typeof F2.Apps[appConfig.appId] === 'function') {
// IE
setTimeout(function() {
_apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root);
if (_apps[appConfig.instanceId].app['init'] !== undefined) {
_apps[appConfig.instanceId].app.init();
}
}, 0);
}
else {
F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')');
}
}
};
/**
* Loads the app's html/css/javascript
* @method loadApp
* @private
* @param {Array} appConfigs An array of
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
* @param {F2.AppManifest} [appManifest] The AppManifest object
*/
var _loadApps = function(appConfigs, appManifest) {
appConfigs = [].concat(appConfigs);
// check for secure app
if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) {
_loadSecureApp(appConfigs[0], appManifest);
return;
}
// check that the number of apps in manifest matches the number requested
if (appConfigs.length != appManifest.apps.length) {
F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest);
return;
}
// Fn for loading manifest Styles
var _loadStyles = function(styles, cb) {
// Attempt to use the user provided method
if (_config.loadStyles) {
_config.loadStyles(styles, cb);
}
else {
// load styles, see #101
var stylesFragment = null,
useCreateStyleSheet = !! document.createStyleSheet;
jQuery.each(styles, function(i, e) {
if (useCreateStyleSheet) {
document.createStyleSheet(e);
}
else {
stylesFragment = stylesFragment || [];
stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>');
}
});
if (stylesFragment) {
jQuery('head').append(stylesFragment.join(''));
}
cb();
}
};
// Fn for loading manifest Scripts
var _loadScripts = function(scripts, cb) {
// Attempt to use the user provided method
if (_config.loadScripts) {
_config.loadScripts(scripts, cb);
}
else {
if (scripts.length) {
var scriptCount = scripts.length;
var scriptsLoaded = 0;
// Check for IE10+ so that we don't rely on onreadystatechange
var readyStates = ('addEventListener' in window) ? {} : {
'loaded': true,
'complete': true
};
// Log and emit event for the failed (400,500) scripts
var _error = function(e) {
setTimeout(function() {
var evtData = {
src: e.target.src,
appId: appConfigs[0].appId
};
// Send error to console
F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\'');
// Emit event
F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData);
if (!_bUsesAppHandlers) {
_appScriptLoadFailed(appConfigs[0], evtData.src);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
appConfigs[0],
evtData.src
);
}
}, _config.scriptErrorTimeout); // Defaults to 7000
};
// Load scripts and eval inlines once complete
jQuery.each(scripts, function(i, e) {
var doc = document,
script = doc.createElement('script'),
resourceUrl = e;
// If in debugMode, add cache buster to each script URL
if (_config.debugMode) {
resourceUrl += '?cachebuster=' + new Date().getTime();
}
// Scripts needed to be loaded in order they're defined in the AppManifest
script.async = false;
// Add other attrs
script.src = resourceUrl;
script.type = 'text/javascript';
script.charset = 'utf-8';
script.onerror = _error;
// Use a closure for the load event so that we can dereference the original script
script.onload = script.onreadystatechange = function(e) {
e = e || window.event; // For older IE
if (e.type == 'load' || readyStates[script.readyState]) {
// Done, cleanup
script.onload = script.onreadystatechange = script.onerror = null;
// Dereference script
script = null;
// Are we done loading all scripts for this app?
if (++scriptsLoaded === scriptCount) {
cb();
}
}
};
doc.body.appendChild(script);
});
}
else {
cb();
}
}
};
var _loadInlineScripts = function(inlines, cb) {
// Attempt to use the user provided method
if (_config.loadInlineScripts) {
_config.loadInlineScripts(inlines, cb);
}
else {
for (var i = 0, len = inlines.length; i < len; i++) {
try {
eval(inlines[i]);
}
catch (exception) {
F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]);
if (!_bUsesAppHandlers) {
_appScriptLoadFailed(appConfigs[0], exception);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
appConfigs[0],
exception
);
}
}
}
cb();
}
};
// Determine whether an element has been added to the page
var elementInDocument = function(element) {
if (element) {
while (element.parentNode) {
element = element.parentNode;
if (element === document) {
return true;
}
}
}
return false;
};
// Fn for loading manifest app html
var _loadHtml = function(apps) {
jQuery.each(apps, function(i, a) {
if (!_bUsesAppHandlers) {
// load html and save the root node
appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html));
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfigs[i], // the app config
_outerHtml(a.html)
);
var appId = appConfigs[i].appId;
var root = appConfigs[i].root;
if (!root) {
throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.');
}
if (!elementInDocument(root)) {
throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfigs[i] // the app config
);
if (!F2.isNativeDOMNode(root)) {
throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.');
}
$(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId);
}
// init events
_initAppEvents(appConfigs[i]);
});
};
// Pull out the manifest data
var scripts = appManifest.scripts || [];
var styles = appManifest.styles || [];
var inlines = appManifest.inlineScripts || [];
var apps = appManifest.apps || [];
// Finally, load the styles, html, and scripts
_loadStyles(styles, function() {
// Put the html on the page
_loadHtml(apps);
// Add the script content to the page
_loadScripts(scripts, function() {
// Load any inline scripts
_loadInlineScripts(inlines, function() {
// Create the apps
jQuery.each(appConfigs, function(i, a) {
_createAppInstance(a, appManifest.apps[i]);
});
});
});
});
};
/**
* Loads the app's html/css/javascript into an iframe
* @method loadSecureApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the
* page.
*/
var _loadSecureApp = function(appConfig, appManifest) {
// make sure the container is configured for secure apps
if (_config.secureAppPagePath) {
if (!_bUsesAppHandlers) {
// create the html container for the iframe
appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>'));
}
else {
var $root = jQuery(appConfig.root);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfig, // the app config
appManifest.html
);
if ($root.parents('body:first').length === 0) {
throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfig // the app config
);
if (!appConfig.root) {
throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
if (!F2.isNativeDOMNode(appConfig.root)) {
throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId);
}
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// init events
_initAppEvents(appConfig);
// create RPC socket
F2.Rpc.register(appConfig, appManifest);
}
else {
F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.');
}
};
var _outerHtml = function(html) {
return jQuery('<div></div>').append(html).html();
};
/**
* Checks if the app is valid
* @method _validateApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @returns {bool} True if the app is valid
*/
var _validateApp = function(appConfig) {
// check for valid app configurations
if (!appConfig.appId) {
F2.log('"appId" missing from app object');
return false;
}
else if (!appConfig.root && !appConfig.manifestUrl) {
F2.log('"manifestUrl" missing from app object');
return false;
}
return true;
};
/**
* Checks if the ContainerConfig is valid
* @method _validateContainerConfig
* @private
* @returns {bool} True if the config is valid
*/
var _validateContainerConfig = function() {
if (_config) {
if (_config.xhr) {
if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) {
throw ('ContainerConfig.xhr should be a function or an object');
}
if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') {
throw ('ContainerConfig.xhr.dataType should be a function');
}
if (_config.xhr.type && typeof _config.xhr.type !== 'function') {
throw ('ContainerConfig.xhr.type should be a function');
}
if (_config.xhr.url && typeof _config.xhr.url !== 'function') {
throw ('ContainerConfig.xhr.url should be a function');
}
}
}
return true;
};
return {
/**
* Gets the current list of apps in the container
* @method getContainerState
* @returns {Array} An array of objects containing the appId
*/
getContainerState: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.getContainerState()');
return;
}
return jQuery.map(_apps, function(app) {
return {
appId: app.config.appId
};
});
},
/**
* Initializes the container. This method must be called before performing
* any other actions in the container.
* @method init
* @param {F2.ContainerConfig} config The configuration object
*/
init: function(config) {
_config = config || {};
_validateContainerConfig();
_hydrateContainerConfig(_config);
// dictates whether we use the old logic or the new logic.
// TODO: Remove in v2.0
_bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed);
// only establish RPC connection if the container supports the secure app page
if ( !! _config.secureAppPagePath || _config.isSecureAppPage) {
F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false);
}
F2.UI.init(_config);
if (!_config.isSecureAppPage) {
_initContainerEvents();
}
},
/**
* Has the container been init?
* @method isInit
* @return {bool} True if the container has been init
*/
isInit: _isInit,
/**
* Begins the loading process for all apps and/or initialization process for pre-loaded apps.
* The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will
* contain the app's unique instanceId within the container. If the
* {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered
* to be a pre-loaded app and will be handled accordingly. Optionally, the
* {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those
* assets will be used instead of making a request.
* @method registerApps
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {Array} [appManifests] An array of
* {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* objects. This array must be the same length as the apps array that is
* objects. This array must be the same length as the apps array that is
* passed in. This can be useful if apps are loaded on the server-side and
* passed down to the client.
* @example
* Traditional App requests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app2',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Pre-loaded and tradition apps mixed.
*
* // Pre-loaded apps and traditional f2 app configs
* // you can preload the same app multiple times as long as you have a unique root for each
* var arConfigs = [
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-1',
* manifestUrl: ''
* },
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-2',
* manifestUrl: ''
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Apps with predefined manifests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app2', context: {}}
* ];
*
* // Pre requested manifest responses
* var arManifests = [
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App 2!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/App2Class.js'],
* styles: ['http://www.domain.com/css/App2Styles.css']
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs, arManifests);
*/
registerApps: function(appConfigs, appManifests) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.registerApps()');
return;
}
else if (!appConfigs) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
}
var appStack = [];
var batches = {};
var callbackStack = {};
var haveManifests = false;
appConfigs = [].concat(appConfigs);
appManifests = [].concat(appManifests || []);
haveManifests = !! appManifests.length;
// appConfigs must have a length
if (!appConfigs.length) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
// ensure that the array of apps and manifests are qual
}
else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) {
F2.log('The length of "apps" does not equal the length of "appManifests"');
return;
}
// validate each app and assign it an instanceId
// then determine which apps can be batched together
jQuery.each(appConfigs, function(i, a) {
// add properties and methods
a = _createAppConfig(a);
// Will set to itself, for preloaded apps, or set to null for apps that aren't already
// on the page.
a.root = a.root || null;
// we validate the app after setting the root property because pre-load apps do no require
// manifest url
if (!_validateApp(a)) {
return; // move to the next app
}
// save app
_apps[a.instanceId] = {
config: a
};
// If the root property is defined then this app is considered to be preloaded and we will
// run it through that logic.
if (a.root) {
if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) {
F2.log('AppConfig invalid for pre-load, not a valid string and not dom node');
F2.log('AppConfig instance:', a);
throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.');
}
else if (jQuery(a.root).length != 1) {
F2.log('AppConfig invalid for pre-load, root not unique');
F2.log('AppConfig instance:', a);
F2.log('Number of dom node instances:', jQuery(a.root).length);
throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.');
}
// instantiate F2.App
_createAppInstance(a);
// init events
_initAppEvents(a);
// Continue on in the .each loop, no need to continue because the app is on the page
// the js in initialized, and it is ready to role.
return; // equivalent to continue in .each
}
if (!_bUsesAppHandlers) {
// fire beforeAppRender
a.root = _beforeAppRender(a);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_CREATE_ROOT,
a // the app config
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_BEFORE,
a // the app config
);
}
// if we have the manifest, go ahead and load the app
if (haveManifests) {
_loadApps(a, appManifests[i]);
}
else {
// check if this app can be batched
if (a.enableBatchRequests && !a.isSecure) {
batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || [];
batches[a.manifestUrl.toLowerCase()].push(a);
}
else {
appStack.push({
apps: [a],
url: a.manifestUrl
});
}
}
});
// we don't have the manifests, go ahead and load them
if (!haveManifests) {
// add the batches to the appStack
jQuery.each(batches, function(i, b) {
appStack.push({
url: i,
apps: b
});
});
// if an app is being loaded more than once on the page, there is the
// potential that the jsonp callback will be clobbered if the request
// for the AppManifest for the app comes back at the same time as
// another request for the same app. We'll create a callbackStack
// that will ensure that requests for the same app are loaded in order
// rather than at the same time
jQuery.each(appStack, function(i, req) {
// define the callback function based on the first app's App ID
var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId;
// push the request onto the callback stack
callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || [];
callbackStack[jsonpCallback].push(req);
});
// loop through each item in the callback stack and make the request
// for the AppManifest. When the request is complete, pop the next
// request off the stack and make the request.
jQuery.each(callbackStack, function(i, requests) {
var manifestRequest = function(jsonpCallback, req) {
if (!req) {
return;
}
// setup defaults and callbacks
var url = req.url,
type = 'GET',
dataType = 'jsonp',
completeFunc = function() {
manifestRequest(i, requests.pop());
},
errorFunc = function() {
jQuery.each(req.apps, function(idx, item) {
F2.log('Removed failed ' + item.name + ' app', item);
F2.removeApp(item.instanceId);
});
},
successFunc = function(appManifest) {
_loadApps(req.apps, appManifest);
};
// optionally fire xhr overrides
if (_config.xhr && _config.xhr.dataType) {
dataType = _config.xhr.dataType(req.url, req.apps);
if (typeof dataType !== 'string') {
throw ('ContainerConfig.xhr.dataType should return a string');
}
}
if (_config.xhr && _config.xhr.type) {
type = _config.xhr.type(req.url, req.apps);
if (typeof type !== 'string') {
throw ('ContainerConfig.xhr.type should return a string');
}
}
if (_config.xhr && _config.xhr.url) {
url = _config.xhr.url(req.url, req.apps);
if (typeof url !== 'string') {
throw ('ContainerConfig.xhr.url should return a string');
}
}
// setup the default request function if an override is not present
var requestFunc = _config.xhr;
if (typeof requestFunc !== 'function') {
requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) {
jQuery.ajax({
url: url,
type: type,
data: {
params: F2.stringify(req.apps, F2.appConfigReplacer)
},
jsonp: false, // do not put 'callback=' in the query string
jsonpCallback: jsonpCallback, // Unique function name
dataType: dataType,
success: successCallback,
error: function(jqxhr, settings, exception) {
F2.log('Failed to load app(s)', exception.toString(), req.apps);
errorCallback();
},
complete: completeCallback
});
};
}
requestFunc(url, req.apps, successFunc, errorFunc, completeFunc);
};
manifestRequest(i, requests.pop());
});
}
},
/**
* Removes all apps from the container
* @method removeAllApps
*/
removeAllApps: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeAllApps()');
return;
}
jQuery.each(_apps, function(i, a) {
F2.removeApp(a.config.instanceId);
});
},
/**
* Removes an app from the container
* @method removeApp
* @param {string} instanceId The app's instanceId
*/
removeApp: function(instanceId) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeApp()');
return;
}
if (_apps[instanceId]) {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_AFTER,
_apps[instanceId] // the app instance
);
delete _apps[instanceId];
}
}
};
})());
exports.F2 = F2;
if (typeof define !== 'undefined' && define.amd) {
define(function() {
return F2;
});
}
})(typeof exports !== 'undefined' ? exports : window);
|
app/node_modules/core-js/client/shim.js
|
icsbookmarket/uhmicsbookmarket
|
/**
* core-js 2.4.1
* https://github.com/zloirock/core-js
* License: http://rock.mit-license.org
* © 2016 Denis Pushkarev
*/
!function(__e, __g, undefined){
'use strict';
/******/ (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__) {
__webpack_require__(1);
__webpack_require__(50);
__webpack_require__(51);
__webpack_require__(52);
__webpack_require__(54);
__webpack_require__(55);
__webpack_require__(58);
__webpack_require__(59);
__webpack_require__(60);
__webpack_require__(61);
__webpack_require__(62);
__webpack_require__(63);
__webpack_require__(64);
__webpack_require__(65);
__webpack_require__(66);
__webpack_require__(68);
__webpack_require__(70);
__webpack_require__(72);
__webpack_require__(74);
__webpack_require__(77);
__webpack_require__(78);
__webpack_require__(79);
__webpack_require__(83);
__webpack_require__(86);
__webpack_require__(87);
__webpack_require__(88);
__webpack_require__(89);
__webpack_require__(91);
__webpack_require__(92);
__webpack_require__(93);
__webpack_require__(94);
__webpack_require__(95);
__webpack_require__(97);
__webpack_require__(99);
__webpack_require__(100);
__webpack_require__(101);
__webpack_require__(103);
__webpack_require__(104);
__webpack_require__(105);
__webpack_require__(107);
__webpack_require__(108);
__webpack_require__(109);
__webpack_require__(111);
__webpack_require__(112);
__webpack_require__(113);
__webpack_require__(114);
__webpack_require__(115);
__webpack_require__(116);
__webpack_require__(117);
__webpack_require__(118);
__webpack_require__(119);
__webpack_require__(120);
__webpack_require__(121);
__webpack_require__(122);
__webpack_require__(123);
__webpack_require__(124);
__webpack_require__(126);
__webpack_require__(130);
__webpack_require__(131);
__webpack_require__(132);
__webpack_require__(133);
__webpack_require__(137);
__webpack_require__(139);
__webpack_require__(140);
__webpack_require__(141);
__webpack_require__(142);
__webpack_require__(143);
__webpack_require__(144);
__webpack_require__(145);
__webpack_require__(146);
__webpack_require__(147);
__webpack_require__(148);
__webpack_require__(149);
__webpack_require__(150);
__webpack_require__(151);
__webpack_require__(152);
__webpack_require__(158);
__webpack_require__(159);
__webpack_require__(161);
__webpack_require__(162);
__webpack_require__(163);
__webpack_require__(167);
__webpack_require__(168);
__webpack_require__(169);
__webpack_require__(170);
__webpack_require__(171);
__webpack_require__(173);
__webpack_require__(174);
__webpack_require__(175);
__webpack_require__(176);
__webpack_require__(179);
__webpack_require__(181);
__webpack_require__(182);
__webpack_require__(183);
__webpack_require__(185);
__webpack_require__(187);
__webpack_require__(189);
__webpack_require__(190);
__webpack_require__(191);
__webpack_require__(193);
__webpack_require__(194);
__webpack_require__(195);
__webpack_require__(196);
__webpack_require__(203);
__webpack_require__(206);
__webpack_require__(207);
__webpack_require__(209);
__webpack_require__(210);
__webpack_require__(211);
__webpack_require__(212);
__webpack_require__(213);
__webpack_require__(214);
__webpack_require__(215);
__webpack_require__(216);
__webpack_require__(217);
__webpack_require__(218);
__webpack_require__(219);
__webpack_require__(220);
__webpack_require__(222);
__webpack_require__(223);
__webpack_require__(224);
__webpack_require__(225);
__webpack_require__(226);
__webpack_require__(227);
__webpack_require__(228);
__webpack_require__(229);
__webpack_require__(231);
__webpack_require__(234);
__webpack_require__(235);
__webpack_require__(237);
__webpack_require__(238);
__webpack_require__(239);
__webpack_require__(240);
__webpack_require__(241);
__webpack_require__(242);
__webpack_require__(243);
__webpack_require__(244);
__webpack_require__(245);
__webpack_require__(246);
__webpack_require__(247);
__webpack_require__(249);
__webpack_require__(250);
__webpack_require__(251);
__webpack_require__(252);
__webpack_require__(253);
__webpack_require__(254);
__webpack_require__(255);
__webpack_require__(256);
__webpack_require__(258);
__webpack_require__(259);
__webpack_require__(261);
__webpack_require__(262);
__webpack_require__(263);
__webpack_require__(264);
__webpack_require__(267);
__webpack_require__(268);
__webpack_require__(269);
__webpack_require__(270);
__webpack_require__(271);
__webpack_require__(272);
__webpack_require__(273);
__webpack_require__(274);
__webpack_require__(276);
__webpack_require__(277);
__webpack_require__(278);
__webpack_require__(279);
__webpack_require__(280);
__webpack_require__(281);
__webpack_require__(282);
__webpack_require__(283);
__webpack_require__(284);
__webpack_require__(285);
__webpack_require__(286);
__webpack_require__(287);
module.exports = __webpack_require__(288);
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// ECMAScript 6 symbols shim
var global = __webpack_require__(2)
, has = __webpack_require__(3)
, DESCRIPTORS = __webpack_require__(4)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, META = __webpack_require__(20).KEY
, $fails = __webpack_require__(5)
, shared = __webpack_require__(21)
, setToStringTag = __webpack_require__(22)
, uid = __webpack_require__(17)
, wks = __webpack_require__(23)
, wksExt = __webpack_require__(24)
, wksDefine = __webpack_require__(25)
, keyOf = __webpack_require__(27)
, enumKeys = __webpack_require__(40)
, isArray = __webpack_require__(43)
, anObject = __webpack_require__(10)
, toIObject = __webpack_require__(30)
, toPrimitive = __webpack_require__(14)
, createDesc = __webpack_require__(15)
, _create = __webpack_require__(44)
, gOPNExt = __webpack_require__(47)
, $GOPD = __webpack_require__(49)
, $DP = __webpack_require__(9)
, $keys = __webpack_require__(28)
, gOPD = $GOPD.f
, dP = $DP.f
, gOPN = gOPNExt.f
, $Symbol = global.Symbol
, $JSON = global.JSON
, _stringify = $JSON && $JSON.stringify
, PROTOTYPE = 'prototype'
, HIDDEN = wks('_hidden')
, TO_PRIMITIVE = wks('toPrimitive')
, isEnum = {}.propertyIsEnumerable
, SymbolRegistry = shared('symbol-registry')
, AllSymbols = shared('symbols')
, OPSymbols = shared('op-symbols')
, ObjectProto = Object[PROTOTYPE]
, USE_NATIVE = typeof $Symbol == 'function'
, QObject = global.QObject;
// Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild;
// fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
var setSymbolDesc = DESCRIPTORS && $fails(function(){
return _create(dP({}, 'a', {
get: function(){ return dP(this, 'a', {value: 7}).a; }
})).a != 7;
}) ? function(it, key, D){
var protoDesc = gOPD(ObjectProto, key);
if(protoDesc)delete ObjectProto[key];
dP(it, key, D);
if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc);
} : dP;
var wrap = function(tag){
var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]);
sym._k = tag;
return sym;
};
var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){
return typeof it == 'symbol';
} : function(it){
return it instanceof $Symbol;
};
var $defineProperty = function defineProperty(it, key, D){
if(it === ObjectProto)$defineProperty(OPSymbols, key, D);
anObject(it);
key = toPrimitive(key, true);
anObject(D);
if(has(AllSymbols, key)){
if(!D.enumerable){
if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {}));
it[HIDDEN][key] = true;
} else {
if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false;
D = _create(D, {enumerable: createDesc(0, false)});
} return setSymbolDesc(it, key, D);
} return dP(it, key, D);
};
var $defineProperties = function defineProperties(it, P){
anObject(it);
var keys = enumKeys(P = toIObject(P))
, i = 0
, l = keys.length
, key;
while(l > i)$defineProperty(it, key = keys[i++], P[key]);
return it;
};
var $create = function create(it, P){
return P === undefined ? _create(it) : $defineProperties(_create(it), P);
};
var $propertyIsEnumerable = function propertyIsEnumerable(key){
var E = isEnum.call(this, key = toPrimitive(key, true));
if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false;
return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true;
};
var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){
it = toIObject(it);
key = toPrimitive(key, true);
if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return;
var D = gOPD(it, key);
if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true;
return D;
};
var $getOwnPropertyNames = function getOwnPropertyNames(it){
var names = gOPN(toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key);
} return result;
};
var $getOwnPropertySymbols = function getOwnPropertySymbols(it){
var IS_OP = it === ObjectProto
, names = gOPN(IS_OP ? OPSymbols : toIObject(it))
, result = []
, i = 0
, key;
while(names.length > i){
if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]);
} return result;
};
// 19.4.1.1 Symbol([description])
if(!USE_NATIVE){
$Symbol = function Symbol(){
if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!');
var tag = uid(arguments.length > 0 ? arguments[0] : undefined);
var $set = function(value){
if(this === ObjectProto)$set.call(OPSymbols, value);
if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false;
setSymbolDesc(this, tag, createDesc(1, value));
};
if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set});
return wrap(tag);
};
redefine($Symbol[PROTOTYPE], 'toString', function toString(){
return this._k;
});
$GOPD.f = $getOwnPropertyDescriptor;
$DP.f = $defineProperty;
__webpack_require__(48).f = gOPNExt.f = $getOwnPropertyNames;
__webpack_require__(42).f = $propertyIsEnumerable;
__webpack_require__(41).f = $getOwnPropertySymbols;
if(DESCRIPTORS && !__webpack_require__(26)){
redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true);
}
wksExt.f = function(name){
return wrap(wks(name));
}
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol});
for(var symbols = (
// 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14
'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables'
).split(','), i = 0; symbols.length > i; )wks(symbols[i++]);
for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]);
$export($export.S + $export.F * !USE_NATIVE, 'Symbol', {
// 19.4.2.1 Symbol.for(key)
'for': function(key){
return has(SymbolRegistry, key += '')
? SymbolRegistry[key]
: SymbolRegistry[key] = $Symbol(key);
},
// 19.4.2.5 Symbol.keyFor(sym)
keyFor: function keyFor(key){
if(isSymbol(key))return keyOf(SymbolRegistry, key);
throw TypeError(key + ' is not a symbol!');
},
useSetter: function(){ setter = true; },
useSimple: function(){ setter = false; }
});
$export($export.S + $export.F * !USE_NATIVE, 'Object', {
// 19.1.2.2 Object.create(O [, Properties])
create: $create,
// 19.1.2.4 Object.defineProperty(O, P, Attributes)
defineProperty: $defineProperty,
// 19.1.2.3 Object.defineProperties(O, Properties)
defineProperties: $defineProperties,
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
getOwnPropertyDescriptor: $getOwnPropertyDescriptor,
// 19.1.2.7 Object.getOwnPropertyNames(O)
getOwnPropertyNames: $getOwnPropertyNames,
// 19.1.2.8 Object.getOwnPropertySymbols(O)
getOwnPropertySymbols: $getOwnPropertySymbols
});
// 24.3.2 JSON.stringify(value [, replacer [, space]])
$JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){
var S = $Symbol();
// MS Edge converts symbol values to JSON as {}
// WebKit converts symbol values to JSON as null
// V8 throws on boxed symbols
return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}';
})), 'JSON', {
stringify: function stringify(it){
if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined
var args = [it]
, i = 1
, replacer, $replacer;
while(arguments.length > i)args.push(arguments[i++]);
replacer = args[1];
if(typeof replacer == 'function')$replacer = replacer;
if($replacer || !isArray(replacer))replacer = function(key, value){
if($replacer)value = $replacer.call(this, key, value);
if(!isSymbol(value))return value;
};
args[1] = replacer;
return _stringify.apply($JSON, args);
}
});
// 19.4.3.4 Symbol.prototype[@@toPrimitive](hint)
$Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(8)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf);
// 19.4.3.5 Symbol.prototype[@@toStringTag]
setToStringTag($Symbol, 'Symbol');
// 20.2.1.9 Math[@@toStringTag]
setToStringTag(Math, 'Math', true);
// 24.3.3 JSON[@@toStringTag]
setToStringTag(global.JSON, 'JSON', true);
/***/ },
/* 2 */
/***/ function(module, exports) {
// https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
var global = module.exports = typeof window != 'undefined' && window.Math == Math
? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
/***/ },
/* 3 */
/***/ function(module, exports) {
var hasOwnProperty = {}.hasOwnProperty;
module.exports = function(it, key){
return hasOwnProperty.call(it, key);
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
// Thank's IE8 for his funny defineProperty
module.exports = !__webpack_require__(5)(function(){
return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = function(exec){
try {
return !!exec();
} catch(e){
return true;
}
};
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, hide = __webpack_require__(8)
, redefine = __webpack_require__(16)
, ctx = __webpack_require__(18)
, PROTOTYPE = 'prototype';
var $export = function(type, name, source){
var IS_FORCED = type & $export.F
, IS_GLOBAL = type & $export.G
, IS_STATIC = type & $export.S
, IS_PROTO = type & $export.P
, IS_BIND = type & $export.B
, target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE]
, exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
, expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {})
, key, own, out, exp;
if(IS_GLOBAL)source = name;
for(key in source){
// contains in native
own = !IS_FORCED && target && target[key] !== undefined;
// export native or passed
out = (own ? target : source)[key];
// bind timers to global for call from export context
exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
// extend global
if(target)redefine(target, key, out, type & $export.U);
// export
if(exports[key] != out)hide(exports, key, exp);
if(IS_PROTO && expProto[key] != out)expProto[key] = out;
}
};
global.core = core;
// type bitmap
$export.F = 1; // forced
$export.G = 2; // global
$export.S = 4; // static
$export.P = 8; // proto
$export.B = 16; // bind
$export.W = 32; // wrap
$export.U = 64; // safe
$export.R = 128; // real proto method for `library`
module.exports = $export;
/***/ },
/* 7 */
/***/ function(module, exports) {
var core = module.exports = {version: '2.4.0'};
if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, createDesc = __webpack_require__(15);
module.exports = __webpack_require__(4) ? function(object, key, value){
return dP.f(object, key, createDesc(1, value));
} : function(object, key, value){
object[key] = value;
return object;
};
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
var anObject = __webpack_require__(10)
, IE8_DOM_DEFINE = __webpack_require__(12)
, toPrimitive = __webpack_require__(14)
, dP = Object.defineProperty;
exports.f = __webpack_require__(4) ? Object.defineProperty : function defineProperty(O, P, Attributes){
anObject(O);
P = toPrimitive(P, true);
anObject(Attributes);
if(IE8_DOM_DEFINE)try {
return dP(O, P, Attributes);
} catch(e){ /* empty */ }
if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!');
if('value' in Attributes)O[P] = Attributes.value;
return O;
};
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11);
module.exports = function(it){
if(!isObject(it))throw TypeError(it + ' is not an object!');
return it;
};
/***/ },
/* 11 */
/***/ function(module, exports) {
module.exports = function(it){
return typeof it === 'object' ? it !== null : typeof it === 'function';
};
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
module.exports = !__webpack_require__(4) && !__webpack_require__(5)(function(){
return Object.defineProperty(__webpack_require__(13)('div'), 'a', {get: function(){ return 7; }}).a != 7;
});
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, document = __webpack_require__(2).document
// in old IE typeof document.createElement is 'object'
, is = isObject(document) && isObject(document.createElement);
module.exports = function(it){
return is ? document.createElement(it) : {};
};
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.1 ToPrimitive(input [, PreferredType])
var isObject = __webpack_require__(11);
// instead of the ES6 spec version, we didn't implement @@toPrimitive case
// and the second argument - flag - preferred type is a string
module.exports = function(it, S){
if(!isObject(it))return it;
var fn, val;
if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val;
if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val;
throw TypeError("Can't convert object to primitive value");
};
/***/ },
/* 15 */
/***/ function(module, exports) {
module.exports = function(bitmap, value){
return {
enumerable : !(bitmap & 1),
configurable: !(bitmap & 2),
writable : !(bitmap & 4),
value : value
};
};
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, hide = __webpack_require__(8)
, has = __webpack_require__(3)
, SRC = __webpack_require__(17)('src')
, TO_STRING = 'toString'
, $toString = Function[TO_STRING]
, TPL = ('' + $toString).split(TO_STRING);
__webpack_require__(7).inspectSource = function(it){
return $toString.call(it);
};
(module.exports = function(O, key, val, safe){
var isFunction = typeof val == 'function';
if(isFunction)has(val, 'name') || hide(val, 'name', key);
if(O[key] === val)return;
if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key)));
if(O === global){
O[key] = val;
} else {
if(!safe){
delete O[key];
hide(O, key, val);
} else {
if(O[key])O[key] = val;
else hide(O, key, val);
}
}
// add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
})(Function.prototype, TO_STRING, function toString(){
return typeof this == 'function' && this[SRC] || $toString.call(this);
});
/***/ },
/* 17 */
/***/ function(module, exports) {
var id = 0
, px = Math.random();
module.exports = function(key){
return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
};
/***/ },
/* 18 */
/***/ function(module, exports, __webpack_require__) {
// optional / simple context binding
var aFunction = __webpack_require__(19);
module.exports = function(fn, that, length){
aFunction(fn);
if(that === undefined)return fn;
switch(length){
case 1: return function(a){
return fn.call(that, a);
};
case 2: return function(a, b){
return fn.call(that, a, b);
};
case 3: return function(a, b, c){
return fn.call(that, a, b, c);
};
}
return function(/* ...args */){
return fn.apply(that, arguments);
};
};
/***/ },
/* 19 */
/***/ function(module, exports) {
module.exports = function(it){
if(typeof it != 'function')throw TypeError(it + ' is not a function!');
return it;
};
/***/ },
/* 20 */
/***/ function(module, exports, __webpack_require__) {
var META = __webpack_require__(17)('meta')
, isObject = __webpack_require__(11)
, has = __webpack_require__(3)
, setDesc = __webpack_require__(9).f
, id = 0;
var isExtensible = Object.isExtensible || function(){
return true;
};
var FREEZE = !__webpack_require__(5)(function(){
return isExtensible(Object.preventExtensions({}));
});
var setMeta = function(it){
setDesc(it, META, {value: {
i: 'O' + ++id, // object ID
w: {} // weak collections IDs
}});
};
var fastKey = function(it, create){
// return primitive with prefix
if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it;
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return 'F';
// not necessary to add metadata
if(!create)return 'E';
// add missing metadata
setMeta(it);
// return object ID
} return it[META].i;
};
var getWeak = function(it, create){
if(!has(it, META)){
// can't set metadata to uncaught frozen object
if(!isExtensible(it))return true;
// not necessary to add metadata
if(!create)return false;
// add missing metadata
setMeta(it);
// return hash weak collections IDs
} return it[META].w;
};
// add metadata on freeze-family methods calling
var onFreeze = function(it){
if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it);
return it;
};
var meta = module.exports = {
KEY: META,
NEED: false,
fastKey: fastKey,
getWeak: getWeak,
onFreeze: onFreeze
};
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, SHARED = '__core-js_shared__'
, store = global[SHARED] || (global[SHARED] = {});
module.exports = function(key){
return store[key] || (store[key] = {});
};
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
var def = __webpack_require__(9).f
, has = __webpack_require__(3)
, TAG = __webpack_require__(23)('toStringTag');
module.exports = function(it, tag, stat){
if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag});
};
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
var store = __webpack_require__(21)('wks')
, uid = __webpack_require__(17)
, Symbol = __webpack_require__(2).Symbol
, USE_SYMBOL = typeof Symbol == 'function';
var $exports = module.exports = function(name){
return store[name] || (store[name] =
USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name));
};
$exports.store = store;
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
exports.f = __webpack_require__(23);
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, core = __webpack_require__(7)
, LIBRARY = __webpack_require__(26)
, wksExt = __webpack_require__(24)
, defineProperty = __webpack_require__(9).f;
module.exports = function(name){
var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)});
};
/***/ },
/* 26 */
/***/ function(module, exports) {
module.exports = false;
/***/ },
/* 27 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(28)
, toIObject = __webpack_require__(30);
module.exports = function(object, el){
var O = toIObject(object)
, keys = getKeys(O)
, length = keys.length
, index = 0
, key;
while(length > index)if(O[key = keys[index++]] === el)return key;
};
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 / 15.2.3.14 Object.keys(O)
var $keys = __webpack_require__(29)
, enumBugKeys = __webpack_require__(39);
module.exports = Object.keys || function keys(O){
return $keys(O, enumBugKeys);
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
var has = __webpack_require__(3)
, toIObject = __webpack_require__(30)
, arrayIndexOf = __webpack_require__(34)(false)
, IE_PROTO = __webpack_require__(38)('IE_PROTO');
module.exports = function(object, names){
var O = toIObject(object)
, i = 0
, result = []
, key;
for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key);
// Don't enum bug & hidden keys
while(names.length > i)if(has(O, key = names[i++])){
~arrayIndexOf(result, key) || result.push(key);
}
return result;
};
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
// to indexed object, toObject with fallback for non-array-like ES3 strings
var IObject = __webpack_require__(31)
, defined = __webpack_require__(33);
module.exports = function(it){
return IObject(defined(it));
};
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
// fallback for non-array-like ES3 and non-enumerable old V8 strings
var cof = __webpack_require__(32);
module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){
return cof(it) == 'String' ? it.split('') : Object(it);
};
/***/ },
/* 32 */
/***/ function(module, exports) {
var toString = {}.toString;
module.exports = function(it){
return toString.call(it).slice(8, -1);
};
/***/ },
/* 33 */
/***/ function(module, exports) {
// 7.2.1 RequireObjectCoercible(argument)
module.exports = function(it){
if(it == undefined)throw TypeError("Can't call method on " + it);
return it;
};
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
// false -> Array#indexOf
// true -> Array#includes
var toIObject = __webpack_require__(30)
, toLength = __webpack_require__(35)
, toIndex = __webpack_require__(37);
module.exports = function(IS_INCLUDES){
return function($this, el, fromIndex){
var O = toIObject($this)
, length = toLength(O.length)
, index = toIndex(fromIndex, length)
, value;
// Array#includes uses SameValueZero equality algorithm
if(IS_INCLUDES && el != el)while(length > index){
value = O[index++];
if(value != value)return true;
// Array#toIndex ignores holes, Array#includes - not
} else for(;length > index; index++)if(IS_INCLUDES || index in O){
if(O[index] === el)return IS_INCLUDES || index || 0;
} return !IS_INCLUDES && -1;
};
};
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.15 ToLength
var toInteger = __webpack_require__(36)
, min = Math.min;
module.exports = function(it){
return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991
};
/***/ },
/* 36 */
/***/ function(module, exports) {
// 7.1.4 ToInteger
var ceil = Math.ceil
, floor = Math.floor;
module.exports = function(it){
return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
};
/***/ },
/* 37 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(36)
, max = Math.max
, min = Math.min;
module.exports = function(index, length){
index = toInteger(index);
return index < 0 ? max(index + length, 0) : min(index, length);
};
/***/ },
/* 38 */
/***/ function(module, exports, __webpack_require__) {
var shared = __webpack_require__(21)('keys')
, uid = __webpack_require__(17);
module.exports = function(key){
return shared[key] || (shared[key] = uid(key));
};
/***/ },
/* 39 */
/***/ function(module, exports) {
// IE 8- don't enum bug keys
module.exports = (
'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
).split(',');
/***/ },
/* 40 */
/***/ function(module, exports, __webpack_require__) {
// all enumerable object keys, includes symbols
var getKeys = __webpack_require__(28)
, gOPS = __webpack_require__(41)
, pIE = __webpack_require__(42);
module.exports = function(it){
var result = getKeys(it)
, getSymbols = gOPS.f;
if(getSymbols){
var symbols = getSymbols(it)
, isEnum = pIE.f
, i = 0
, key;
while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key);
} return result;
};
/***/ },
/* 41 */
/***/ function(module, exports) {
exports.f = Object.getOwnPropertySymbols;
/***/ },
/* 42 */
/***/ function(module, exports) {
exports.f = {}.propertyIsEnumerable;
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.2 IsArray(argument)
var cof = __webpack_require__(32);
module.exports = Array.isArray || function isArray(arg){
return cof(arg) == 'Array';
};
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
var anObject = __webpack_require__(10)
, dPs = __webpack_require__(45)
, enumBugKeys = __webpack_require__(39)
, IE_PROTO = __webpack_require__(38)('IE_PROTO')
, Empty = function(){ /* empty */ }
, PROTOTYPE = 'prototype';
// Create object with fake `null` prototype: use iframe Object with cleared prototype
var createDict = function(){
// Thrash, waste and sodomy: IE GC bug
var iframe = __webpack_require__(13)('iframe')
, i = enumBugKeys.length
, lt = '<'
, gt = '>'
, iframeDocument;
iframe.style.display = 'none';
__webpack_require__(46).appendChild(iframe);
iframe.src = 'javascript:'; // eslint-disable-line no-script-url
// createDict = iframe.contentWindow.Object;
// html.removeChild(iframe);
iframeDocument = iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt);
iframeDocument.close();
createDict = iframeDocument.F;
while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]];
return createDict();
};
module.exports = Object.create || function create(O, Properties){
var result;
if(O !== null){
Empty[PROTOTYPE] = anObject(O);
result = new Empty;
Empty[PROTOTYPE] = null;
// add "__proto__" for Object.getPrototypeOf polyfill
result[IE_PROTO] = O;
} else result = createDict();
return Properties === undefined ? result : dPs(result, Properties);
};
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9)
, anObject = __webpack_require__(10)
, getKeys = __webpack_require__(28);
module.exports = __webpack_require__(4) ? Object.defineProperties : function defineProperties(O, Properties){
anObject(O);
var keys = getKeys(Properties)
, length = keys.length
, i = 0
, P;
while(length > i)dP.f(O, P = keys[i++], Properties[P]);
return O;
};
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2).document && document.documentElement;
/***/ },
/* 47 */
/***/ function(module, exports, __webpack_require__) {
// fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
var toIObject = __webpack_require__(30)
, gOPN = __webpack_require__(48).f
, toString = {}.toString;
var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
? Object.getOwnPropertyNames(window) : [];
var getWindowNames = function(it){
try {
return gOPN(it);
} catch(e){
return windowNames.slice();
}
};
module.exports.f = function getOwnPropertyNames(it){
return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it));
};
/***/ },
/* 48 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O)
var $keys = __webpack_require__(29)
, hiddenKeys = __webpack_require__(39).concat('length', 'prototype');
exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){
return $keys(O, hiddenKeys);
};
/***/ },
/* 49 */
/***/ function(module, exports, __webpack_require__) {
var pIE = __webpack_require__(42)
, createDesc = __webpack_require__(15)
, toIObject = __webpack_require__(30)
, toPrimitive = __webpack_require__(14)
, has = __webpack_require__(3)
, IE8_DOM_DEFINE = __webpack_require__(12)
, gOPD = Object.getOwnPropertyDescriptor;
exports.f = __webpack_require__(4) ? gOPD : function getOwnPropertyDescriptor(O, P){
O = toIObject(O);
P = toPrimitive(P, true);
if(IE8_DOM_DEFINE)try {
return gOPD(O, P);
} catch(e){ /* empty */ }
if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]);
};
/***/ },
/* 50 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
// 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes)
$export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperty: __webpack_require__(9).f});
/***/ },
/* 51 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
// 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties)
$export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperties: __webpack_require__(45)});
/***/ },
/* 52 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.6 Object.getOwnPropertyDescriptor(O, P)
var toIObject = __webpack_require__(30)
, $getOwnPropertyDescriptor = __webpack_require__(49).f;
__webpack_require__(53)('getOwnPropertyDescriptor', function(){
return function getOwnPropertyDescriptor(it, key){
return $getOwnPropertyDescriptor(toIObject(it), key);
};
});
/***/ },
/* 53 */
/***/ function(module, exports, __webpack_require__) {
// most Object methods by ES6 should accept primitives
var $export = __webpack_require__(6)
, core = __webpack_require__(7)
, fails = __webpack_require__(5);
module.exports = function(KEY, exec){
var fn = (core.Object || {})[KEY] || Object[KEY]
, exp = {};
exp[KEY] = exec(fn);
$export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
};
/***/ },
/* 54 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
// 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties])
$export($export.S, 'Object', {create: __webpack_require__(44)});
/***/ },
/* 55 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 Object.getPrototypeOf(O)
var toObject = __webpack_require__(56)
, $getPrototypeOf = __webpack_require__(57);
__webpack_require__(53)('getPrototypeOf', function(){
return function getPrototypeOf(it){
return $getPrototypeOf(toObject(it));
};
});
/***/ },
/* 56 */
/***/ function(module, exports, __webpack_require__) {
// 7.1.13 ToObject(argument)
var defined = __webpack_require__(33);
module.exports = function(it){
return Object(defined(it));
};
/***/ },
/* 57 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O)
var has = __webpack_require__(3)
, toObject = __webpack_require__(56)
, IE_PROTO = __webpack_require__(38)('IE_PROTO')
, ObjectProto = Object.prototype;
module.exports = Object.getPrototypeOf || function(O){
O = toObject(O);
if(has(O, IE_PROTO))return O[IE_PROTO];
if(typeof O.constructor == 'function' && O instanceof O.constructor){
return O.constructor.prototype;
} return O instanceof Object ? ObjectProto : null;
};
/***/ },
/* 58 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.14 Object.keys(O)
var toObject = __webpack_require__(56)
, $keys = __webpack_require__(28);
__webpack_require__(53)('keys', function(){
return function keys(it){
return $keys(toObject(it));
};
});
/***/ },
/* 59 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.7 Object.getOwnPropertyNames(O)
__webpack_require__(53)('getOwnPropertyNames', function(){
return __webpack_require__(47).f;
});
/***/ },
/* 60 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.5 Object.freeze(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('freeze', function($freeze){
return function freeze(it){
return $freeze && isObject(it) ? $freeze(meta(it)) : it;
};
});
/***/ },
/* 61 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.17 Object.seal(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('seal', function($seal){
return function seal(it){
return $seal && isObject(it) ? $seal(meta(it)) : it;
};
});
/***/ },
/* 62 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.15 Object.preventExtensions(O)
var isObject = __webpack_require__(11)
, meta = __webpack_require__(20).onFreeze;
__webpack_require__(53)('preventExtensions', function($preventExtensions){
return function preventExtensions(it){
return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it;
};
});
/***/ },
/* 63 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.12 Object.isFrozen(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isFrozen', function($isFrozen){
return function isFrozen(it){
return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true;
};
});
/***/ },
/* 64 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.13 Object.isSealed(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isSealed', function($isSealed){
return function isSealed(it){
return isObject(it) ? $isSealed ? $isSealed(it) : false : true;
};
});
/***/ },
/* 65 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.2.11 Object.isExtensible(O)
var isObject = __webpack_require__(11);
__webpack_require__(53)('isExtensible', function($isExtensible){
return function isExtensible(it){
return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false;
};
});
/***/ },
/* 66 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.1 Object.assign(target, source)
var $export = __webpack_require__(6);
$export($export.S + $export.F, 'Object', {assign: __webpack_require__(67)});
/***/ },
/* 67 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.2.1 Object.assign(target, source, ...)
var getKeys = __webpack_require__(28)
, gOPS = __webpack_require__(41)
, pIE = __webpack_require__(42)
, toObject = __webpack_require__(56)
, IObject = __webpack_require__(31)
, $assign = Object.assign;
// should work with symbols and should have deterministic property order (V8 bug)
module.exports = !$assign || __webpack_require__(5)(function(){
var A = {}
, B = {}
, S = Symbol()
, K = 'abcdefghijklmnopqrst';
A[S] = 7;
K.split('').forEach(function(k){ B[k] = k; });
return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K;
}) ? function assign(target, source){ // eslint-disable-line no-unused-vars
var T = toObject(target)
, aLen = arguments.length
, index = 1
, getSymbols = gOPS.f
, isEnum = pIE.f;
while(aLen > index){
var S = IObject(arguments[index++])
, keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S)
, length = keys.length
, j = 0
, key;
while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key];
} return T;
} : $assign;
/***/ },
/* 68 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.10 Object.is(value1, value2)
var $export = __webpack_require__(6);
$export($export.S, 'Object', {is: __webpack_require__(69)});
/***/ },
/* 69 */
/***/ function(module, exports) {
// 7.2.9 SameValue(x, y)
module.exports = Object.is || function is(x, y){
return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y;
};
/***/ },
/* 70 */
/***/ function(module, exports, __webpack_require__) {
// 19.1.3.19 Object.setPrototypeOf(O, proto)
var $export = __webpack_require__(6);
$export($export.S, 'Object', {setPrototypeOf: __webpack_require__(71).set});
/***/ },
/* 71 */
/***/ function(module, exports, __webpack_require__) {
// Works with __proto__ only. Old v8 can't work with null proto objects.
/* eslint-disable no-proto */
var isObject = __webpack_require__(11)
, anObject = __webpack_require__(10);
var check = function(O, proto){
anObject(O);
if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!");
};
module.exports = {
set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line
function(test, buggy, set){
try {
set = __webpack_require__(18)(Function.call, __webpack_require__(49).f(Object.prototype, '__proto__').set, 2);
set(test, []);
buggy = !(test instanceof Array);
} catch(e){ buggy = true; }
return function setPrototypeOf(O, proto){
check(O, proto);
if(buggy)O.__proto__ = proto;
else set(O, proto);
return O;
};
}({}, false) : undefined),
check: check
};
/***/ },
/* 72 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 19.1.3.6 Object.prototype.toString()
var classof = __webpack_require__(73)
, test = {};
test[__webpack_require__(23)('toStringTag')] = 'z';
if(test + '' != '[object z]'){
__webpack_require__(16)(Object.prototype, 'toString', function toString(){
return '[object ' + classof(this) + ']';
}, true);
}
/***/ },
/* 73 */
/***/ function(module, exports, __webpack_require__) {
// getting tag from 19.1.3.6 Object.prototype.toString()
var cof = __webpack_require__(32)
, TAG = __webpack_require__(23)('toStringTag')
// ES3 wrong here
, ARG = cof(function(){ return arguments; }()) == 'Arguments';
// fallback for IE11 Script Access Denied error
var tryGet = function(it, key){
try {
return it[key];
} catch(e){ /* empty */ }
};
module.exports = function(it){
var O, T, B;
return it === undefined ? 'Undefined' : it === null ? 'Null'
// @@toStringTag case
: typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
// builtinTag case
: ARG ? cof(O)
// ES3 arguments fallback
: (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
};
/***/ },
/* 74 */
/***/ function(module, exports, __webpack_require__) {
// 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...)
var $export = __webpack_require__(6);
$export($export.P, 'Function', {bind: __webpack_require__(75)});
/***/ },
/* 75 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var aFunction = __webpack_require__(19)
, isObject = __webpack_require__(11)
, invoke = __webpack_require__(76)
, arraySlice = [].slice
, factories = {};
var construct = function(F, len, args){
if(!(len in factories)){
for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']';
factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')');
} return factories[len](F, args);
};
module.exports = Function.bind || function bind(that /*, args... */){
var fn = aFunction(this)
, partArgs = arraySlice.call(arguments, 1);
var bound = function(/* args... */){
var args = partArgs.concat(arraySlice.call(arguments));
return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that);
};
if(isObject(fn.prototype))bound.prototype = fn.prototype;
return bound;
};
/***/ },
/* 76 */
/***/ function(module, exports) {
// fast apply, http://jsperf.lnkit.com/fast-apply/5
module.exports = function(fn, args, that){
var un = that === undefined;
switch(args.length){
case 0: return un ? fn()
: fn.call(that);
case 1: return un ? fn(args[0])
: fn.call(that, args[0]);
case 2: return un ? fn(args[0], args[1])
: fn.call(that, args[0], args[1]);
case 3: return un ? fn(args[0], args[1], args[2])
: fn.call(that, args[0], args[1], args[2]);
case 4: return un ? fn(args[0], args[1], args[2], args[3])
: fn.call(that, args[0], args[1], args[2], args[3]);
} return fn.apply(that, args);
};
/***/ },
/* 77 */
/***/ function(module, exports, __webpack_require__) {
var dP = __webpack_require__(9).f
, createDesc = __webpack_require__(15)
, has = __webpack_require__(3)
, FProto = Function.prototype
, nameRE = /^\s*function ([^ (]*)/
, NAME = 'name';
var isExtensible = Object.isExtensible || function(){
return true;
};
// 19.2.4.2 name
NAME in FProto || __webpack_require__(4) && dP(FProto, NAME, {
configurable: true,
get: function(){
try {
var that = this
, name = ('' + that).match(nameRE)[1];
has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name));
return name;
} catch(e){
return '';
}
}
});
/***/ },
/* 78 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var isObject = __webpack_require__(11)
, getPrototypeOf = __webpack_require__(57)
, HAS_INSTANCE = __webpack_require__(23)('hasInstance')
, FunctionProto = Function.prototype;
// 19.2.3.6 Function.prototype[@@hasInstance](V)
if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(9).f(FunctionProto, HAS_INSTANCE, {value: function(O){
if(typeof this != 'function' || !isObject(O))return false;
if(!isObject(this.prototype))return O instanceof this;
// for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this:
while(O = getPrototypeOf(O))if(this.prototype === O)return true;
return false;
}});
/***/ },
/* 79 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, has = __webpack_require__(3)
, cof = __webpack_require__(32)
, inheritIfRequired = __webpack_require__(80)
, toPrimitive = __webpack_require__(14)
, fails = __webpack_require__(5)
, gOPN = __webpack_require__(48).f
, gOPD = __webpack_require__(49).f
, dP = __webpack_require__(9).f
, $trim = __webpack_require__(81).trim
, NUMBER = 'Number'
, $Number = global[NUMBER]
, Base = $Number
, proto = $Number.prototype
// Opera ~12 has broken Object#toString
, BROKEN_COF = cof(__webpack_require__(44)(proto)) == NUMBER
, TRIM = 'trim' in String.prototype;
// 7.1.3 ToNumber(argument)
var toNumber = function(argument){
var it = toPrimitive(argument, false);
if(typeof it == 'string' && it.length > 2){
it = TRIM ? it.trim() : $trim(it, 3);
var first = it.charCodeAt(0)
, third, radix, maxCode;
if(first === 43 || first === 45){
third = it.charCodeAt(2);
if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix
} else if(first === 48){
switch(it.charCodeAt(1)){
case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i
case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i
default : return +it;
}
for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){
code = digits.charCodeAt(i);
// parseInt parses a string to a first unavailable symbol
// but ToNumber should return NaN if a string contains unavailable symbols
if(code < 48 || code > maxCode)return NaN;
} return parseInt(digits, radix);
}
} return +it;
};
if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){
$Number = function Number(value){
var it = arguments.length < 1 ? 0 : value
, that = this;
return that instanceof $Number
// check on 1..constructor(foo) case
&& (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER)
? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it);
};
for(var keys = __webpack_require__(4) ? gOPN(Base) : (
// ES3:
'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' +
// ES6 (in case, if modules with ES6 Number statics required before):
'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' +
'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger'
).split(','), j = 0, key; keys.length > j; j++){
if(has(Base, key = keys[j]) && !has($Number, key)){
dP($Number, key, gOPD(Base, key));
}
}
$Number.prototype = proto;
proto.constructor = $Number;
__webpack_require__(16)(global, NUMBER, $Number);
}
/***/ },
/* 80 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, setPrototypeOf = __webpack_require__(71).set;
module.exports = function(that, target, C){
var P, S = target.constructor;
if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){
setPrototypeOf(that, P);
} return that;
};
/***/ },
/* 81 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, defined = __webpack_require__(33)
, fails = __webpack_require__(5)
, spaces = __webpack_require__(82)
, space = '[' + spaces + ']'
, non = '\u200b\u0085'
, ltrim = RegExp('^' + space + space + '*')
, rtrim = RegExp(space + space + '*$');
var exporter = function(KEY, exec, ALIAS){
var exp = {};
var FORCE = fails(function(){
return !!spaces[KEY]() || non[KEY]() != non;
});
var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY];
if(ALIAS)exp[ALIAS] = fn;
$export($export.P + $export.F * FORCE, 'String', exp);
};
// 1 -> String#trimLeft
// 2 -> String#trimRight
// 3 -> String#trim
var trim = exporter.trim = function(string, TYPE){
string = String(defined(string));
if(TYPE & 1)string = string.replace(ltrim, '');
if(TYPE & 2)string = string.replace(rtrim, '');
return string;
};
module.exports = exporter;
/***/ },
/* 82 */
/***/ function(module, exports) {
module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' +
'\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';
/***/ },
/* 83 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toInteger = __webpack_require__(36)
, aNumberValue = __webpack_require__(84)
, repeat = __webpack_require__(85)
, $toFixed = 1..toFixed
, floor = Math.floor
, data = [0, 0, 0, 0, 0, 0]
, ERROR = 'Number.toFixed: incorrect invocation!'
, ZERO = '0';
var multiply = function(n, c){
var i = -1
, c2 = c;
while(++i < 6){
c2 += n * data[i];
data[i] = c2 % 1e7;
c2 = floor(c2 / 1e7);
}
};
var divide = function(n){
var i = 6
, c = 0;
while(--i >= 0){
c += data[i];
data[i] = floor(c / n);
c = (c % n) * 1e7;
}
};
var numToString = function(){
var i = 6
, s = '';
while(--i >= 0){
if(s !== '' || i === 0 || data[i] !== 0){
var t = String(data[i]);
s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t;
}
} return s;
};
var pow = function(x, n, acc){
return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc);
};
var log = function(x){
var n = 0
, x2 = x;
while(x2 >= 4096){
n += 12;
x2 /= 4096;
}
while(x2 >= 2){
n += 1;
x2 /= 2;
} return n;
};
$export($export.P + $export.F * (!!$toFixed && (
0.00008.toFixed(3) !== '0.000' ||
0.9.toFixed(0) !== '1' ||
1.255.toFixed(2) !== '1.25' ||
1000000000000000128..toFixed(0) !== '1000000000000000128'
) || !__webpack_require__(5)(function(){
// V8 ~ Android 4.3-
$toFixed.call({});
})), 'Number', {
toFixed: function toFixed(fractionDigits){
var x = aNumberValue(this, ERROR)
, f = toInteger(fractionDigits)
, s = ''
, m = ZERO
, e, z, j, k;
if(f < 0 || f > 20)throw RangeError(ERROR);
if(x != x)return 'NaN';
if(x <= -1e21 || x >= 1e21)return String(x);
if(x < 0){
s = '-';
x = -x;
}
if(x > 1e-21){
e = log(x * pow(2, 69, 1)) - 69;
z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1);
z *= 0x10000000000000;
e = 52 - e;
if(e > 0){
multiply(0, z);
j = f;
while(j >= 7){
multiply(1e7, 0);
j -= 7;
}
multiply(pow(10, j, 1), 0);
j = e - 1;
while(j >= 23){
divide(1 << 23);
j -= 23;
}
divide(1 << j);
multiply(1, 1);
divide(2);
m = numToString();
} else {
multiply(0, z);
multiply(1 << -e, 0);
m = numToString() + repeat.call(ZERO, f);
}
}
if(f > 0){
k = m.length;
m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f));
} else {
m = s + m;
} return m;
}
});
/***/ },
/* 84 */
/***/ function(module, exports, __webpack_require__) {
var cof = __webpack_require__(32);
module.exports = function(it, msg){
if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg);
return +it;
};
/***/ },
/* 85 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var toInteger = __webpack_require__(36)
, defined = __webpack_require__(33);
module.exports = function repeat(count){
var str = String(defined(this))
, res = ''
, n = toInteger(count);
if(n < 0 || n == Infinity)throw RangeError("Count can't be negative");
for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str;
return res;
};
/***/ },
/* 86 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $fails = __webpack_require__(5)
, aNumberValue = __webpack_require__(84)
, $toPrecision = 1..toPrecision;
$export($export.P + $export.F * ($fails(function(){
// IE7-
return $toPrecision.call(1, undefined) !== '1';
}) || !$fails(function(){
// V8 ~ Android 4.3-
$toPrecision.call({});
})), 'Number', {
toPrecision: function toPrecision(precision){
var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!');
return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision);
}
});
/***/ },
/* 87 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.1 Number.EPSILON
var $export = __webpack_require__(6);
$export($export.S, 'Number', {EPSILON: Math.pow(2, -52)});
/***/ },
/* 88 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.2 Number.isFinite(number)
var $export = __webpack_require__(6)
, _isFinite = __webpack_require__(2).isFinite;
$export($export.S, 'Number', {
isFinite: function isFinite(it){
return typeof it == 'number' && _isFinite(it);
}
});
/***/ },
/* 89 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var $export = __webpack_require__(6);
$export($export.S, 'Number', {isInteger: __webpack_require__(90)});
/***/ },
/* 90 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.3 Number.isInteger(number)
var isObject = __webpack_require__(11)
, floor = Math.floor;
module.exports = function isInteger(it){
return !isObject(it) && isFinite(it) && floor(it) === it;
};
/***/ },
/* 91 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.4 Number.isNaN(number)
var $export = __webpack_require__(6);
$export($export.S, 'Number', {
isNaN: function isNaN(number){
return number != number;
}
});
/***/ },
/* 92 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.5 Number.isSafeInteger(number)
var $export = __webpack_require__(6)
, isInteger = __webpack_require__(90)
, abs = Math.abs;
$export($export.S, 'Number', {
isSafeInteger: function isSafeInteger(number){
return isInteger(number) && abs(number) <= 0x1fffffffffffff;
}
});
/***/ },
/* 93 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.6 Number.MAX_SAFE_INTEGER
var $export = __webpack_require__(6);
$export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff});
/***/ },
/* 94 */
/***/ function(module, exports, __webpack_require__) {
// 20.1.2.10 Number.MIN_SAFE_INTEGER
var $export = __webpack_require__(6);
$export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff});
/***/ },
/* 95 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseFloat = __webpack_require__(96);
// 20.1.2.12 Number.parseFloat(string)
$export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat});
/***/ },
/* 96 */
/***/ function(module, exports, __webpack_require__) {
var $parseFloat = __webpack_require__(2).parseFloat
, $trim = __webpack_require__(81).trim;
module.exports = 1 / $parseFloat(__webpack_require__(82) + '-0') !== -Infinity ? function parseFloat(str){
var string = $trim(String(str), 3)
, result = $parseFloat(string);
return result === 0 && string.charAt(0) == '-' ? -0 : result;
} : $parseFloat;
/***/ },
/* 97 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseInt = __webpack_require__(98);
// 20.1.2.13 Number.parseInt(string, radix)
$export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt});
/***/ },
/* 98 */
/***/ function(module, exports, __webpack_require__) {
var $parseInt = __webpack_require__(2).parseInt
, $trim = __webpack_require__(81).trim
, ws = __webpack_require__(82)
, hex = /^[\-+]?0[xX]/;
module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){
var string = $trim(String(str), 3);
return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10));
} : $parseInt;
/***/ },
/* 99 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseInt = __webpack_require__(98);
// 18.2.5 parseInt(string, radix)
$export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt});
/***/ },
/* 100 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $parseFloat = __webpack_require__(96);
// 18.2.4 parseFloat(string)
$export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat});
/***/ },
/* 101 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.3 Math.acosh(x)
var $export = __webpack_require__(6)
, log1p = __webpack_require__(102)
, sqrt = Math.sqrt
, $acosh = Math.acosh;
$export($export.S + $export.F * !($acosh
// V8 bug: https://code.google.com/p/v8/issues/detail?id=3509
&& Math.floor($acosh(Number.MAX_VALUE)) == 710
// Tor Browser bug: Math.acosh(Infinity) -> NaN
&& $acosh(Infinity) == Infinity
), 'Math', {
acosh: function acosh(x){
return (x = +x) < 1 ? NaN : x > 94906265.62425156
? Math.log(x) + Math.LN2
: log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1));
}
});
/***/ },
/* 102 */
/***/ function(module, exports) {
// 20.2.2.20 Math.log1p(x)
module.exports = Math.log1p || function log1p(x){
return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x);
};
/***/ },
/* 103 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.5 Math.asinh(x)
var $export = __webpack_require__(6)
, $asinh = Math.asinh;
function asinh(x){
return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1));
}
// Tor Browser bug: Math.asinh(0) -> -0
$export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh});
/***/ },
/* 104 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.7 Math.atanh(x)
var $export = __webpack_require__(6)
, $atanh = Math.atanh;
// Tor Browser bug: Math.atanh(-0) -> 0
$export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', {
atanh: function atanh(x){
return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2;
}
});
/***/ },
/* 105 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.9 Math.cbrt(x)
var $export = __webpack_require__(6)
, sign = __webpack_require__(106);
$export($export.S, 'Math', {
cbrt: function cbrt(x){
return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3);
}
});
/***/ },
/* 106 */
/***/ function(module, exports) {
// 20.2.2.28 Math.sign(x)
module.exports = Math.sign || function sign(x){
return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1;
};
/***/ },
/* 107 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.11 Math.clz32(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
clz32: function clz32(x){
return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32;
}
});
/***/ },
/* 108 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.12 Math.cosh(x)
var $export = __webpack_require__(6)
, exp = Math.exp;
$export($export.S, 'Math', {
cosh: function cosh(x){
return (exp(x = +x) + exp(-x)) / 2;
}
});
/***/ },
/* 109 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.14 Math.expm1(x)
var $export = __webpack_require__(6)
, $expm1 = __webpack_require__(110);
$export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1});
/***/ },
/* 110 */
/***/ function(module, exports) {
// 20.2.2.14 Math.expm1(x)
var $expm1 = Math.expm1;
module.exports = (!$expm1
// Old FF bug
|| $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168
// Tor Browser bug
|| $expm1(-2e-17) != -2e-17
) ? function expm1(x){
return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1;
} : $expm1;
/***/ },
/* 111 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.16 Math.fround(x)
var $export = __webpack_require__(6)
, sign = __webpack_require__(106)
, pow = Math.pow
, EPSILON = pow(2, -52)
, EPSILON32 = pow(2, -23)
, MAX32 = pow(2, 127) * (2 - EPSILON32)
, MIN32 = pow(2, -126);
var roundTiesToEven = function(n){
return n + 1 / EPSILON - 1 / EPSILON;
};
$export($export.S, 'Math', {
fround: function fround(x){
var $abs = Math.abs(x)
, $sign = sign(x)
, a, result;
if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32;
a = (1 + EPSILON32 / EPSILON) * $abs;
result = a - (a - $abs);
if(result > MAX32 || result != result)return $sign * Infinity;
return $sign * result;
}
});
/***/ },
/* 112 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.17 Math.hypot([value1[, value2[, … ]]])
var $export = __webpack_require__(6)
, abs = Math.abs;
$export($export.S, 'Math', {
hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars
var sum = 0
, i = 0
, aLen = arguments.length
, larg = 0
, arg, div;
while(i < aLen){
arg = abs(arguments[i++]);
if(larg < arg){
div = larg / arg;
sum = sum * div * div + 1;
larg = arg;
} else if(arg > 0){
div = arg / larg;
sum += div * div;
} else sum += arg;
}
return larg === Infinity ? Infinity : larg * Math.sqrt(sum);
}
});
/***/ },
/* 113 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.18 Math.imul(x, y)
var $export = __webpack_require__(6)
, $imul = Math.imul;
// some WebKit versions fails with big numbers, some has wrong arity
$export($export.S + $export.F * __webpack_require__(5)(function(){
return $imul(0xffffffff, 5) != -5 || $imul.length != 2;
}), 'Math', {
imul: function imul(x, y){
var UINT16 = 0xffff
, xn = +x
, yn = +y
, xl = UINT16 & xn
, yl = UINT16 & yn;
return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0);
}
});
/***/ },
/* 114 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.21 Math.log10(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
log10: function log10(x){
return Math.log(x) / Math.LN10;
}
});
/***/ },
/* 115 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.20 Math.log1p(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {log1p: __webpack_require__(102)});
/***/ },
/* 116 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.22 Math.log2(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
log2: function log2(x){
return Math.log(x) / Math.LN2;
}
});
/***/ },
/* 117 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.28 Math.sign(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {sign: __webpack_require__(106)});
/***/ },
/* 118 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.30 Math.sinh(x)
var $export = __webpack_require__(6)
, expm1 = __webpack_require__(110)
, exp = Math.exp;
// V8 near Chromium 38 has a problem with very small numbers
$export($export.S + $export.F * __webpack_require__(5)(function(){
return !Math.sinh(-2e-17) != -2e-17;
}), 'Math', {
sinh: function sinh(x){
return Math.abs(x = +x) < 1
? (expm1(x) - expm1(-x)) / 2
: (exp(x - 1) - exp(-x - 1)) * (Math.E / 2);
}
});
/***/ },
/* 119 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.33 Math.tanh(x)
var $export = __webpack_require__(6)
, expm1 = __webpack_require__(110)
, exp = Math.exp;
$export($export.S, 'Math', {
tanh: function tanh(x){
var a = expm1(x = +x)
, b = expm1(-x);
return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x));
}
});
/***/ },
/* 120 */
/***/ function(module, exports, __webpack_require__) {
// 20.2.2.34 Math.trunc(x)
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
trunc: function trunc(it){
return (it > 0 ? Math.floor : Math.ceil)(it);
}
});
/***/ },
/* 121 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, toIndex = __webpack_require__(37)
, fromCharCode = String.fromCharCode
, $fromCodePoint = String.fromCodePoint;
// length should be 1, old FF problem
$export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', {
// 21.1.2.2 String.fromCodePoint(...codePoints)
fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars
var res = []
, aLen = arguments.length
, i = 0
, code;
while(aLen > i){
code = +arguments[i++];
if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point');
res.push(code < 0x10000
? fromCharCode(code)
: fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00)
);
} return res.join('');
}
});
/***/ },
/* 122 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, toLength = __webpack_require__(35);
$export($export.S, 'String', {
// 21.1.2.4 String.raw(callSite, ...substitutions)
raw: function raw(callSite){
var tpl = toIObject(callSite.raw)
, len = toLength(tpl.length)
, aLen = arguments.length
, res = []
, i = 0;
while(len > i){
res.push(String(tpl[i++]));
if(i < aLen)res.push(String(arguments[i]));
} return res.join('');
}
});
/***/ },
/* 123 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.1.3.25 String.prototype.trim()
__webpack_require__(81)('trim', function($trim){
return function trim(){
return $trim(this, 3);
};
});
/***/ },
/* 124 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $at = __webpack_require__(125)(false);
$export($export.P, 'String', {
// 21.1.3.3 String.prototype.codePointAt(pos)
codePointAt: function codePointAt(pos){
return $at(this, pos);
}
});
/***/ },
/* 125 */
/***/ function(module, exports, __webpack_require__) {
var toInteger = __webpack_require__(36)
, defined = __webpack_require__(33);
// true -> String#at
// false -> String#codePointAt
module.exports = function(TO_STRING){
return function(that, pos){
var s = String(defined(that))
, i = toInteger(pos)
, l = s.length
, a, b;
if(i < 0 || i >= l)return TO_STRING ? '' : undefined;
a = s.charCodeAt(i);
return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff
? TO_STRING ? s.charAt(i) : a
: TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000;
};
};
/***/ },
/* 126 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.6 String.prototype.endsWith(searchString [, endPosition])
'use strict';
var $export = __webpack_require__(6)
, toLength = __webpack_require__(35)
, context = __webpack_require__(127)
, ENDS_WITH = 'endsWith'
, $endsWith = ''[ENDS_WITH];
$export($export.P + $export.F * __webpack_require__(129)(ENDS_WITH), 'String', {
endsWith: function endsWith(searchString /*, endPosition = @length */){
var that = context(this, searchString, ENDS_WITH)
, endPosition = arguments.length > 1 ? arguments[1] : undefined
, len = toLength(that.length)
, end = endPosition === undefined ? len : Math.min(toLength(endPosition), len)
, search = String(searchString);
return $endsWith
? $endsWith.call(that, search, end)
: that.slice(end - search.length, end) === search;
}
});
/***/ },
/* 127 */
/***/ function(module, exports, __webpack_require__) {
// helper for String#{startsWith, endsWith, includes}
var isRegExp = __webpack_require__(128)
, defined = __webpack_require__(33);
module.exports = function(that, searchString, NAME){
if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!");
return String(defined(that));
};
/***/ },
/* 128 */
/***/ function(module, exports, __webpack_require__) {
// 7.2.8 IsRegExp(argument)
var isObject = __webpack_require__(11)
, cof = __webpack_require__(32)
, MATCH = __webpack_require__(23)('match');
module.exports = function(it){
var isRegExp;
return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp');
};
/***/ },
/* 129 */
/***/ function(module, exports, __webpack_require__) {
var MATCH = __webpack_require__(23)('match');
module.exports = function(KEY){
var re = /./;
try {
'/./'[KEY](re);
} catch(e){
try {
re[MATCH] = false;
return !'/./'[KEY](re);
} catch(f){ /* empty */ }
} return true;
};
/***/ },
/* 130 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.7 String.prototype.includes(searchString, position = 0)
'use strict';
var $export = __webpack_require__(6)
, context = __webpack_require__(127)
, INCLUDES = 'includes';
$export($export.P + $export.F * __webpack_require__(129)(INCLUDES), 'String', {
includes: function includes(searchString /*, position = 0 */){
return !!~context(this, searchString, INCLUDES)
.indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined);
}
});
/***/ },
/* 131 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.P, 'String', {
// 21.1.3.13 String.prototype.repeat(count)
repeat: __webpack_require__(85)
});
/***/ },
/* 132 */
/***/ function(module, exports, __webpack_require__) {
// 21.1.3.18 String.prototype.startsWith(searchString [, position ])
'use strict';
var $export = __webpack_require__(6)
, toLength = __webpack_require__(35)
, context = __webpack_require__(127)
, STARTS_WITH = 'startsWith'
, $startsWith = ''[STARTS_WITH];
$export($export.P + $export.F * __webpack_require__(129)(STARTS_WITH), 'String', {
startsWith: function startsWith(searchString /*, position = 0 */){
var that = context(this, searchString, STARTS_WITH)
, index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length))
, search = String(searchString);
return $startsWith
? $startsWith.call(that, search, index)
: that.slice(index, index + search.length) === search;
}
});
/***/ },
/* 133 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $at = __webpack_require__(125)(true);
// 21.1.3.27 String.prototype[@@iterator]()
__webpack_require__(134)(String, 'String', function(iterated){
this._t = String(iterated); // target
this._i = 0; // next index
// 21.1.5.2.1 %StringIteratorPrototype%.next()
}, function(){
var O = this._t
, index = this._i
, point;
if(index >= O.length)return {value: undefined, done: true};
point = $at(O, index);
this._i += point.length;
return {value: point, done: false};
});
/***/ },
/* 134 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(26)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, hide = __webpack_require__(8)
, has = __webpack_require__(3)
, Iterators = __webpack_require__(135)
, $iterCreate = __webpack_require__(136)
, setToStringTag = __webpack_require__(22)
, getPrototypeOf = __webpack_require__(57)
, ITERATOR = __webpack_require__(23)('iterator')
, BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next`
, FF_ITERATOR = '@@iterator'
, KEYS = 'keys'
, VALUES = 'values';
var returnThis = function(){ return this; };
module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){
$iterCreate(Constructor, NAME, next);
var getMethod = function(kind){
if(!BUGGY && kind in proto)return proto[kind];
switch(kind){
case KEYS: return function keys(){ return new Constructor(this, kind); };
case VALUES: return function values(){ return new Constructor(this, kind); };
} return function entries(){ return new Constructor(this, kind); };
};
var TAG = NAME + ' Iterator'
, DEF_VALUES = DEFAULT == VALUES
, VALUES_BUG = false
, proto = Base.prototype
, $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT]
, $default = $native || getMethod(DEFAULT)
, $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined
, $anyNative = NAME == 'Array' ? proto.entries || $native : $native
, methods, key, IteratorPrototype;
// Fix native
if($anyNative){
IteratorPrototype = getPrototypeOf($anyNative.call(new Base));
if(IteratorPrototype !== Object.prototype){
// Set @@toStringTag to native iterators
setToStringTag(IteratorPrototype, TAG, true);
// fix for some old engines
if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis);
}
}
// fix Array#{values, @@iterator}.name in V8 / FF
if(DEF_VALUES && $native && $native.name !== VALUES){
VALUES_BUG = true;
$default = function values(){ return $native.call(this); };
}
// Define iterator
if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){
hide(proto, ITERATOR, $default);
}
// Plug for library
Iterators[NAME] = $default;
Iterators[TAG] = returnThis;
if(DEFAULT){
methods = {
values: DEF_VALUES ? $default : getMethod(VALUES),
keys: IS_SET ? $default : getMethod(KEYS),
entries: $entries
};
if(FORCED)for(key in methods){
if(!(key in proto))redefine(proto, key, methods[key]);
} else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods);
}
return methods;
};
/***/ },
/* 135 */
/***/ function(module, exports) {
module.exports = {};
/***/ },
/* 136 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var create = __webpack_require__(44)
, descriptor = __webpack_require__(15)
, setToStringTag = __webpack_require__(22)
, IteratorPrototype = {};
// 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
__webpack_require__(8)(IteratorPrototype, __webpack_require__(23)('iterator'), function(){ return this; });
module.exports = function(Constructor, NAME, next){
Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)});
setToStringTag(Constructor, NAME + ' Iterator');
};
/***/ },
/* 137 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.2 String.prototype.anchor(name)
__webpack_require__(138)('anchor', function(createHTML){
return function anchor(name){
return createHTML(this, 'a', 'name', name);
}
});
/***/ },
/* 138 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, fails = __webpack_require__(5)
, defined = __webpack_require__(33)
, quot = /"/g;
// B.2.3.2.1 CreateHTML(string, tag, attribute, value)
var createHTML = function(string, tag, attribute, value) {
var S = String(defined(string))
, p1 = '<' + tag;
if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '"') + '"';
return p1 + '>' + S + '</' + tag + '>';
};
module.exports = function(NAME, exec){
var O = {};
O[NAME] = exec(createHTML);
$export($export.P + $export.F * fails(function(){
var test = ''[NAME]('"');
return test !== test.toLowerCase() || test.split('"').length > 3;
}), 'String', O);
};
/***/ },
/* 139 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.3 String.prototype.big()
__webpack_require__(138)('big', function(createHTML){
return function big(){
return createHTML(this, 'big', '', '');
}
});
/***/ },
/* 140 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.4 String.prototype.blink()
__webpack_require__(138)('blink', function(createHTML){
return function blink(){
return createHTML(this, 'blink', '', '');
}
});
/***/ },
/* 141 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.5 String.prototype.bold()
__webpack_require__(138)('bold', function(createHTML){
return function bold(){
return createHTML(this, 'b', '', '');
}
});
/***/ },
/* 142 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.6 String.prototype.fixed()
__webpack_require__(138)('fixed', function(createHTML){
return function fixed(){
return createHTML(this, 'tt', '', '');
}
});
/***/ },
/* 143 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.7 String.prototype.fontcolor(color)
__webpack_require__(138)('fontcolor', function(createHTML){
return function fontcolor(color){
return createHTML(this, 'font', 'color', color);
}
});
/***/ },
/* 144 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.8 String.prototype.fontsize(size)
__webpack_require__(138)('fontsize', function(createHTML){
return function fontsize(size){
return createHTML(this, 'font', 'size', size);
}
});
/***/ },
/* 145 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.9 String.prototype.italics()
__webpack_require__(138)('italics', function(createHTML){
return function italics(){
return createHTML(this, 'i', '', '');
}
});
/***/ },
/* 146 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.10 String.prototype.link(url)
__webpack_require__(138)('link', function(createHTML){
return function link(url){
return createHTML(this, 'a', 'href', url);
}
});
/***/ },
/* 147 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.11 String.prototype.small()
__webpack_require__(138)('small', function(createHTML){
return function small(){
return createHTML(this, 'small', '', '');
}
});
/***/ },
/* 148 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.12 String.prototype.strike()
__webpack_require__(138)('strike', function(createHTML){
return function strike(){
return createHTML(this, 'strike', '', '');
}
});
/***/ },
/* 149 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.13 String.prototype.sub()
__webpack_require__(138)('sub', function(createHTML){
return function sub(){
return createHTML(this, 'sub', '', '');
}
});
/***/ },
/* 150 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// B.2.3.14 String.prototype.sup()
__webpack_require__(138)('sup', function(createHTML){
return function sup(){
return createHTML(this, 'sup', '', '');
}
});
/***/ },
/* 151 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.2.2 / 15.4.3.2 Array.isArray(arg)
var $export = __webpack_require__(6);
$export($export.S, 'Array', {isArray: __webpack_require__(43)});
/***/ },
/* 152 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var ctx = __webpack_require__(18)
, $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, call = __webpack_require__(153)
, isArrayIter = __webpack_require__(154)
, toLength = __webpack_require__(35)
, createProperty = __webpack_require__(155)
, getIterFn = __webpack_require__(156);
$export($export.S + $export.F * !__webpack_require__(157)(function(iter){ Array.from(iter); }), 'Array', {
// 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined)
from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){
var O = toObject(arrayLike)
, C = typeof this == 'function' ? this : Array
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, index = 0
, iterFn = getIterFn(O)
, length, result, step, iterator;
if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2);
// if object isn't iterable or it's array with default iterator - use simple case
if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){
for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){
createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value);
}
} else {
length = toLength(O.length);
for(result = new C(length); length > index; index++){
createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]);
}
}
result.length = index;
return result;
}
});
/***/ },
/* 153 */
/***/ function(module, exports, __webpack_require__) {
// call something on iterator step with safe closing on error
var anObject = __webpack_require__(10);
module.exports = function(iterator, fn, value, entries){
try {
return entries ? fn(anObject(value)[0], value[1]) : fn(value);
// 7.4.6 IteratorClose(iterator, completion)
} catch(e){
var ret = iterator['return'];
if(ret !== undefined)anObject(ret.call(iterator));
throw e;
}
};
/***/ },
/* 154 */
/***/ function(module, exports, __webpack_require__) {
// check on default Array iterator
var Iterators = __webpack_require__(135)
, ITERATOR = __webpack_require__(23)('iterator')
, ArrayProto = Array.prototype;
module.exports = function(it){
return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it);
};
/***/ },
/* 155 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $defineProperty = __webpack_require__(9)
, createDesc = __webpack_require__(15);
module.exports = function(object, index, value){
if(index in object)$defineProperty.f(object, index, createDesc(0, value));
else object[index] = value;
};
/***/ },
/* 156 */
/***/ function(module, exports, __webpack_require__) {
var classof = __webpack_require__(73)
, ITERATOR = __webpack_require__(23)('iterator')
, Iterators = __webpack_require__(135);
module.exports = __webpack_require__(7).getIteratorMethod = function(it){
if(it != undefined)return it[ITERATOR]
|| it['@@iterator']
|| Iterators[classof(it)];
};
/***/ },
/* 157 */
/***/ function(module, exports, __webpack_require__) {
var ITERATOR = __webpack_require__(23)('iterator')
, SAFE_CLOSING = false;
try {
var riter = [7][ITERATOR]();
riter['return'] = function(){ SAFE_CLOSING = true; };
Array.from(riter, function(){ throw 2; });
} catch(e){ /* empty */ }
module.exports = function(exec, skipClosing){
if(!skipClosing && !SAFE_CLOSING)return false;
var safe = false;
try {
var arr = [7]
, iter = arr[ITERATOR]();
iter.next = function(){ return {done: safe = true}; };
arr[ITERATOR] = function(){ return iter; };
exec(arr);
} catch(e){ /* empty */ }
return safe;
};
/***/ },
/* 158 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, createProperty = __webpack_require__(155);
// WebKit Array.of isn't generic
$export($export.S + $export.F * __webpack_require__(5)(function(){
function F(){}
return !(Array.of.call(F) instanceof F);
}), 'Array', {
// 22.1.2.3 Array.of( ...items)
of: function of(/* ...args */){
var index = 0
, aLen = arguments.length
, result = new (typeof this == 'function' ? this : Array)(aLen);
while(aLen > index)createProperty(result, index, arguments[index++]);
result.length = aLen;
return result;
}
});
/***/ },
/* 159 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.13 Array.prototype.join(separator)
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, arrayJoin = [].join;
// fallback for not array-like strings
$export($export.P + $export.F * (__webpack_require__(31) != Object || !__webpack_require__(160)(arrayJoin)), 'Array', {
join: function join(separator){
return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator);
}
});
/***/ },
/* 160 */
/***/ function(module, exports, __webpack_require__) {
var fails = __webpack_require__(5);
module.exports = function(method, arg){
return !!method && fails(function(){
arg ? method.call(null, function(){}, 1) : method.call(null);
});
};
/***/ },
/* 161 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, html = __webpack_require__(46)
, cof = __webpack_require__(32)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35)
, arraySlice = [].slice;
// fallback for not array-like ES3 strings and DOM objects
$export($export.P + $export.F * __webpack_require__(5)(function(){
if(html)arraySlice.call(html);
}), 'Array', {
slice: function slice(begin, end){
var len = toLength(this.length)
, klass = cof(this);
end = end === undefined ? len : end;
if(klass == 'Array')return arraySlice.call(this, begin, end);
var start = toIndex(begin, len)
, upTo = toIndex(end, len)
, size = toLength(upTo - start)
, cloned = Array(size)
, i = 0;
for(; i < size; i++)cloned[i] = klass == 'String'
? this.charAt(start + i)
: this[start + i];
return cloned;
}
});
/***/ },
/* 162 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, aFunction = __webpack_require__(19)
, toObject = __webpack_require__(56)
, fails = __webpack_require__(5)
, $sort = [].sort
, test = [1, 2, 3];
$export($export.P + $export.F * (fails(function(){
// IE8-
test.sort(undefined);
}) || !fails(function(){
// V8 bug
test.sort(null);
// Old WebKit
}) || !__webpack_require__(160)($sort)), 'Array', {
// 22.1.3.25 Array.prototype.sort(comparefn)
sort: function sort(comparefn){
return comparefn === undefined
? $sort.call(toObject(this))
: $sort.call(toObject(this), aFunction(comparefn));
}
});
/***/ },
/* 163 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $forEach = __webpack_require__(164)(0)
, STRICT = __webpack_require__(160)([].forEach, true);
$export($export.P + $export.F * !STRICT, 'Array', {
// 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg])
forEach: function forEach(callbackfn /* , thisArg */){
return $forEach(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 164 */
/***/ function(module, exports, __webpack_require__) {
// 0 -> Array#forEach
// 1 -> Array#map
// 2 -> Array#filter
// 3 -> Array#some
// 4 -> Array#every
// 5 -> Array#find
// 6 -> Array#findIndex
var ctx = __webpack_require__(18)
, IObject = __webpack_require__(31)
, toObject = __webpack_require__(56)
, toLength = __webpack_require__(35)
, asc = __webpack_require__(165);
module.exports = function(TYPE, $create){
var IS_MAP = TYPE == 1
, IS_FILTER = TYPE == 2
, IS_SOME = TYPE == 3
, IS_EVERY = TYPE == 4
, IS_FIND_INDEX = TYPE == 6
, NO_HOLES = TYPE == 5 || IS_FIND_INDEX
, create = $create || asc;
return function($this, callbackfn, that){
var O = toObject($this)
, self = IObject(O)
, f = ctx(callbackfn, that, 3)
, length = toLength(self.length)
, index = 0
, result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined
, val, res;
for(;length > index; index++)if(NO_HOLES || index in self){
val = self[index];
res = f(val, index, O);
if(TYPE){
if(IS_MAP)result[index] = res; // map
else if(res)switch(TYPE){
case 3: return true; // some
case 5: return val; // find
case 6: return index; // findIndex
case 2: result.push(val); // filter
} else if(IS_EVERY)return false; // every
}
}
return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result;
};
};
/***/ },
/* 165 */
/***/ function(module, exports, __webpack_require__) {
// 9.4.2.3 ArraySpeciesCreate(originalArray, length)
var speciesConstructor = __webpack_require__(166);
module.exports = function(original, length){
return new (speciesConstructor(original))(length);
};
/***/ },
/* 166 */
/***/ function(module, exports, __webpack_require__) {
var isObject = __webpack_require__(11)
, isArray = __webpack_require__(43)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(original){
var C;
if(isArray(original)){
C = original.constructor;
// cross-realm fallback
if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined;
if(isObject(C)){
C = C[SPECIES];
if(C === null)C = undefined;
}
} return C === undefined ? Array : C;
};
/***/ },
/* 167 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $map = __webpack_require__(164)(1);
$export($export.P + $export.F * !__webpack_require__(160)([].map, true), 'Array', {
// 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg])
map: function map(callbackfn /* , thisArg */){
return $map(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 168 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $filter = __webpack_require__(164)(2);
$export($export.P + $export.F * !__webpack_require__(160)([].filter, true), 'Array', {
// 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg])
filter: function filter(callbackfn /* , thisArg */){
return $filter(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 169 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $some = __webpack_require__(164)(3);
$export($export.P + $export.F * !__webpack_require__(160)([].some, true), 'Array', {
// 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg])
some: function some(callbackfn /* , thisArg */){
return $some(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 170 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $every = __webpack_require__(164)(4);
$export($export.P + $export.F * !__webpack_require__(160)([].every, true), 'Array', {
// 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg])
every: function every(callbackfn /* , thisArg */){
return $every(this, callbackfn, arguments[1]);
}
});
/***/ },
/* 171 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $reduce = __webpack_require__(172);
$export($export.P + $export.F * !__webpack_require__(160)([].reduce, true), 'Array', {
// 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue])
reduce: function reduce(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], false);
}
});
/***/ },
/* 172 */
/***/ function(module, exports, __webpack_require__) {
var aFunction = __webpack_require__(19)
, toObject = __webpack_require__(56)
, IObject = __webpack_require__(31)
, toLength = __webpack_require__(35);
module.exports = function(that, callbackfn, aLen, memo, isRight){
aFunction(callbackfn);
var O = toObject(that)
, self = IObject(O)
, length = toLength(O.length)
, index = isRight ? length - 1 : 0
, i = isRight ? -1 : 1;
if(aLen < 2)for(;;){
if(index in self){
memo = self[index];
index += i;
break;
}
index += i;
if(isRight ? index < 0 : length <= index){
throw TypeError('Reduce of empty array with no initial value');
}
}
for(;isRight ? index >= 0 : length > index; index += i)if(index in self){
memo = callbackfn(memo, self[index], index, O);
}
return memo;
};
/***/ },
/* 173 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $reduce = __webpack_require__(172);
$export($export.P + $export.F * !__webpack_require__(160)([].reduceRight, true), 'Array', {
// 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue])
reduceRight: function reduceRight(callbackfn /* , initialValue */){
return $reduce(this, callbackfn, arguments.length, arguments[1], true);
}
});
/***/ },
/* 174 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $indexOf = __webpack_require__(34)(false)
, $native = [].indexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(160)($native)), 'Array', {
// 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex])
indexOf: function indexOf(searchElement /*, fromIndex = 0 */){
return NEGATIVE_ZERO
// convert -0 to +0
? $native.apply(this, arguments) || 0
: $indexOf(this, searchElement, arguments[1]);
}
});
/***/ },
/* 175 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toIObject = __webpack_require__(30)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, $native = [].lastIndexOf
, NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0;
$export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(160)($native)), 'Array', {
// 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex])
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){
// convert -0 to +0
if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0;
var O = toIObject(this)
, length = toLength(O.length)
, index = length - 1;
if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1]));
if(index < 0)index = length + index;
for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0;
return -1;
}
});
/***/ },
/* 176 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
var $export = __webpack_require__(6);
$export($export.P, 'Array', {copyWithin: __webpack_require__(177)});
__webpack_require__(178)('copyWithin');
/***/ },
/* 177 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length)
'use strict';
var toObject = __webpack_require__(56)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35);
module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){
var O = toObject(this)
, len = toLength(O.length)
, to = toIndex(target, len)
, from = toIndex(start, len)
, end = arguments.length > 2 ? arguments[2] : undefined
, count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to)
, inc = 1;
if(from < to && to < from + count){
inc = -1;
from += count - 1;
to += count - 1;
}
while(count-- > 0){
if(from in O)O[to] = O[from];
else delete O[to];
to += inc;
from += inc;
} return O;
};
/***/ },
/* 178 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.31 Array.prototype[@@unscopables]
var UNSCOPABLES = __webpack_require__(23)('unscopables')
, ArrayProto = Array.prototype;
if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(8)(ArrayProto, UNSCOPABLES, {});
module.exports = function(key){
ArrayProto[UNSCOPABLES][key] = true;
};
/***/ },
/* 179 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
var $export = __webpack_require__(6);
$export($export.P, 'Array', {fill: __webpack_require__(180)});
__webpack_require__(178)('fill');
/***/ },
/* 180 */
/***/ function(module, exports, __webpack_require__) {
// 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length)
'use strict';
var toObject = __webpack_require__(56)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35);
module.exports = function fill(value /*, start = 0, end = @length */){
var O = toObject(this)
, length = toLength(O.length)
, aLen = arguments.length
, index = toIndex(aLen > 1 ? arguments[1] : undefined, length)
, end = aLen > 2 ? arguments[2] : undefined
, endPos = end === undefined ? length : toIndex(end, length);
while(endPos > index)O[index++] = value;
return O;
};
/***/ },
/* 181 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined)
var $export = __webpack_require__(6)
, $find = __webpack_require__(164)(5)
, KEY = 'find'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
find: function find(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(178)(KEY);
/***/ },
/* 182 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined)
var $export = __webpack_require__(6)
, $find = __webpack_require__(164)(6)
, KEY = 'findIndex'
, forced = true;
// Shouldn't skip holes
if(KEY in [])Array(1)[KEY](function(){ forced = false; });
$export($export.P + $export.F * forced, 'Array', {
findIndex: function findIndex(callbackfn/*, that = undefined */){
return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(178)(KEY);
/***/ },
/* 183 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var addToUnscopables = __webpack_require__(178)
, step = __webpack_require__(184)
, Iterators = __webpack_require__(135)
, toIObject = __webpack_require__(30);
// 22.1.3.4 Array.prototype.entries()
// 22.1.3.13 Array.prototype.keys()
// 22.1.3.29 Array.prototype.values()
// 22.1.3.30 Array.prototype[@@iterator]()
module.exports = __webpack_require__(134)(Array, 'Array', function(iterated, kind){
this._t = toIObject(iterated); // target
this._i = 0; // next index
this._k = kind; // kind
// 22.1.5.2.1 %ArrayIteratorPrototype%.next()
}, function(){
var O = this._t
, kind = this._k
, index = this._i++;
if(!O || index >= O.length){
this._t = undefined;
return step(1);
}
if(kind == 'keys' )return step(0, index);
if(kind == 'values')return step(0, O[index]);
return step(0, [index, O[index]]);
}, 'values');
// argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7)
Iterators.Arguments = Iterators.Array;
addToUnscopables('keys');
addToUnscopables('values');
addToUnscopables('entries');
/***/ },
/* 184 */
/***/ function(module, exports) {
module.exports = function(done, value){
return {value: value, done: !!done};
};
/***/ },
/* 185 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(186)('Array');
/***/ },
/* 186 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, dP = __webpack_require__(9)
, DESCRIPTORS = __webpack_require__(4)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(KEY){
var C = global[KEY];
if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, {
configurable: true,
get: function(){ return this; }
});
};
/***/ },
/* 187 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, inheritIfRequired = __webpack_require__(80)
, dP = __webpack_require__(9).f
, gOPN = __webpack_require__(48).f
, isRegExp = __webpack_require__(128)
, $flags = __webpack_require__(188)
, $RegExp = global.RegExp
, Base = $RegExp
, proto = $RegExp.prototype
, re1 = /a/g
, re2 = /a/g
// "new" creates a new object, old webkit buggy here
, CORRECT_NEW = new $RegExp(re1) !== re1;
if(__webpack_require__(4) && (!CORRECT_NEW || __webpack_require__(5)(function(){
re2[__webpack_require__(23)('match')] = false;
// RegExp constructor can alter flags and IsRegExp works correct with @@match
return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i';
}))){
$RegExp = function RegExp(p, f){
var tiRE = this instanceof $RegExp
, piRE = isRegExp(p)
, fiU = f === undefined;
return !tiRE && piRE && p.constructor === $RegExp && fiU ? p
: inheritIfRequired(CORRECT_NEW
? new Base(piRE && !fiU ? p.source : p, f)
: Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f)
, tiRE ? this : proto, $RegExp);
};
var proxy = function(key){
key in $RegExp || dP($RegExp, key, {
configurable: true,
get: function(){ return Base[key]; },
set: function(it){ Base[key] = it; }
});
};
for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]);
proto.constructor = $RegExp;
$RegExp.prototype = proto;
__webpack_require__(16)(global, 'RegExp', $RegExp);
}
__webpack_require__(186)('RegExp');
/***/ },
/* 188 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 21.2.5.3 get RegExp.prototype.flags
var anObject = __webpack_require__(10);
module.exports = function(){
var that = anObject(this)
, result = '';
if(that.global) result += 'g';
if(that.ignoreCase) result += 'i';
if(that.multiline) result += 'm';
if(that.unicode) result += 'u';
if(that.sticky) result += 'y';
return result;
};
/***/ },
/* 189 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
__webpack_require__(190);
var anObject = __webpack_require__(10)
, $flags = __webpack_require__(188)
, DESCRIPTORS = __webpack_require__(4)
, TO_STRING = 'toString'
, $toString = /./[TO_STRING];
var define = function(fn){
__webpack_require__(16)(RegExp.prototype, TO_STRING, fn, true);
};
// 21.2.5.14 RegExp.prototype.toString()
if(__webpack_require__(5)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){
define(function toString(){
var R = anObject(this);
return '/'.concat(R.source, '/',
'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined);
});
// FF44- RegExp#toString has a wrong name
} else if($toString.name != TO_STRING){
define(function toString(){
return $toString.call(this);
});
}
/***/ },
/* 190 */
/***/ function(module, exports, __webpack_require__) {
// 21.2.5.3 get RegExp.prototype.flags()
if(__webpack_require__(4) && /./g.flags != 'g')__webpack_require__(9).f(RegExp.prototype, 'flags', {
configurable: true,
get: __webpack_require__(188)
});
/***/ },
/* 191 */
/***/ function(module, exports, __webpack_require__) {
// @@match logic
__webpack_require__(192)('match', 1, function(defined, MATCH, $match){
// 21.1.3.11 String.prototype.match(regexp)
return [function match(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[MATCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O));
}, $match];
});
/***/ },
/* 192 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var hide = __webpack_require__(8)
, redefine = __webpack_require__(16)
, fails = __webpack_require__(5)
, defined = __webpack_require__(33)
, wks = __webpack_require__(23);
module.exports = function(KEY, length, exec){
var SYMBOL = wks(KEY)
, fns = exec(defined, SYMBOL, ''[KEY])
, strfn = fns[0]
, rxfn = fns[1];
if(fails(function(){
var O = {};
O[SYMBOL] = function(){ return 7; };
return ''[KEY](O) != 7;
})){
redefine(String.prototype, KEY, strfn);
hide(RegExp.prototype, SYMBOL, length == 2
// 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
// 21.2.5.11 RegExp.prototype[@@split](string, limit)
? function(string, arg){ return rxfn.call(string, this, arg); }
// 21.2.5.6 RegExp.prototype[@@match](string)
// 21.2.5.9 RegExp.prototype[@@search](string)
: function(string){ return rxfn.call(string, this); }
);
}
};
/***/ },
/* 193 */
/***/ function(module, exports, __webpack_require__) {
// @@replace logic
__webpack_require__(192)('replace', 2, function(defined, REPLACE, $replace){
// 21.1.3.14 String.prototype.replace(searchValue, replaceValue)
return [function replace(searchValue, replaceValue){
'use strict';
var O = defined(this)
, fn = searchValue == undefined ? undefined : searchValue[REPLACE];
return fn !== undefined
? fn.call(searchValue, O, replaceValue)
: $replace.call(String(O), searchValue, replaceValue);
}, $replace];
});
/***/ },
/* 194 */
/***/ function(module, exports, __webpack_require__) {
// @@search logic
__webpack_require__(192)('search', 1, function(defined, SEARCH, $search){
// 21.1.3.15 String.prototype.search(regexp)
return [function search(regexp){
'use strict';
var O = defined(this)
, fn = regexp == undefined ? undefined : regexp[SEARCH];
return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O));
}, $search];
});
/***/ },
/* 195 */
/***/ function(module, exports, __webpack_require__) {
// @@split logic
__webpack_require__(192)('split', 2, function(defined, SPLIT, $split){
'use strict';
var isRegExp = __webpack_require__(128)
, _split = $split
, $push = [].push
, $SPLIT = 'split'
, LENGTH = 'length'
, LAST_INDEX = 'lastIndex';
if(
'abbc'[$SPLIT](/(b)*/)[1] == 'c' ||
'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 ||
'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 ||
'.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 ||
'.'[$SPLIT](/()()/)[LENGTH] > 1 ||
''[$SPLIT](/.?/)[LENGTH]
){
var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group
// based on es5-shim implementation, need to rework it
$split = function(separator, limit){
var string = String(this);
if(separator === undefined && limit === 0)return [];
// If `separator` is not a regex, use native split
if(!isRegExp(separator))return _split.call(string, separator, limit);
var output = [];
var flags = (separator.ignoreCase ? 'i' : '') +
(separator.multiline ? 'm' : '') +
(separator.unicode ? 'u' : '') +
(separator.sticky ? 'y' : '');
var lastLastIndex = 0;
var splitLimit = limit === undefined ? 4294967295 : limit >>> 0;
// Make `global` and avoid `lastIndex` issues by working with a copy
var separatorCopy = new RegExp(separator.source, flags + 'g');
var separator2, match, lastIndex, lastLength, i;
// Doesn't need flags gy, but they don't hurt
if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags);
while(match = separatorCopy.exec(string)){
// `separatorCopy.lastIndex` is not reliable cross-browser
lastIndex = match.index + match[0][LENGTH];
if(lastIndex > lastLastIndex){
output.push(string.slice(lastLastIndex, match.index));
// Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG
if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){
for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined;
});
if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1));
lastLength = match[0][LENGTH];
lastLastIndex = lastIndex;
if(output[LENGTH] >= splitLimit)break;
}
if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop
}
if(lastLastIndex === string[LENGTH]){
if(lastLength || !separatorCopy.test(''))output.push('');
} else output.push(string.slice(lastLastIndex));
return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output;
};
// Chakra, V8
} else if('0'[$SPLIT](undefined, 0)[LENGTH]){
$split = function(separator, limit){
return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit);
};
}
// 21.1.3.17 String.prototype.split(separator, limit)
return [function split(separator, limit){
var O = defined(this)
, fn = separator == undefined ? undefined : separator[SPLIT];
return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit);
}, $split];
});
/***/ },
/* 196 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var LIBRARY = __webpack_require__(26)
, global = __webpack_require__(2)
, ctx = __webpack_require__(18)
, classof = __webpack_require__(73)
, $export = __webpack_require__(6)
, isObject = __webpack_require__(11)
, aFunction = __webpack_require__(19)
, anInstance = __webpack_require__(197)
, forOf = __webpack_require__(198)
, speciesConstructor = __webpack_require__(199)
, task = __webpack_require__(200).set
, microtask = __webpack_require__(201)()
, PROMISE = 'Promise'
, TypeError = global.TypeError
, process = global.process
, $Promise = global[PROMISE]
, process = global.process
, isNode = classof(process) == 'process'
, empty = function(){ /* empty */ }
, Internal, GenericPromiseCapability, Wrapper;
var USE_NATIVE = !!function(){
try {
// correct subclassing with @@species support
var promise = $Promise.resolve(1)
, FakePromise = (promise.constructor = {})[__webpack_require__(23)('species')] = function(exec){ exec(empty, empty); };
// unhandled rejections tracking support, NodeJS Promise without it fails @@species test
return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise;
} catch(e){ /* empty */ }
}();
// helpers
var sameConstructor = function(a, b){
// with library wrapper special case
return a === b || a === $Promise && b === Wrapper;
};
var isThenable = function(it){
var then;
return isObject(it) && typeof (then = it.then) == 'function' ? then : false;
};
var newPromiseCapability = function(C){
return sameConstructor($Promise, C)
? new PromiseCapability(C)
: new GenericPromiseCapability(C);
};
var PromiseCapability = GenericPromiseCapability = function(C){
var resolve, reject;
this.promise = new C(function($$resolve, $$reject){
if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor');
resolve = $$resolve;
reject = $$reject;
});
this.resolve = aFunction(resolve);
this.reject = aFunction(reject);
};
var perform = function(exec){
try {
exec();
} catch(e){
return {error: e};
}
};
var notify = function(promise, isReject){
if(promise._n)return;
promise._n = true;
var chain = promise._c;
microtask(function(){
var value = promise._v
, ok = promise._s == 1
, i = 0;
var run = function(reaction){
var handler = ok ? reaction.ok : reaction.fail
, resolve = reaction.resolve
, reject = reaction.reject
, domain = reaction.domain
, result, then;
try {
if(handler){
if(!ok){
if(promise._h == 2)onHandleUnhandled(promise);
promise._h = 1;
}
if(handler === true)result = value;
else {
if(domain)domain.enter();
result = handler(value);
if(domain)domain.exit();
}
if(result === reaction.promise){
reject(TypeError('Promise-chain cycle'));
} else if(then = isThenable(result)){
then.call(result, resolve, reject);
} else resolve(result);
} else reject(value);
} catch(e){
reject(e);
}
};
while(chain.length > i)run(chain[i++]); // variable length - can't use forEach
promise._c = [];
promise._n = false;
if(isReject && !promise._h)onUnhandled(promise);
});
};
var onUnhandled = function(promise){
task.call(global, function(){
var value = promise._v
, abrupt, handler, console;
if(isUnhandled(promise)){
abrupt = perform(function(){
if(isNode){
process.emit('unhandledRejection', value, promise);
} else if(handler = global.onunhandledrejection){
handler({promise: promise, reason: value});
} else if((console = global.console) && console.error){
console.error('Unhandled promise rejection', value);
}
});
// Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should
promise._h = isNode || isUnhandled(promise) ? 2 : 1;
} promise._a = undefined;
if(abrupt)throw abrupt.error;
});
};
var isUnhandled = function(promise){
if(promise._h == 1)return false;
var chain = promise._a || promise._c
, i = 0
, reaction;
while(chain.length > i){
reaction = chain[i++];
if(reaction.fail || !isUnhandled(reaction.promise))return false;
} return true;
};
var onHandleUnhandled = function(promise){
task.call(global, function(){
var handler;
if(isNode){
process.emit('rejectionHandled', promise);
} else if(handler = global.onrejectionhandled){
handler({promise: promise, reason: promise._v});
}
});
};
var $reject = function(value){
var promise = this;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
promise._v = value;
promise._s = 2;
if(!promise._a)promise._a = promise._c.slice();
notify(promise, true);
};
var $resolve = function(value){
var promise = this
, then;
if(promise._d)return;
promise._d = true;
promise = promise._w || promise; // unwrap
try {
if(promise === value)throw TypeError("Promise can't be resolved itself");
if(then = isThenable(value)){
microtask(function(){
var wrapper = {_w: promise, _d: false}; // wrap
try {
then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1));
} catch(e){
$reject.call(wrapper, e);
}
});
} else {
promise._v = value;
promise._s = 1;
notify(promise, false);
}
} catch(e){
$reject.call({_w: promise, _d: false}, e); // wrap
}
};
// constructor polyfill
if(!USE_NATIVE){
// 25.4.3.1 Promise(executor)
$Promise = function Promise(executor){
anInstance(this, $Promise, PROMISE, '_h');
aFunction(executor);
Internal.call(this);
try {
executor(ctx($resolve, this, 1), ctx($reject, this, 1));
} catch(err){
$reject.call(this, err);
}
};
Internal = function Promise(executor){
this._c = []; // <- awaiting reactions
this._a = undefined; // <- checked in isUnhandled reactions
this._s = 0; // <- state
this._d = false; // <- done
this._v = undefined; // <- value
this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled
this._n = false; // <- notify
};
Internal.prototype = __webpack_require__(202)($Promise.prototype, {
// 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected)
then: function then(onFulfilled, onRejected){
var reaction = newPromiseCapability(speciesConstructor(this, $Promise));
reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true;
reaction.fail = typeof onRejected == 'function' && onRejected;
reaction.domain = isNode ? process.domain : undefined;
this._c.push(reaction);
if(this._a)this._a.push(reaction);
if(this._s)notify(this, false);
return reaction.promise;
},
// 25.4.5.1 Promise.prototype.catch(onRejected)
'catch': function(onRejected){
return this.then(undefined, onRejected);
}
});
PromiseCapability = function(){
var promise = new Internal;
this.promise = promise;
this.resolve = ctx($resolve, promise, 1);
this.reject = ctx($reject, promise, 1);
};
}
$export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise});
__webpack_require__(22)($Promise, PROMISE);
__webpack_require__(186)(PROMISE);
Wrapper = __webpack_require__(7)[PROMISE];
// statics
$export($export.S + $export.F * !USE_NATIVE, PROMISE, {
// 25.4.4.5 Promise.reject(r)
reject: function reject(r){
var capability = newPromiseCapability(this)
, $$reject = capability.reject;
$$reject(r);
return capability.promise;
}
});
$export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, {
// 25.4.4.6 Promise.resolve(x)
resolve: function resolve(x){
// instanceof instead of internal slot check because we should fix it without replacement native Promise core
if(x instanceof $Promise && sameConstructor(x.constructor, this))return x;
var capability = newPromiseCapability(this)
, $$resolve = capability.resolve;
$$resolve(x);
return capability.promise;
}
});
$export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(157)(function(iter){
$Promise.all(iter)['catch'](empty);
})), PROMISE, {
// 25.4.4.1 Promise.all(iterable)
all: function all(iterable){
var C = this
, capability = newPromiseCapability(C)
, resolve = capability.resolve
, reject = capability.reject;
var abrupt = perform(function(){
var values = []
, index = 0
, remaining = 1;
forOf(iterable, false, function(promise){
var $index = index++
, alreadyCalled = false;
values.push(undefined);
remaining++;
C.resolve(promise).then(function(value){
if(alreadyCalled)return;
alreadyCalled = true;
values[$index] = value;
--remaining || resolve(values);
}, reject);
});
--remaining || resolve(values);
});
if(abrupt)reject(abrupt.error);
return capability.promise;
},
// 25.4.4.4 Promise.race(iterable)
race: function race(iterable){
var C = this
, capability = newPromiseCapability(C)
, reject = capability.reject;
var abrupt = perform(function(){
forOf(iterable, false, function(promise){
C.resolve(promise).then(capability.resolve, reject);
});
});
if(abrupt)reject(abrupt.error);
return capability.promise;
}
});
/***/ },
/* 197 */
/***/ function(module, exports) {
module.exports = function(it, Constructor, name, forbiddenField){
if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){
throw TypeError(name + ': incorrect invocation!');
} return it;
};
/***/ },
/* 198 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(18)
, call = __webpack_require__(153)
, isArrayIter = __webpack_require__(154)
, anObject = __webpack_require__(10)
, toLength = __webpack_require__(35)
, getIterFn = __webpack_require__(156)
, BREAK = {}
, RETURN = {};
var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){
var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable)
, f = ctx(fn, that, entries ? 2 : 1)
, index = 0
, length, step, iterator, result;
if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!');
// fast case for arrays with default iterator
if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){
result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]);
if(result === BREAK || result === RETURN)return result;
} else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){
result = call(iterator, f, step.value, entries);
if(result === BREAK || result === RETURN)return result;
}
};
exports.BREAK = BREAK;
exports.RETURN = RETURN;
/***/ },
/* 199 */
/***/ function(module, exports, __webpack_require__) {
// 7.3.20 SpeciesConstructor(O, defaultConstructor)
var anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, SPECIES = __webpack_require__(23)('species');
module.exports = function(O, D){
var C = anObject(O).constructor, S;
return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S);
};
/***/ },
/* 200 */
/***/ function(module, exports, __webpack_require__) {
var ctx = __webpack_require__(18)
, invoke = __webpack_require__(76)
, html = __webpack_require__(46)
, cel = __webpack_require__(13)
, global = __webpack_require__(2)
, process = global.process
, setTask = global.setImmediate
, clearTask = global.clearImmediate
, MessageChannel = global.MessageChannel
, counter = 0
, queue = {}
, ONREADYSTATECHANGE = 'onreadystatechange'
, defer, channel, port;
var run = function(){
var id = +this;
if(queue.hasOwnProperty(id)){
var fn = queue[id];
delete queue[id];
fn();
}
};
var listener = function(event){
run.call(event.data);
};
// Node.js 0.9+ & IE10+ has setImmediate, otherwise:
if(!setTask || !clearTask){
setTask = function setImmediate(fn){
var args = [], i = 1;
while(arguments.length > i)args.push(arguments[i++]);
queue[++counter] = function(){
invoke(typeof fn == 'function' ? fn : Function(fn), args);
};
defer(counter);
return counter;
};
clearTask = function clearImmediate(id){
delete queue[id];
};
// Node.js 0.8-
if(__webpack_require__(32)(process) == 'process'){
defer = function(id){
process.nextTick(ctx(run, id, 1));
};
// Browsers with MessageChannel, includes WebWorkers
} else if(MessageChannel){
channel = new MessageChannel;
port = channel.port2;
channel.port1.onmessage = listener;
defer = ctx(port.postMessage, port, 1);
// Browsers with postMessage, skip WebWorkers
// IE8 has postMessage, but it's sync & typeof its postMessage is 'object'
} else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){
defer = function(id){
global.postMessage(id + '', '*');
};
global.addEventListener('message', listener, false);
// IE8-
} else if(ONREADYSTATECHANGE in cel('script')){
defer = function(id){
html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){
html.removeChild(this);
run.call(id);
};
};
// Rest old browsers
} else {
defer = function(id){
setTimeout(ctx(run, id, 1), 0);
};
}
}
module.exports = {
set: setTask,
clear: clearTask
};
/***/ },
/* 201 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, macrotask = __webpack_require__(200).set
, Observer = global.MutationObserver || global.WebKitMutationObserver
, process = global.process
, Promise = global.Promise
, isNode = __webpack_require__(32)(process) == 'process';
module.exports = function(){
var head, last, notify;
var flush = function(){
var parent, fn;
if(isNode && (parent = process.domain))parent.exit();
while(head){
fn = head.fn;
head = head.next;
try {
fn();
} catch(e){
if(head)notify();
else last = undefined;
throw e;
}
} last = undefined;
if(parent)parent.enter();
};
// Node.js
if(isNode){
notify = function(){
process.nextTick(flush);
};
// browsers with MutationObserver
} else if(Observer){
var toggle = true
, node = document.createTextNode('');
new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new
notify = function(){
node.data = toggle = !toggle;
};
// environments with maybe non-completely correct, but existent Promise
} else if(Promise && Promise.resolve){
var promise = Promise.resolve();
notify = function(){
promise.then(flush);
};
// for other environments - macrotask based on:
// - setImmediate
// - MessageChannel
// - window.postMessag
// - onreadystatechange
// - setTimeout
} else {
notify = function(){
// strange IE + webpack dev server bug - use .call(global)
macrotask.call(global, flush);
};
}
return function(fn){
var task = {fn: fn, next: undefined};
if(last)last.next = task;
if(!head){
head = task;
notify();
} last = task;
};
};
/***/ },
/* 202 */
/***/ function(module, exports, __webpack_require__) {
var redefine = __webpack_require__(16);
module.exports = function(target, src, safe){
for(var key in src)redefine(target, key, src[key], safe);
return target;
};
/***/ },
/* 203 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(204);
// 23.1 Map Objects
module.exports = __webpack_require__(205)('Map', function(get){
return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.1.3.6 Map.prototype.get(key)
get: function get(key){
var entry = strong.getEntry(this, key);
return entry && entry.v;
},
// 23.1.3.9 Map.prototype.set(key, value)
set: function set(key, value){
return strong.def(this, key === 0 ? 0 : key, value);
}
}, strong, true);
/***/ },
/* 204 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var dP = __webpack_require__(9).f
, create = __webpack_require__(44)
, redefineAll = __webpack_require__(202)
, ctx = __webpack_require__(18)
, anInstance = __webpack_require__(197)
, defined = __webpack_require__(33)
, forOf = __webpack_require__(198)
, $iterDefine = __webpack_require__(134)
, step = __webpack_require__(184)
, setSpecies = __webpack_require__(186)
, DESCRIPTORS = __webpack_require__(4)
, fastKey = __webpack_require__(20).fastKey
, SIZE = DESCRIPTORS ? '_s' : 'size';
var getEntry = function(that, key){
// fast case
var index = fastKey(key), entry;
if(index !== 'F')return that._i[index];
// frozen object case
for(entry = that._f; entry; entry = entry.n){
if(entry.k == key)return entry;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = create(null); // index
that._f = undefined; // first entry
that._l = undefined; // last entry
that[SIZE] = 0; // size
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.1.3.1 Map.prototype.clear()
// 23.2.3.2 Set.prototype.clear()
clear: function clear(){
for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){
entry.r = true;
if(entry.p)entry.p = entry.p.n = undefined;
delete data[entry.i];
}
that._f = that._l = undefined;
that[SIZE] = 0;
},
// 23.1.3.3 Map.prototype.delete(key)
// 23.2.3.4 Set.prototype.delete(value)
'delete': function(key){
var that = this
, entry = getEntry(that, key);
if(entry){
var next = entry.n
, prev = entry.p;
delete that._i[entry.i];
entry.r = true;
if(prev)prev.n = next;
if(next)next.p = prev;
if(that._f == entry)that._f = next;
if(that._l == entry)that._l = prev;
that[SIZE]--;
} return !!entry;
},
// 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined)
// 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined)
forEach: function forEach(callbackfn /*, that = undefined */){
anInstance(this, C, 'forEach');
var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3)
, entry;
while(entry = entry ? entry.n : this._f){
f(entry.v, entry.k, this);
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
}
},
// 23.1.3.7 Map.prototype.has(key)
// 23.2.3.7 Set.prototype.has(value)
has: function has(key){
return !!getEntry(this, key);
}
});
if(DESCRIPTORS)dP(C.prototype, 'size', {
get: function(){
return defined(this[SIZE]);
}
});
return C;
},
def: function(that, key, value){
var entry = getEntry(that, key)
, prev, index;
// change existing entry
if(entry){
entry.v = value;
// create new entry
} else {
that._l = entry = {
i: index = fastKey(key, true), // <- index
k: key, // <- key
v: value, // <- value
p: prev = that._l, // <- previous entry
n: undefined, // <- next entry
r: false // <- removed
};
if(!that._f)that._f = entry;
if(prev)prev.n = entry;
that[SIZE]++;
// add to index
if(index !== 'F')that._i[index] = entry;
} return that;
},
getEntry: getEntry,
setStrong: function(C, NAME, IS_MAP){
// add .keys, .values, .entries, [@@iterator]
// 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11
$iterDefine(C, NAME, function(iterated, kind){
this._t = iterated; // target
this._k = kind; // kind
this._l = undefined; // previous
}, function(){
var that = this
, kind = that._k
, entry = that._l;
// revert to the last existing entry
while(entry && entry.r)entry = entry.p;
// get next entry
if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){
// or finish the iteration
that._t = undefined;
return step(1);
}
// return step by kind
if(kind == 'keys' )return step(0, entry.k);
if(kind == 'values')return step(0, entry.v);
return step(0, [entry.k, entry.v]);
}, IS_MAP ? 'entries' : 'values' , !IS_MAP, true);
// add [@@species], 23.1.2.2, 23.2.2.2
setSpecies(NAME);
}
};
/***/ },
/* 205 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, $export = __webpack_require__(6)
, redefine = __webpack_require__(16)
, redefineAll = __webpack_require__(202)
, meta = __webpack_require__(20)
, forOf = __webpack_require__(198)
, anInstance = __webpack_require__(197)
, isObject = __webpack_require__(11)
, fails = __webpack_require__(5)
, $iterDetect = __webpack_require__(157)
, setToStringTag = __webpack_require__(22)
, inheritIfRequired = __webpack_require__(80);
module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){
var Base = global[NAME]
, C = Base
, ADDER = IS_MAP ? 'set' : 'add'
, proto = C && C.prototype
, O = {};
var fixMethod = function(KEY){
var fn = proto[KEY];
redefine(proto, KEY,
KEY == 'delete' ? function(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'has' ? function has(a){
return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'get' ? function get(a){
return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a);
} : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; }
: function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; }
);
};
if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){
new C().entries().next();
}))){
// create collection constructor
C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER);
redefineAll(C.prototype, methods);
meta.NEED = true;
} else {
var instance = new C
// early implementations not supports chaining
, HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance
// V8 ~ Chromium 40- weak-collections throws on primitives, but should return false
, THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); })
// most early implementations doesn't supports iterables, most modern - not close it correctly
, ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new
// for early implementations -0 and +0 not the same
, BUGGY_ZERO = !IS_WEAK && fails(function(){
// V8 ~ Chromium 42- fails only with 5+ elements
var $instance = new C()
, index = 5;
while(index--)$instance[ADDER](index, index);
return !$instance.has(-0);
});
if(!ACCEPT_ITERABLES){
C = wrapper(function(target, iterable){
anInstance(target, C, NAME);
var that = inheritIfRequired(new Base, target, C);
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
return that;
});
C.prototype = proto;
proto.constructor = C;
}
if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){
fixMethod('delete');
fixMethod('has');
IS_MAP && fixMethod('get');
}
if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER);
// weak collections should not contains .clear method
if(IS_WEAK && proto.clear)delete proto.clear;
}
setToStringTag(C, NAME);
O[NAME] = C;
$export($export.G + $export.W + $export.F * (C != Base), O);
if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP);
return C;
};
/***/ },
/* 206 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var strong = __webpack_require__(204);
// 23.2 Set Objects
module.exports = __webpack_require__(205)('Set', function(get){
return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.2.3.1 Set.prototype.add(value)
add: function add(value){
return strong.def(this, value = value === 0 ? 0 : value, value);
}
}, strong);
/***/ },
/* 207 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var each = __webpack_require__(164)(0)
, redefine = __webpack_require__(16)
, meta = __webpack_require__(20)
, assign = __webpack_require__(67)
, weak = __webpack_require__(208)
, isObject = __webpack_require__(11)
, getWeak = meta.getWeak
, isExtensible = Object.isExtensible
, uncaughtFrozenStore = weak.ufstore
, tmp = {}
, InternalMap;
var wrapper = function(get){
return function WeakMap(){
return get(this, arguments.length > 0 ? arguments[0] : undefined);
};
};
var methods = {
// 23.3.3.3 WeakMap.prototype.get(key)
get: function get(key){
if(isObject(key)){
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).get(key);
return data ? data[this._i] : undefined;
}
},
// 23.3.3.5 WeakMap.prototype.set(key, value)
set: function set(key, value){
return weak.def(this, key, value);
}
};
// 23.3 WeakMap Objects
var $WeakMap = module.exports = __webpack_require__(205)('WeakMap', wrapper, methods, weak, true, true);
// IE11 WeakMap frozen keys fix
if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){
InternalMap = weak.getConstructor(wrapper);
assign(InternalMap.prototype, methods);
meta.NEED = true;
each(['delete', 'has', 'get', 'set'], function(key){
var proto = $WeakMap.prototype
, method = proto[key];
redefine(proto, key, function(a, b){
// store frozen objects on internal weakmap shim
if(isObject(a) && !isExtensible(a)){
if(!this._f)this._f = new InternalMap;
var result = this._f[key](a, b);
return key == 'set' ? this : result;
// store all the rest on native weakmap
} return method.call(this, a, b);
});
});
}
/***/ },
/* 208 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var redefineAll = __webpack_require__(202)
, getWeak = __webpack_require__(20).getWeak
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11)
, anInstance = __webpack_require__(197)
, forOf = __webpack_require__(198)
, createArrayMethod = __webpack_require__(164)
, $has = __webpack_require__(3)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, id = 0;
// fallback for uncaught frozen keys
var uncaughtFrozenStore = function(that){
return that._l || (that._l = new UncaughtFrozenStore);
};
var UncaughtFrozenStore = function(){
this.a = [];
};
var findUncaughtFrozen = function(store, key){
return arrayFind(store.a, function(it){
return it[0] === key;
});
};
UncaughtFrozenStore.prototype = {
get: function(key){
var entry = findUncaughtFrozen(this, key);
if(entry)return entry[1];
},
has: function(key){
return !!findUncaughtFrozen(this, key);
},
set: function(key, value){
var entry = findUncaughtFrozen(this, key);
if(entry)entry[1] = value;
else this.a.push([key, value]);
},
'delete': function(key){
var index = arrayFindIndex(this.a, function(it){
return it[0] === key;
});
if(~index)this.a.splice(index, 1);
return !!~index;
}
};
module.exports = {
getConstructor: function(wrapper, NAME, IS_MAP, ADDER){
var C = wrapper(function(that, iterable){
anInstance(that, C, NAME, '_i');
that._i = id++; // collection id
that._l = undefined; // leak store for uncaught frozen objects
if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that);
});
redefineAll(C.prototype, {
// 23.3.3.2 WeakMap.prototype.delete(key)
// 23.4.3.3 WeakSet.prototype.delete(value)
'delete': function(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this)['delete'](key);
return data && $has(data, this._i) && delete data[this._i];
},
// 23.3.3.4 WeakMap.prototype.has(key)
// 23.4.3.4 WeakSet.prototype.has(value)
has: function has(key){
if(!isObject(key))return false;
var data = getWeak(key);
if(data === true)return uncaughtFrozenStore(this).has(key);
return data && $has(data, this._i);
}
});
return C;
},
def: function(that, key, value){
var data = getWeak(anObject(key), true);
if(data === true)uncaughtFrozenStore(that).set(key, value);
else data[that._i] = value;
return that;
},
ufstore: uncaughtFrozenStore
};
/***/ },
/* 209 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var weak = __webpack_require__(208);
// 23.4 WeakSet Objects
__webpack_require__(205)('WeakSet', function(get){
return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); };
}, {
// 23.4.3.1 WeakSet.prototype.add(value)
add: function add(value){
return weak.def(this, value, true);
}
}, weak, false, true);
/***/ },
/* 210 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.1 Reflect.apply(target, thisArgument, argumentsList)
var $export = __webpack_require__(6)
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, rApply = (__webpack_require__(2).Reflect || {}).apply
, fApply = Function.apply;
// MS Edge argumentsList argument is optional
$export($export.S + $export.F * !__webpack_require__(5)(function(){
rApply(function(){});
}), 'Reflect', {
apply: function apply(target, thisArgument, argumentsList){
var T = aFunction(target)
, L = anObject(argumentsList);
return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L);
}
});
/***/ },
/* 211 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.2 Reflect.construct(target, argumentsList [, newTarget])
var $export = __webpack_require__(6)
, create = __webpack_require__(44)
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11)
, fails = __webpack_require__(5)
, bind = __webpack_require__(75)
, rConstruct = (__webpack_require__(2).Reflect || {}).construct;
// MS Edge supports only 2 arguments and argumentsList argument is optional
// FF Nightly sets third argument as `new.target`, but does not create `this` from it
var NEW_TARGET_BUG = fails(function(){
function F(){}
return !(rConstruct(function(){}, [], F) instanceof F);
});
var ARGS_BUG = !fails(function(){
rConstruct(function(){});
});
$export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', {
construct: function construct(Target, args /*, newTarget*/){
aFunction(Target);
anObject(args);
var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]);
if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget);
if(Target == newTarget){
// w/o altered newTarget, optimization for 0-4 arguments
switch(args.length){
case 0: return new Target;
case 1: return new Target(args[0]);
case 2: return new Target(args[0], args[1]);
case 3: return new Target(args[0], args[1], args[2]);
case 4: return new Target(args[0], args[1], args[2], args[3]);
}
// w/o altered newTarget, lot of arguments case
var $args = [null];
$args.push.apply($args, args);
return new (bind.apply(Target, $args));
}
// with altered newTarget, not support built-in constructors
var proto = newTarget.prototype
, instance = create(isObject(proto) ? proto : Object.prototype)
, result = Function.apply.call(Target, instance, args);
return isObject(result) ? result : instance;
}
});
/***/ },
/* 212 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.3 Reflect.defineProperty(target, propertyKey, attributes)
var dP = __webpack_require__(9)
, $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, toPrimitive = __webpack_require__(14);
// MS Edge has broken Reflect.defineProperty - throwing instead of returning false
$export($export.S + $export.F * __webpack_require__(5)(function(){
Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2});
}), 'Reflect', {
defineProperty: function defineProperty(target, propertyKey, attributes){
anObject(target);
propertyKey = toPrimitive(propertyKey, true);
anObject(attributes);
try {
dP.f(target, propertyKey, attributes);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 213 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.4 Reflect.deleteProperty(target, propertyKey)
var $export = __webpack_require__(6)
, gOPD = __webpack_require__(49).f
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
deleteProperty: function deleteProperty(target, propertyKey){
var desc = gOPD(anObject(target), propertyKey);
return desc && !desc.configurable ? false : delete target[propertyKey];
}
});
/***/ },
/* 214 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 26.1.5 Reflect.enumerate(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10);
var Enumerate = function(iterated){
this._t = anObject(iterated); // target
this._i = 0; // next index
var keys = this._k = [] // keys
, key;
for(key in iterated)keys.push(key);
};
__webpack_require__(136)(Enumerate, 'Object', function(){
var that = this
, keys = that._k
, key;
do {
if(that._i >= keys.length)return {value: undefined, done: true};
} while(!((key = keys[that._i++]) in that._t));
return {value: key, done: false};
});
$export($export.S, 'Reflect', {
enumerate: function enumerate(target){
return new Enumerate(target);
}
});
/***/ },
/* 215 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.6 Reflect.get(target, propertyKey [, receiver])
var gOPD = __webpack_require__(49)
, getPrototypeOf = __webpack_require__(57)
, has = __webpack_require__(3)
, $export = __webpack_require__(6)
, isObject = __webpack_require__(11)
, anObject = __webpack_require__(10);
function get(target, propertyKey/*, receiver*/){
var receiver = arguments.length < 3 ? target : arguments[2]
, desc, proto;
if(anObject(target) === receiver)return target[propertyKey];
if(desc = gOPD.f(target, propertyKey))return has(desc, 'value')
? desc.value
: desc.get !== undefined
? desc.get.call(receiver)
: undefined;
if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver);
}
$export($export.S, 'Reflect', {get: get});
/***/ },
/* 216 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey)
var gOPD = __webpack_require__(49)
, $export = __webpack_require__(6)
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){
return gOPD.f(anObject(target), propertyKey);
}
});
/***/ },
/* 217 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.8 Reflect.getPrototypeOf(target)
var $export = __webpack_require__(6)
, getProto = __webpack_require__(57)
, anObject = __webpack_require__(10);
$export($export.S, 'Reflect', {
getPrototypeOf: function getPrototypeOf(target){
return getProto(anObject(target));
}
});
/***/ },
/* 218 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.9 Reflect.has(target, propertyKey)
var $export = __webpack_require__(6);
$export($export.S, 'Reflect', {
has: function has(target, propertyKey){
return propertyKey in target;
}
});
/***/ },
/* 219 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.10 Reflect.isExtensible(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, $isExtensible = Object.isExtensible;
$export($export.S, 'Reflect', {
isExtensible: function isExtensible(target){
anObject(target);
return $isExtensible ? $isExtensible(target) : true;
}
});
/***/ },
/* 220 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.11 Reflect.ownKeys(target)
var $export = __webpack_require__(6);
$export($export.S, 'Reflect', {ownKeys: __webpack_require__(221)});
/***/ },
/* 221 */
/***/ function(module, exports, __webpack_require__) {
// all object keys, includes non-enumerable and symbols
var gOPN = __webpack_require__(48)
, gOPS = __webpack_require__(41)
, anObject = __webpack_require__(10)
, Reflect = __webpack_require__(2).Reflect;
module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){
var keys = gOPN.f(anObject(it))
, getSymbols = gOPS.f;
return getSymbols ? keys.concat(getSymbols(it)) : keys;
};
/***/ },
/* 222 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.12 Reflect.preventExtensions(target)
var $export = __webpack_require__(6)
, anObject = __webpack_require__(10)
, $preventExtensions = Object.preventExtensions;
$export($export.S, 'Reflect', {
preventExtensions: function preventExtensions(target){
anObject(target);
try {
if($preventExtensions)$preventExtensions(target);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 223 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.13 Reflect.set(target, propertyKey, V [, receiver])
var dP = __webpack_require__(9)
, gOPD = __webpack_require__(49)
, getPrototypeOf = __webpack_require__(57)
, has = __webpack_require__(3)
, $export = __webpack_require__(6)
, createDesc = __webpack_require__(15)
, anObject = __webpack_require__(10)
, isObject = __webpack_require__(11);
function set(target, propertyKey, V/*, receiver*/){
var receiver = arguments.length < 4 ? target : arguments[3]
, ownDesc = gOPD.f(anObject(target), propertyKey)
, existingDescriptor, proto;
if(!ownDesc){
if(isObject(proto = getPrototypeOf(target))){
return set(proto, propertyKey, V, receiver);
}
ownDesc = createDesc(0);
}
if(has(ownDesc, 'value')){
if(ownDesc.writable === false || !isObject(receiver))return false;
existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0);
existingDescriptor.value = V;
dP.f(receiver, propertyKey, existingDescriptor);
return true;
}
return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true);
}
$export($export.S, 'Reflect', {set: set});
/***/ },
/* 224 */
/***/ function(module, exports, __webpack_require__) {
// 26.1.14 Reflect.setPrototypeOf(target, proto)
var $export = __webpack_require__(6)
, setProto = __webpack_require__(71);
if(setProto)$export($export.S, 'Reflect', {
setPrototypeOf: function setPrototypeOf(target, proto){
setProto.check(target, proto);
try {
setProto.set(target, proto);
return true;
} catch(e){
return false;
}
}
});
/***/ },
/* 225 */
/***/ function(module, exports, __webpack_require__) {
// 20.3.3.1 / 15.9.4.4 Date.now()
var $export = __webpack_require__(6);
$export($export.S, 'Date', {now: function(){ return new Date().getTime(); }});
/***/ },
/* 226 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14);
$export($export.P + $export.F * __webpack_require__(5)(function(){
return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1;
}), 'Date', {
toJSON: function toJSON(key){
var O = toObject(this)
, pv = toPrimitive(O);
return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString();
}
});
/***/ },
/* 227 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString()
var $export = __webpack_require__(6)
, fails = __webpack_require__(5)
, getTime = Date.prototype.getTime;
var lz = function(num){
return num > 9 ? num : '0' + num;
};
// PhantomJS / old WebKit has a broken implementations
$export($export.P + $export.F * (fails(function(){
return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z';
}) || !fails(function(){
new Date(NaN).toISOString();
})), 'Date', {
toISOString: function toISOString(){
if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value');
var d = this
, y = d.getUTCFullYear()
, m = d.getUTCMilliseconds()
, s = y < 0 ? '-' : y > 9999 ? '+' : '';
return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) +
'-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) +
'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) +
':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z';
}
});
/***/ },
/* 228 */
/***/ function(module, exports, __webpack_require__) {
var DateProto = Date.prototype
, INVALID_DATE = 'Invalid Date'
, TO_STRING = 'toString'
, $toString = DateProto[TO_STRING]
, getTime = DateProto.getTime;
if(new Date(NaN) + '' != INVALID_DATE){
__webpack_require__(16)(DateProto, TO_STRING, function toString(){
var value = getTime.call(this);
return value === value ? $toString.call(this) : INVALID_DATE;
});
}
/***/ },
/* 229 */
/***/ function(module, exports, __webpack_require__) {
var TO_PRIMITIVE = __webpack_require__(23)('toPrimitive')
, proto = Date.prototype;
if(!(TO_PRIMITIVE in proto))__webpack_require__(8)(proto, TO_PRIMITIVE, __webpack_require__(230));
/***/ },
/* 230 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var anObject = __webpack_require__(10)
, toPrimitive = __webpack_require__(14)
, NUMBER = 'number';
module.exports = function(hint){
if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint');
return toPrimitive(anObject(this), hint != NUMBER);
};
/***/ },
/* 231 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, $typed = __webpack_require__(232)
, buffer = __webpack_require__(233)
, anObject = __webpack_require__(10)
, toIndex = __webpack_require__(37)
, toLength = __webpack_require__(35)
, isObject = __webpack_require__(11)
, ArrayBuffer = __webpack_require__(2).ArrayBuffer
, speciesConstructor = __webpack_require__(199)
, $ArrayBuffer = buffer.ArrayBuffer
, $DataView = buffer.DataView
, $isView = $typed.ABV && ArrayBuffer.isView
, $slice = $ArrayBuffer.prototype.slice
, VIEW = $typed.VIEW
, ARRAY_BUFFER = 'ArrayBuffer';
$export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer});
$export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, {
// 24.1.3.1 ArrayBuffer.isView(arg)
isView: function isView(it){
return $isView && $isView(it) || isObject(it) && VIEW in it;
}
});
$export($export.P + $export.U + $export.F * __webpack_require__(5)(function(){
return !new $ArrayBuffer(2).slice(1, undefined).byteLength;
}), ARRAY_BUFFER, {
// 24.1.4.3 ArrayBuffer.prototype.slice(start, end)
slice: function slice(start, end){
if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix
var len = anObject(this).byteLength
, first = toIndex(start, len)
, final = toIndex(end === undefined ? len : end, len)
, result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first))
, viewS = new $DataView(this)
, viewT = new $DataView(result)
, index = 0;
while(first < final){
viewT.setUint8(index++, viewS.getUint8(first++));
} return result;
}
});
__webpack_require__(186)(ARRAY_BUFFER);
/***/ },
/* 232 */
/***/ function(module, exports, __webpack_require__) {
var global = __webpack_require__(2)
, hide = __webpack_require__(8)
, uid = __webpack_require__(17)
, TYPED = uid('typed_array')
, VIEW = uid('view')
, ABV = !!(global.ArrayBuffer && global.DataView)
, CONSTR = ABV
, i = 0, l = 9, Typed;
var TypedArrayConstructors = (
'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array'
).split(',');
while(i < l){
if(Typed = global[TypedArrayConstructors[i++]]){
hide(Typed.prototype, TYPED, true);
hide(Typed.prototype, VIEW, true);
} else CONSTR = false;
}
module.exports = {
ABV: ABV,
CONSTR: CONSTR,
TYPED: TYPED,
VIEW: VIEW
};
/***/ },
/* 233 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var global = __webpack_require__(2)
, DESCRIPTORS = __webpack_require__(4)
, LIBRARY = __webpack_require__(26)
, $typed = __webpack_require__(232)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, fails = __webpack_require__(5)
, anInstance = __webpack_require__(197)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, gOPN = __webpack_require__(48).f
, dP = __webpack_require__(9).f
, arrayFill = __webpack_require__(180)
, setToStringTag = __webpack_require__(22)
, ARRAY_BUFFER = 'ArrayBuffer'
, DATA_VIEW = 'DataView'
, PROTOTYPE = 'prototype'
, WRONG_LENGTH = 'Wrong length!'
, WRONG_INDEX = 'Wrong index!'
, $ArrayBuffer = global[ARRAY_BUFFER]
, $DataView = global[DATA_VIEW]
, Math = global.Math
, RangeError = global.RangeError
, Infinity = global.Infinity
, BaseBuffer = $ArrayBuffer
, abs = Math.abs
, pow = Math.pow
, floor = Math.floor
, log = Math.log
, LN2 = Math.LN2
, BUFFER = 'buffer'
, BYTE_LENGTH = 'byteLength'
, BYTE_OFFSET = 'byteOffset'
, $BUFFER = DESCRIPTORS ? '_b' : BUFFER
, $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH
, $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET;
// IEEE754 conversions based on https://github.com/feross/ieee754
var packIEEE754 = function(value, mLen, nBytes){
var buffer = Array(nBytes)
, eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0
, i = 0
, s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0
, e, m, c;
value = abs(value)
if(value != value || value === Infinity){
m = value != value ? 1 : 0;
e = eMax;
} else {
e = floor(log(value) / LN2);
if(value * (c = pow(2, -e)) < 1){
e--;
c *= 2;
}
if(e + eBias >= 1){
value += rt / c;
} else {
value += rt * pow(2, 1 - eBias);
}
if(value * c >= 2){
e++;
c /= 2;
}
if(e + eBias >= eMax){
m = 0;
e = eMax;
} else if(e + eBias >= 1){
m = (value * c - 1) * pow(2, mLen);
e = e + eBias;
} else {
m = value * pow(2, eBias - 1) * pow(2, mLen);
e = 0;
}
}
for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8);
e = e << mLen | m;
eLen += mLen;
for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8);
buffer[--i] |= s * 128;
return buffer;
};
var unpackIEEE754 = function(buffer, mLen, nBytes){
var eLen = nBytes * 8 - mLen - 1
, eMax = (1 << eLen) - 1
, eBias = eMax >> 1
, nBits = eLen - 7
, i = nBytes - 1
, s = buffer[i--]
, e = s & 127
, m;
s >>= 7;
for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8);
m = e & (1 << -nBits) - 1;
e >>= -nBits;
nBits += mLen;
for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8);
if(e === 0){
e = 1 - eBias;
} else if(e === eMax){
return m ? NaN : s ? -Infinity : Infinity;
} else {
m = m + pow(2, mLen);
e = e - eBias;
} return (s ? -1 : 1) * m * pow(2, e - mLen);
};
var unpackI32 = function(bytes){
return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
};
var packI8 = function(it){
return [it & 0xff];
};
var packI16 = function(it){
return [it & 0xff, it >> 8 & 0xff];
};
var packI32 = function(it){
return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff];
};
var packF64 = function(it){
return packIEEE754(it, 52, 8);
};
var packF32 = function(it){
return packIEEE754(it, 23, 4);
};
var addGetter = function(C, key, internal){
dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }});
};
var get = function(view, bytes, index, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = store.slice(start, start + bytes);
return isLittleEndian ? pack : pack.reverse();
};
var set = function(view, bytes, index, conversion, value, isLittleEndian){
var numIndex = +index
, intIndex = toInteger(numIndex);
if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX);
var store = view[$BUFFER]._b
, start = intIndex + view[$OFFSET]
, pack = conversion(+value);
for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1];
};
var validateArrayBufferArguments = function(that, length){
anInstance(that, $ArrayBuffer, ARRAY_BUFFER);
var numberLength = +length
, byteLength = toLength(numberLength);
if(numberLength != byteLength)throw RangeError(WRONG_LENGTH);
return byteLength;
};
if(!$typed.ABV){
$ArrayBuffer = function ArrayBuffer(length){
var byteLength = validateArrayBufferArguments(this, length);
this._b = arrayFill.call(Array(byteLength), 0);
this[$LENGTH] = byteLength;
};
$DataView = function DataView(buffer, byteOffset, byteLength){
anInstance(this, $DataView, DATA_VIEW);
anInstance(buffer, $ArrayBuffer, DATA_VIEW);
var bufferLength = buffer[$LENGTH]
, offset = toInteger(byteOffset);
if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!');
byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength);
if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH);
this[$BUFFER] = buffer;
this[$OFFSET] = offset;
this[$LENGTH] = byteLength;
};
if(DESCRIPTORS){
addGetter($ArrayBuffer, BYTE_LENGTH, '_l');
addGetter($DataView, BUFFER, '_b');
addGetter($DataView, BYTE_LENGTH, '_l');
addGetter($DataView, BYTE_OFFSET, '_o');
}
redefineAll($DataView[PROTOTYPE], {
getInt8: function getInt8(byteOffset){
return get(this, 1, byteOffset)[0] << 24 >> 24;
},
getUint8: function getUint8(byteOffset){
return get(this, 1, byteOffset)[0];
},
getInt16: function getInt16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return (bytes[1] << 8 | bytes[0]) << 16 >> 16;
},
getUint16: function getUint16(byteOffset /*, littleEndian */){
var bytes = get(this, 2, byteOffset, arguments[1]);
return bytes[1] << 8 | bytes[0];
},
getInt32: function getInt32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1]));
},
getUint32: function getUint32(byteOffset /*, littleEndian */){
return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0;
},
getFloat32: function getFloat32(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4);
},
getFloat64: function getFloat64(byteOffset /*, littleEndian */){
return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8);
},
setInt8: function setInt8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setUint8: function setUint8(byteOffset, value){
set(this, 1, byteOffset, packI8, value);
},
setInt16: function setInt16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setUint16: function setUint16(byteOffset, value /*, littleEndian */){
set(this, 2, byteOffset, packI16, value, arguments[2]);
},
setInt32: function setInt32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setUint32: function setUint32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packI32, value, arguments[2]);
},
setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){
set(this, 4, byteOffset, packF32, value, arguments[2]);
},
setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){
set(this, 8, byteOffset, packF64, value, arguments[2]);
}
});
} else {
if(!fails(function(){
new $ArrayBuffer; // eslint-disable-line no-new
}) || !fails(function(){
new $ArrayBuffer(.5); // eslint-disable-line no-new
})){
$ArrayBuffer = function ArrayBuffer(length){
return new BaseBuffer(validateArrayBufferArguments(this, length));
};
var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE];
for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){
if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]);
};
if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer;
}
// iOS Safari 7.x bug
var view = new $DataView(new $ArrayBuffer(2))
, $setInt8 = $DataView[PROTOTYPE].setInt8;
view.setInt8(0, 2147483648);
view.setInt8(1, 2147483649);
if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], {
setInt8: function setInt8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
},
setUint8: function setUint8(byteOffset, value){
$setInt8.call(this, byteOffset, value << 24 >> 24);
}
}, true);
}
setToStringTag($ArrayBuffer, ARRAY_BUFFER);
setToStringTag($DataView, DATA_VIEW);
hide($DataView[PROTOTYPE], $typed.VIEW, true);
exports[ARRAY_BUFFER] = $ArrayBuffer;
exports[DATA_VIEW] = $DataView;
/***/ },
/* 234 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6);
$export($export.G + $export.W + $export.F * !__webpack_require__(232).ABV, {
DataView: __webpack_require__(233).DataView
});
/***/ },
/* 235 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int8', 1, function(init){
return function Int8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 236 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
if(__webpack_require__(4)){
var LIBRARY = __webpack_require__(26)
, global = __webpack_require__(2)
, fails = __webpack_require__(5)
, $export = __webpack_require__(6)
, $typed = __webpack_require__(232)
, $buffer = __webpack_require__(233)
, ctx = __webpack_require__(18)
, anInstance = __webpack_require__(197)
, propertyDesc = __webpack_require__(15)
, hide = __webpack_require__(8)
, redefineAll = __webpack_require__(202)
, toInteger = __webpack_require__(36)
, toLength = __webpack_require__(35)
, toIndex = __webpack_require__(37)
, toPrimitive = __webpack_require__(14)
, has = __webpack_require__(3)
, same = __webpack_require__(69)
, classof = __webpack_require__(73)
, isObject = __webpack_require__(11)
, toObject = __webpack_require__(56)
, isArrayIter = __webpack_require__(154)
, create = __webpack_require__(44)
, getPrototypeOf = __webpack_require__(57)
, gOPN = __webpack_require__(48).f
, getIterFn = __webpack_require__(156)
, uid = __webpack_require__(17)
, wks = __webpack_require__(23)
, createArrayMethod = __webpack_require__(164)
, createArrayIncludes = __webpack_require__(34)
, speciesConstructor = __webpack_require__(199)
, ArrayIterators = __webpack_require__(183)
, Iterators = __webpack_require__(135)
, $iterDetect = __webpack_require__(157)
, setSpecies = __webpack_require__(186)
, arrayFill = __webpack_require__(180)
, arrayCopyWithin = __webpack_require__(177)
, $DP = __webpack_require__(9)
, $GOPD = __webpack_require__(49)
, dP = $DP.f
, gOPD = $GOPD.f
, RangeError = global.RangeError
, TypeError = global.TypeError
, Uint8Array = global.Uint8Array
, ARRAY_BUFFER = 'ArrayBuffer'
, SHARED_BUFFER = 'Shared' + ARRAY_BUFFER
, BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT'
, PROTOTYPE = 'prototype'
, ArrayProto = Array[PROTOTYPE]
, $ArrayBuffer = $buffer.ArrayBuffer
, $DataView = $buffer.DataView
, arrayForEach = createArrayMethod(0)
, arrayFilter = createArrayMethod(2)
, arraySome = createArrayMethod(3)
, arrayEvery = createArrayMethod(4)
, arrayFind = createArrayMethod(5)
, arrayFindIndex = createArrayMethod(6)
, arrayIncludes = createArrayIncludes(true)
, arrayIndexOf = createArrayIncludes(false)
, arrayValues = ArrayIterators.values
, arrayKeys = ArrayIterators.keys
, arrayEntries = ArrayIterators.entries
, arrayLastIndexOf = ArrayProto.lastIndexOf
, arrayReduce = ArrayProto.reduce
, arrayReduceRight = ArrayProto.reduceRight
, arrayJoin = ArrayProto.join
, arraySort = ArrayProto.sort
, arraySlice = ArrayProto.slice
, arrayToString = ArrayProto.toString
, arrayToLocaleString = ArrayProto.toLocaleString
, ITERATOR = wks('iterator')
, TAG = wks('toStringTag')
, TYPED_CONSTRUCTOR = uid('typed_constructor')
, DEF_CONSTRUCTOR = uid('def_constructor')
, ALL_CONSTRUCTORS = $typed.CONSTR
, TYPED_ARRAY = $typed.TYPED
, VIEW = $typed.VIEW
, WRONG_LENGTH = 'Wrong length!';
var $map = createArrayMethod(1, function(O, length){
return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length);
});
var LITTLE_ENDIAN = fails(function(){
return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
});
var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){
new Uint8Array(1).set({});
});
var strictToLength = function(it, SAME){
if(it === undefined)throw TypeError(WRONG_LENGTH);
var number = +it
, length = toLength(it);
if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH);
return length;
};
var toOffset = function(it, BYTES){
var offset = toInteger(it);
if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!');
return offset;
};
var validate = function(it){
if(isObject(it) && TYPED_ARRAY in it)return it;
throw TypeError(it + ' is not a typed array!');
};
var allocate = function(C, length){
if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){
throw TypeError('It is not a typed array constructor!');
} return new C(length);
};
var speciesFromList = function(O, list){
return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list);
};
var fromList = function(C, list){
var index = 0
, length = list.length
, result = allocate(C, length);
while(length > index)result[index] = list[index++];
return result;
};
var addGetter = function(it, key, internal){
dP(it, key, {get: function(){ return this._d[internal]; }});
};
var $from = function from(source /*, mapfn, thisArg */){
var O = toObject(source)
, aLen = arguments.length
, mapfn = aLen > 1 ? arguments[1] : undefined
, mapping = mapfn !== undefined
, iterFn = getIterFn(O)
, i, length, values, result, step, iterator;
if(iterFn != undefined && !isArrayIter(iterFn)){
for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){
values.push(step.value);
} O = values;
}
if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2);
for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){
result[i] = mapping ? mapfn(O[i], i) : O[i];
}
return result;
};
var $of = function of(/*...items*/){
var index = 0
, length = arguments.length
, result = allocate(this, length);
while(length > index)result[index] = arguments[index++];
return result;
};
// iOS Safari 6.x fails here
var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); });
var $toLocaleString = function toLocaleString(){
return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments);
};
var proto = {
copyWithin: function copyWithin(target, start /*, end */){
return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined);
},
every: function every(callbackfn /*, thisArg */){
return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars
return arrayFill.apply(validate(this), arguments);
},
filter: function filter(callbackfn /*, thisArg */){
return speciesFromList(this, arrayFilter(validate(this), callbackfn,
arguments.length > 1 ? arguments[1] : undefined));
},
find: function find(predicate /*, thisArg */){
return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
findIndex: function findIndex(predicate /*, thisArg */){
return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined);
},
forEach: function forEach(callbackfn /*, thisArg */){
arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
indexOf: function indexOf(searchElement /*, fromIndex */){
return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
includes: function includes(searchElement /*, fromIndex */){
return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined);
},
join: function join(separator){ // eslint-disable-line no-unused-vars
return arrayJoin.apply(validate(this), arguments);
},
lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars
return arrayLastIndexOf.apply(validate(this), arguments);
},
map: function map(mapfn /*, thisArg */){
return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined);
},
reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduce.apply(validate(this), arguments);
},
reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars
return arrayReduceRight.apply(validate(this), arguments);
},
reverse: function reverse(){
var that = this
, length = validate(that).length
, middle = Math.floor(length / 2)
, index = 0
, value;
while(index < middle){
value = that[index];
that[index++] = that[--length];
that[length] = value;
} return that;
},
some: function some(callbackfn /*, thisArg */){
return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined);
},
sort: function sort(comparefn){
return arraySort.call(validate(this), comparefn);
},
subarray: function subarray(begin, end){
var O = validate(this)
, length = O.length
, $begin = toIndex(begin, length);
return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))(
O.buffer,
O.byteOffset + $begin * O.BYTES_PER_ELEMENT,
toLength((end === undefined ? length : toIndex(end, length)) - $begin)
);
}
};
var $slice = function slice(start, end){
return speciesFromList(this, arraySlice.call(validate(this), start, end));
};
var $set = function set(arrayLike /*, offset */){
validate(this);
var offset = toOffset(arguments[1], 1)
, length = this.length
, src = toObject(arrayLike)
, len = toLength(src.length)
, index = 0;
if(len + offset > length)throw RangeError(WRONG_LENGTH);
while(index < len)this[offset + index] = src[index++];
};
var $iterators = {
entries: function entries(){
return arrayEntries.call(validate(this));
},
keys: function keys(){
return arrayKeys.call(validate(this));
},
values: function values(){
return arrayValues.call(validate(this));
}
};
var isTAIndex = function(target, key){
return isObject(target)
&& target[TYPED_ARRAY]
&& typeof key != 'symbol'
&& key in target
&& String(+key) == String(key);
};
var $getDesc = function getOwnPropertyDescriptor(target, key){
return isTAIndex(target, key = toPrimitive(key, true))
? propertyDesc(2, target[key])
: gOPD(target, key);
};
var $setDesc = function defineProperty(target, key, desc){
if(isTAIndex(target, key = toPrimitive(key, true))
&& isObject(desc)
&& has(desc, 'value')
&& !has(desc, 'get')
&& !has(desc, 'set')
// TODO: add validation descriptor w/o calling accessors
&& !desc.configurable
&& (!has(desc, 'writable') || desc.writable)
&& (!has(desc, 'enumerable') || desc.enumerable)
){
target[key] = desc.value;
return target;
} else return dP(target, key, desc);
};
if(!ALL_CONSTRUCTORS){
$GOPD.f = $getDesc;
$DP.f = $setDesc;
}
$export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', {
getOwnPropertyDescriptor: $getDesc,
defineProperty: $setDesc
});
if(fails(function(){ arrayToString.call({}); })){
arrayToString = arrayToLocaleString = function toString(){
return arrayJoin.call(this);
}
}
var $TypedArrayPrototype$ = redefineAll({}, proto);
redefineAll($TypedArrayPrototype$, $iterators);
hide($TypedArrayPrototype$, ITERATOR, $iterators.values);
redefineAll($TypedArrayPrototype$, {
slice: $slice,
set: $set,
constructor: function(){ /* noop */ },
toString: arrayToString,
toLocaleString: $toLocaleString
});
addGetter($TypedArrayPrototype$, 'buffer', 'b');
addGetter($TypedArrayPrototype$, 'byteOffset', 'o');
addGetter($TypedArrayPrototype$, 'byteLength', 'l');
addGetter($TypedArrayPrototype$, 'length', 'e');
dP($TypedArrayPrototype$, TAG, {
get: function(){ return this[TYPED_ARRAY]; }
});
module.exports = function(KEY, BYTES, wrapper, CLAMPED){
CLAMPED = !!CLAMPED;
var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array'
, ISNT_UINT8 = NAME != 'Uint8Array'
, GETTER = 'get' + KEY
, SETTER = 'set' + KEY
, TypedArray = global[NAME]
, Base = TypedArray || {}
, TAC = TypedArray && getPrototypeOf(TypedArray)
, FORCED = !TypedArray || !$typed.ABV
, O = {}
, TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE];
var getter = function(that, index){
var data = that._d;
return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN);
};
var setter = function(that, index, value){
var data = that._d;
if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff;
data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN);
};
var addElement = function(that, index){
dP(that, index, {
get: function(){
return getter(this, index);
},
set: function(value){
return setter(this, index, value);
},
enumerable: true
});
};
if(FORCED){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME, '_d');
var index = 0
, offset = 0
, buffer, byteLength, length, klass;
if(!isObject(data)){
length = strictToLength(data, true)
byteLength = length * BYTES;
buffer = new $ArrayBuffer(byteLength);
} else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
buffer = data;
offset = toOffset($offset, BYTES);
var $len = data.byteLength;
if($length === undefined){
if($len % BYTES)throw RangeError(WRONG_LENGTH);
byteLength = $len - offset;
if(byteLength < 0)throw RangeError(WRONG_LENGTH);
} else {
byteLength = toLength($length) * BYTES;
if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH);
}
length = byteLength / BYTES;
} else if(TYPED_ARRAY in data){
return fromList(TypedArray, data);
} else {
return $from.call(TypedArray, data);
}
hide(that, '_d', {
b: buffer,
o: offset,
l: byteLength,
e: length,
v: new $DataView(buffer)
});
while(index < length)addElement(that, index++);
});
TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$);
hide(TypedArrayPrototype, 'constructor', TypedArray);
} else if(!$iterDetect(function(iter){
// V8 works with iterators, but fails in many other cases
// https://code.google.com/p/v8/issues/detail?id=4552
new TypedArray(null); // eslint-disable-line no-new
new TypedArray(iter); // eslint-disable-line no-new
}, true)){
TypedArray = wrapper(function(that, data, $offset, $length){
anInstance(that, TypedArray, NAME);
var klass;
// `ws` module bug, temporarily remove validation length for Uint8Array
// https://github.com/websockets/ws/pull/645
if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8));
if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){
return $length !== undefined
? new Base(data, toOffset($offset, BYTES), $length)
: $offset !== undefined
? new Base(data, toOffset($offset, BYTES))
: new Base(data);
}
if(TYPED_ARRAY in data)return fromList(TypedArray, data);
return $from.call(TypedArray, data);
});
arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){
if(!(key in TypedArray))hide(TypedArray, key, Base[key]);
});
TypedArray[PROTOTYPE] = TypedArrayPrototype;
if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray;
}
var $nativeIterator = TypedArrayPrototype[ITERATOR]
, CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined)
, $iterator = $iterators.values;
hide(TypedArray, TYPED_CONSTRUCTOR, true);
hide(TypedArrayPrototype, TYPED_ARRAY, NAME);
hide(TypedArrayPrototype, VIEW, true);
hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray);
if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){
dP(TypedArrayPrototype, TAG, {
get: function(){ return NAME; }
});
}
O[NAME] = TypedArray;
$export($export.G + $export.W + $export.F * (TypedArray != Base), O);
$export($export.S, NAME, {
BYTES_PER_ELEMENT: BYTES,
from: $from,
of: $of
});
if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES);
$export($export.P, NAME, proto);
setSpecies(NAME);
$export($export.P + $export.F * FORCED_SET, NAME, {set: $set});
$export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators);
$export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString});
$export($export.P + $export.F * fails(function(){
new TypedArray(1).slice();
}), NAME, {slice: $slice});
$export($export.P + $export.F * (fails(function(){
return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString()
}) || !fails(function(){
TypedArrayPrototype.toLocaleString.call([1, 2]);
})), NAME, {toLocaleString: $toLocaleString});
Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator;
if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator);
};
} else module.exports = function(){ /* empty */ };
/***/ },
/* 237 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint8', 1, function(init){
return function Uint8Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 238 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint8', 1, function(init){
return function Uint8ClampedArray(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
}, true);
/***/ },
/* 239 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int16', 2, function(init){
return function Int16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 240 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint16', 2, function(init){
return function Uint16Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 241 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Int32', 4, function(init){
return function Int32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 242 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Uint32', 4, function(init){
return function Uint32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 243 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Float32', 4, function(init){
return function Float32Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 244 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(236)('Float64', 8, function(init){
return function Float64Array(data, byteOffset, length){
return init(this, data, byteOffset, length);
};
});
/***/ },
/* 245 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/Array.prototype.includes
var $export = __webpack_require__(6)
, $includes = __webpack_require__(34)(true);
$export($export.P, 'Array', {
includes: function includes(el /*, fromIndex = 0 */){
return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
}
});
__webpack_require__(178)('includes');
/***/ },
/* 246 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/mathiasbynens/String.prototype.at
var $export = __webpack_require__(6)
, $at = __webpack_require__(125)(true);
$export($export.P, 'String', {
at: function at(pos){
return $at(this, pos);
}
});
/***/ },
/* 247 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(6)
, $pad = __webpack_require__(248);
$export($export.P, 'String', {
padStart: function padStart(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true);
}
});
/***/ },
/* 248 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-string-pad-start-end
var toLength = __webpack_require__(35)
, repeat = __webpack_require__(85)
, defined = __webpack_require__(33);
module.exports = function(that, maxLength, fillString, left){
var S = String(defined(that))
, stringLength = S.length
, fillStr = fillString === undefined ? ' ' : String(fillString)
, intMaxLength = toLength(maxLength);
if(intMaxLength <= stringLength || fillStr == '')return S;
var fillLen = intMaxLength - stringLength
, stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length));
if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen);
return left ? stringFiller + S : S + stringFiller;
};
/***/ },
/* 249 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/tc39/proposal-string-pad-start-end
var $export = __webpack_require__(6)
, $pad = __webpack_require__(248);
$export($export.P, 'String', {
padEnd: function padEnd(maxLength /*, fillString = ' ' */){
return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false);
}
});
/***/ },
/* 250 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(81)('trimLeft', function($trim){
return function trimLeft(){
return $trim(this, 1);
};
}, 'trimStart');
/***/ },
/* 251 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/sebmarkbage/ecmascript-string-left-right-trim
__webpack_require__(81)('trimRight', function($trim){
return function trimRight(){
return $trim(this, 2);
};
}, 'trimEnd');
/***/ },
/* 252 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://tc39.github.io/String.prototype.matchAll/
var $export = __webpack_require__(6)
, defined = __webpack_require__(33)
, toLength = __webpack_require__(35)
, isRegExp = __webpack_require__(128)
, getFlags = __webpack_require__(188)
, RegExpProto = RegExp.prototype;
var $RegExpStringIterator = function(regexp, string){
this._r = regexp;
this._s = string;
};
__webpack_require__(136)($RegExpStringIterator, 'RegExp String', function next(){
var match = this._r.exec(this._s);
return {value: match, done: match === null};
});
$export($export.P, 'String', {
matchAll: function matchAll(regexp){
defined(this);
if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!');
var S = String(this)
, flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp)
, rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags);
rx.lastIndex = toLength(regexp.lastIndex);
return new $RegExpStringIterator(rx, S);
}
});
/***/ },
/* 253 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(25)('asyncIterator');
/***/ },
/* 254 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(25)('observable');
/***/ },
/* 255 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-getownpropertydescriptors
var $export = __webpack_require__(6)
, ownKeys = __webpack_require__(221)
, toIObject = __webpack_require__(30)
, gOPD = __webpack_require__(49)
, createProperty = __webpack_require__(155);
$export($export.S, 'Object', {
getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){
var O = toIObject(object)
, getDesc = gOPD.f
, keys = ownKeys(O)
, result = {}
, i = 0
, key;
while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key));
return result;
}
});
/***/ },
/* 256 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(6)
, $values = __webpack_require__(257)(false);
$export($export.S, 'Object', {
values: function values(it){
return $values(it);
}
});
/***/ },
/* 257 */
/***/ function(module, exports, __webpack_require__) {
var getKeys = __webpack_require__(28)
, toIObject = __webpack_require__(30)
, isEnum = __webpack_require__(42).f;
module.exports = function(isEntries){
return function(it){
var O = toIObject(it)
, keys = getKeys(O)
, length = keys.length
, i = 0
, result = []
, key;
while(length > i)if(isEnum.call(O, key = keys[i++])){
result.push(isEntries ? [key, O[key]] : O[key]);
} return result;
};
};
/***/ },
/* 258 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/tc39/proposal-object-values-entries
var $export = __webpack_require__(6)
, $entries = __webpack_require__(257)(true);
$export($export.S, 'Object', {
entries: function entries(it){
return $entries(it);
}
});
/***/ },
/* 259 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, aFunction = __webpack_require__(19)
, $defineProperty = __webpack_require__(9);
// B.2.2.2 Object.prototype.__defineGetter__(P, getter)
__webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', {
__defineGetter__: function __defineGetter__(P, getter){
$defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true});
}
});
/***/ },
/* 260 */
/***/ function(module, exports, __webpack_require__) {
// Forced replacement prototype accessors methods
module.exports = __webpack_require__(26)|| !__webpack_require__(5)(function(){
var K = Math.random();
// In FF throws only define methods
__defineSetter__.call(null, K, function(){ /* empty */});
delete __webpack_require__(2)[K];
});
/***/ },
/* 261 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, aFunction = __webpack_require__(19)
, $defineProperty = __webpack_require__(9);
// B.2.2.3 Object.prototype.__defineSetter__(P, setter)
__webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', {
__defineSetter__: function __defineSetter__(P, setter){
$defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true});
}
});
/***/ },
/* 262 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14)
, getPrototypeOf = __webpack_require__(57)
, getOwnPropertyDescriptor = __webpack_require__(49).f;
// B.2.2.4 Object.prototype.__lookupGetter__(P)
__webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', {
__lookupGetter__: function __lookupGetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.get;
} while(O = getPrototypeOf(O));
}
});
/***/ },
/* 263 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var $export = __webpack_require__(6)
, toObject = __webpack_require__(56)
, toPrimitive = __webpack_require__(14)
, getPrototypeOf = __webpack_require__(57)
, getOwnPropertyDescriptor = __webpack_require__(49).f;
// B.2.2.5 Object.prototype.__lookupSetter__(P)
__webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', {
__lookupSetter__: function __lookupSetter__(P){
var O = toObject(this)
, K = toPrimitive(P, true)
, D;
do {
if(D = getOwnPropertyDescriptor(O, K))return D.set;
} while(O = getPrototypeOf(O));
}
});
/***/ },
/* 264 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(6);
$export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(265)('Map')});
/***/ },
/* 265 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var classof = __webpack_require__(73)
, from = __webpack_require__(266);
module.exports = function(NAME){
return function toJSON(){
if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic");
return from(this);
};
};
/***/ },
/* 266 */
/***/ function(module, exports, __webpack_require__) {
var forOf = __webpack_require__(198);
module.exports = function(iter, ITERATOR){
var result = [];
forOf(iter, false, result.push, result, ITERATOR);
return result;
};
/***/ },
/* 267 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/DavidBruant/Map-Set.prototype.toJSON
var $export = __webpack_require__(6);
$export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(265)('Set')});
/***/ },
/* 268 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-global
var $export = __webpack_require__(6);
$export($export.S, 'System', {global: __webpack_require__(2)});
/***/ },
/* 269 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/ljharb/proposal-is-error
var $export = __webpack_require__(6)
, cof = __webpack_require__(32);
$export($export.S, 'Error', {
isError: function isError(it){
return cof(it) === 'Error';
}
});
/***/ },
/* 270 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
iaddh: function iaddh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0;
}
});
/***/ },
/* 271 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
isubh: function isubh(x0, x1, y0, y1){
var $x0 = x0 >>> 0
, $x1 = x1 >>> 0
, $y0 = y0 >>> 0;
return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0;
}
});
/***/ },
/* 272 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
imulh: function imulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >> 16
, v1 = $v >> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16);
}
});
/***/ },
/* 273 */
/***/ function(module, exports, __webpack_require__) {
// https://gist.github.com/BrendanEich/4294d5c212a6d2254703
var $export = __webpack_require__(6);
$export($export.S, 'Math', {
umulh: function umulh(u, v){
var UINT16 = 0xffff
, $u = +u
, $v = +v
, u0 = $u & UINT16
, v0 = $v & UINT16
, u1 = $u >>> 16
, v1 = $v >>> 16
, t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16);
return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16);
}
});
/***/ },
/* 274 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){
ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey));
}});
/***/ },
/* 275 */
/***/ function(module, exports, __webpack_require__) {
var Map = __webpack_require__(203)
, $export = __webpack_require__(6)
, shared = __webpack_require__(21)('metadata')
, store = shared.store || (shared.store = new (__webpack_require__(207)));
var getOrCreateMetadataMap = function(target, targetKey, create){
var targetMetadata = store.get(target);
if(!targetMetadata){
if(!create)return undefined;
store.set(target, targetMetadata = new Map);
}
var keyMetadata = targetMetadata.get(targetKey);
if(!keyMetadata){
if(!create)return undefined;
targetMetadata.set(targetKey, keyMetadata = new Map);
} return keyMetadata;
};
var ordinaryHasOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? false : metadataMap.has(MetadataKey);
};
var ordinaryGetOwnMetadata = function(MetadataKey, O, P){
var metadataMap = getOrCreateMetadataMap(O, P, false);
return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey);
};
var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){
getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue);
};
var ordinaryOwnMetadataKeys = function(target, targetKey){
var metadataMap = getOrCreateMetadataMap(target, targetKey, false)
, keys = [];
if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); });
return keys;
};
var toMetaKey = function(it){
return it === undefined || typeof it == 'symbol' ? it : String(it);
};
var exp = function(O){
$export($export.S, 'Reflect', O);
};
module.exports = {
store: store,
map: getOrCreateMetadataMap,
has: ordinaryHasOwnMetadata,
get: ordinaryGetOwnMetadata,
set: ordinaryDefineOwnMetadata,
keys: ordinaryOwnMetadataKeys,
key: toMetaKey,
exp: exp
};
/***/ },
/* 276 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, toMetaKey = metadata.key
, getOrCreateMetadataMap = metadata.map
, store = metadata.store;
metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){
var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2])
, metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false);
if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false;
if(metadataMap.size)return true;
var targetMetadata = store.get(target);
targetMetadata['delete'](targetKey);
return !!targetMetadata.size || store['delete'](target);
}});
/***/ },
/* 277 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryHasOwnMetadata = metadata.has
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
var ordinaryGetMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P);
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined;
};
metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 278 */
/***/ function(module, exports, __webpack_require__) {
var Set = __webpack_require__(206)
, from = __webpack_require__(266)
, metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
var ordinaryMetadataKeys = function(O, P){
var oKeys = ordinaryOwnMetadataKeys(O, P)
, parent = getPrototypeOf(O);
if(parent === null)return oKeys;
var pKeys = ordinaryMetadataKeys(parent, P);
return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys;
};
metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){
return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 279 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, ordinaryGetOwnMetadata = metadata.get
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryGetOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 280 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, ordinaryOwnMetadataKeys = metadata.keys
, toMetaKey = metadata.key;
metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){
return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1]));
}});
/***/ },
/* 281 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, getPrototypeOf = __webpack_require__(57)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
var ordinaryHasMetadata = function(MetadataKey, O, P){
var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P);
if(hasOwn)return true;
var parent = getPrototypeOf(O);
return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false;
};
metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 282 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, ordinaryHasOwnMetadata = metadata.has
, toMetaKey = metadata.key;
metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){
return ordinaryHasOwnMetadata(metadataKey, anObject(target)
, arguments.length < 3 ? undefined : toMetaKey(arguments[2]));
}});
/***/ },
/* 283 */
/***/ function(module, exports, __webpack_require__) {
var metadata = __webpack_require__(275)
, anObject = __webpack_require__(10)
, aFunction = __webpack_require__(19)
, toMetaKey = metadata.key
, ordinaryDefineOwnMetadata = metadata.set;
metadata.exp({metadata: function metadata(metadataKey, metadataValue){
return function decorator(target, targetKey){
ordinaryDefineOwnMetadata(
metadataKey, metadataValue,
(targetKey !== undefined ? anObject : aFunction)(target),
toMetaKey(targetKey)
);
};
}});
/***/ },
/* 284 */
/***/ function(module, exports, __webpack_require__) {
// https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask
var $export = __webpack_require__(6)
, microtask = __webpack_require__(201)()
, process = __webpack_require__(2).process
, isNode = __webpack_require__(32)(process) == 'process';
$export($export.G, {
asap: function asap(fn){
var domain = isNode && process.domain;
microtask(domain ? domain.bind(fn) : fn);
}
});
/***/ },
/* 285 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
// https://github.com/zenparsing/es-observable
var $export = __webpack_require__(6)
, global = __webpack_require__(2)
, core = __webpack_require__(7)
, microtask = __webpack_require__(201)()
, OBSERVABLE = __webpack_require__(23)('observable')
, aFunction = __webpack_require__(19)
, anObject = __webpack_require__(10)
, anInstance = __webpack_require__(197)
, redefineAll = __webpack_require__(202)
, hide = __webpack_require__(8)
, forOf = __webpack_require__(198)
, RETURN = forOf.RETURN;
var getMethod = function(fn){
return fn == null ? undefined : aFunction(fn);
};
var cleanupSubscription = function(subscription){
var cleanup = subscription._c;
if(cleanup){
subscription._c = undefined;
cleanup();
}
};
var subscriptionClosed = function(subscription){
return subscription._o === undefined;
};
var closeSubscription = function(subscription){
if(!subscriptionClosed(subscription)){
subscription._o = undefined;
cleanupSubscription(subscription);
}
};
var Subscription = function(observer, subscriber){
anObject(observer);
this._c = undefined;
this._o = observer;
observer = new SubscriptionObserver(this);
try {
var cleanup = subscriber(observer)
, subscription = cleanup;
if(cleanup != null){
if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); };
else aFunction(cleanup);
this._c = cleanup;
}
} catch(e){
observer.error(e);
return;
} if(subscriptionClosed(this))cleanupSubscription(this);
};
Subscription.prototype = redefineAll({}, {
unsubscribe: function unsubscribe(){ closeSubscription(this); }
});
var SubscriptionObserver = function(subscription){
this._s = subscription;
};
SubscriptionObserver.prototype = redefineAll({}, {
next: function next(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
try {
var m = getMethod(observer.next);
if(m)return m.call(observer, value);
} catch(e){
try {
closeSubscription(subscription);
} finally {
throw e;
}
}
}
},
error: function error(value){
var subscription = this._s;
if(subscriptionClosed(subscription))throw value;
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.error);
if(!m)throw value;
value = m.call(observer, value);
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
},
complete: function complete(value){
var subscription = this._s;
if(!subscriptionClosed(subscription)){
var observer = subscription._o;
subscription._o = undefined;
try {
var m = getMethod(observer.complete);
value = m ? m.call(observer, value) : undefined;
} catch(e){
try {
cleanupSubscription(subscription);
} finally {
throw e;
}
} cleanupSubscription(subscription);
return value;
}
}
});
var $Observable = function Observable(subscriber){
anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber);
};
redefineAll($Observable.prototype, {
subscribe: function subscribe(observer){
return new Subscription(observer, this._f);
},
forEach: function forEach(fn){
var that = this;
return new (core.Promise || global.Promise)(function(resolve, reject){
aFunction(fn);
var subscription = that.subscribe({
next : function(value){
try {
return fn(value);
} catch(e){
reject(e);
subscription.unsubscribe();
}
},
error: reject,
complete: resolve
});
});
}
});
redefineAll($Observable, {
from: function from(x){
var C = typeof this === 'function' ? this : $Observable;
var method = getMethod(anObject(x)[OBSERVABLE]);
if(method){
var observable = anObject(method.call(x));
return observable.constructor === C ? observable : new C(function(observer){
return observable.subscribe(observer);
});
}
return new C(function(observer){
var done = false;
microtask(function(){
if(!done){
try {
if(forOf(x, false, function(it){
observer.next(it);
if(done)return RETURN;
}) === RETURN)return;
} catch(e){
if(done)throw e;
observer.error(e);
return;
} observer.complete();
}
});
return function(){ done = true; };
});
},
of: function of(){
for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++];
return new (typeof this === 'function' ? this : $Observable)(function(observer){
var done = false;
microtask(function(){
if(!done){
for(var i = 0; i < items.length; ++i){
observer.next(items[i]);
if(done)return;
} observer.complete();
}
});
return function(){ done = true; };
});
}
});
hide($Observable.prototype, OBSERVABLE, function(){ return this; });
$export($export.G, {Observable: $Observable});
__webpack_require__(186)('Observable');
/***/ },
/* 286 */
/***/ function(module, exports, __webpack_require__) {
var $export = __webpack_require__(6)
, $task = __webpack_require__(200);
$export($export.G + $export.B, {
setImmediate: $task.set,
clearImmediate: $task.clear
});
/***/ },
/* 287 */
/***/ function(module, exports, __webpack_require__) {
var $iterators = __webpack_require__(183)
, redefine = __webpack_require__(16)
, global = __webpack_require__(2)
, hide = __webpack_require__(8)
, Iterators = __webpack_require__(135)
, wks = __webpack_require__(23)
, ITERATOR = wks('iterator')
, TO_STRING_TAG = wks('toStringTag')
, ArrayValues = Iterators.Array;
for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){
var NAME = collections[i]
, Collection = global[NAME]
, proto = Collection && Collection.prototype
, key;
if(proto){
if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues);
if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME);
Iterators[NAME] = ArrayValues;
for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true);
}
}
/***/ },
/* 288 */
/***/ function(module, exports, __webpack_require__) {
// ie9- setTimeout & setInterval additional parameters fix
var global = __webpack_require__(2)
, $export = __webpack_require__(6)
, invoke = __webpack_require__(76)
, partial = __webpack_require__(289)
, navigator = global.navigator
, MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check
var wrap = function(set){
return MSIE ? function(fn, time /*, ...args */){
return set(invoke(
partial,
[].slice.call(arguments, 2),
typeof fn == 'function' ? fn : Function(fn)
), time);
} : set;
};
$export($export.G + $export.B + $export.F * MSIE, {
setTimeout: wrap(global.setTimeout),
setInterval: wrap(global.setInterval)
});
/***/ },
/* 289 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
var path = __webpack_require__(290)
, invoke = __webpack_require__(76)
, aFunction = __webpack_require__(19);
module.exports = function(/* ...pargs */){
var fn = aFunction(this)
, length = arguments.length
, pargs = Array(length)
, i = 0
, _ = path._
, holder = false;
while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true;
return function(/* ...args */){
var that = this
, aLen = arguments.length
, j = 0, k = 0, args;
if(!holder && !aLen)return invoke(fn, pargs, that);
args = pargs.slice();
if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++];
while(aLen > k)args.push(arguments[k++]);
return invoke(fn, args, that);
};
};
/***/ },
/* 290 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(2);
/***/ }
/******/ ]);
// CommonJS export
if(typeof module != 'undefined' && module.exports)module.exports = __e;
// RequireJS export
else if(typeof define == 'function' && define.amd)define(function(){return __e});
// Export to global object
else __g.core = __e;
}(1, 1);
|
src/components/ObjectiveListItem.js
|
samkarp/murmuration
|
import React from 'react';
import axios from 'axios';
const ObjectivesListItem = React.createClass({
render: function() {
var classname = "objectiveCollapse"+this.props.objective._id.trim()
var objectiveregionclassname = "objectiveRegionCollapse"+this.props.objective._id.trim()
var objectivetargetclassname = "objectiveTargetCollapse"+this.props.objective._id.trim()
var objectiveresourceclassname = "objectiveResourceCollapse"+this.props.objective._id.trim()
var objectives = this.props.objectives
return (
<div className="objectiveListItem">
<div className="panel-group">
<div className="panel panel-default">
<div className="panel-heading">
<h4 className="panel-title">
<a data-toggle="collapse" href={"#"+classname}>{this.props.objective._source.name}</a>
</h4>
</div>
<div id={classname} className="panel-collapse collapse">
<ul className="list-group">
<li className="list-group-item">
<div className="panel-group">
<div className="panel panel-default">
<div className="panel-heading">
<h4 className="panel-title">
<a data-toggle="collapse" href={"#"+objectiveregionclassname}>Regions</a>
</h4>
</div>
<div id={objectiveregionclassname} className="panel-collapse collapse">
<ul className="list-group">
{this.props.regions.map(function(region){
return ( <li key={region._id} className="list-group-item"><a href="#">{region._source.description}</a></li> )
})}
</ul>
</div>
</div>
</div>
</li>
<li className="list-group-item">
<div className="panel-group">
<div className="panel panel-default">
<div className="panel-heading">
<h4 className="panel-title">
<a data-toggle="collapse" href={"#"+objectivetargetclassname}>Targets</a>
</h4>
</div>
<div id={objectivetargetclassname} className="panel-collapse collapse">
<ul className="list-group">
{this.props.targets.map(function(target){
return ( <li key={target._id} className="list-group-item"><a href="#">{target._source.description}</a></li> )
})}
</ul>
</div>
</div>
</div>
</li>
<li className="list-group-item">
<div className="panel-group">
<div className="panel panel-default">
<div className="panel-heading">
<h4 className="panel-title">
<a data-toggle="collapse" href={"#"+objectiveresourceclassname}>Resources</a>
</h4>
</div>
<div id={objectiveresourceclassname} className="panel-collapse collapse">
<ul className="list-group">
{this.props.resources.map(function(resource){
return ( <li key={resource._id} className="list-group-item"><a href="#">{resource._source.name}</a></li> )
})}
</ul>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
</div>
)}
});
export default ObjectivesListItem
|
src/components/pages/home.js
|
chuntielin/Blog_Yeoman_Fullstack
|
import React from 'react';
import { connect } from 'react-redux';
import { logIn } from 'actions/login-actions';
const HomePage = function HomePage(props) {
return {
props,
login() {
this.props.dispatch(logIn());
},
renderStuff() {
const user = this.props.login.toJS().user;
if (!user) {
return null;
}
return <p>Hello {user.name}</p>
},
render() {
return (
<div>
<h1>Login</h1>
<button onClick={this.login.bind(this)}>Click Meeee</button>
{this.renderStuff()}
</div>
)
}
}
}
function mapStateToProps(state) {
return {
home: state.home,
login: state.login
}
}
export default connect(mapStateToProps)(HomePage);
|
app/javascript/mastodon/components/collapsable.js
|
foozmeat/mastodon
|
import React from 'react';
import Motion from '../features/ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import PropTypes from 'prop-types';
const Collapsable = ({ fullHeight, isVisible, children }) => (
<Motion defaultStyle={{ opacity: !isVisible ? 0 : 100, height: isVisible ? fullHeight : 0 }} style={{ opacity: spring(!isVisible ? 0 : 100), height: spring(!isVisible ? 0 : fullHeight) }}>
{({ opacity, height }) =>
<div style={{ height: `${height}px`, overflow: 'hidden', opacity: opacity / 100, display: Math.floor(opacity) === 0 ? 'none' : 'block' }}>
{children}
</div>
}
</Motion>
);
Collapsable.propTypes = {
fullHeight: PropTypes.number.isRequired,
isVisible: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
};
export default Collapsable;
|
src/components/Heading.js
|
dlindahl/stemcell
|
import { func, node, oneOf, oneOfType, string } from 'prop-types'
import React from 'react'
import Text from './Text'
const LEVELS = [
'canon', // H1
'trafalgar', // H2
'doublePica', // H3
'greatPrimer', // H4
'pica', // H5
'longPrimer' // H6
]
const Heading = ({ as, children, level, ...props }, { theme }) => {
let headingLevel = level
if (typeof level === 'number') {
as = as || `h${level}`
headingLevel = LEVELS[level - 1]
} else if (typeof level === 'string' && LEVELS.includes(level)) {
as = as || `h${LEVELS.indexOf(level) + 1}`
}
return <Text as={as} size={headingLevel} {...props}>{children}</Text>
}
Heading.levels = LEVELS
Heading.defaultProps = {
level: 1
}
Heading.propTypes = {
as: oneOfType([string, func]),
children: node,
level: oneOfType([
oneOf(LEVELS),
oneOf([...Array(6).keys()].map((x) => x + 1))
]).isRequired
}
export default Heading
|
src/components/tab.js
|
heroTM737/Dota2CounterPlayClient
|
import React, { Component } from 'react';
import _ from 'lodash';
export class Tabs extends Component {
constructor(props) {
super(props);
this.state = {
activeTab: null,
children: {}
}
props.children.map(child => {
this.state.children[child.props.title] = child.props.component;
});
this.state.activeTab = props.children[0].props.title;
this.changeTab = this.changeTab.bind(this);
this.getOnClickFunction = this.getOnClickFunction.bind(this);
}
getOnClickFunction(title) {
return () => this.changeTab(title);
}
changeTab(title) {
if (this.onTabChange) {
this.onTabChange(this.state.title, title);
}
this.setState({
activeTab: title
});
}
render() {
var titles = [];
for (var key in this.state.children) {
var className = key == this.state.activeTab ? "active" : "";
titles.push(<li key={key} className={className} onClick={this.getOnClickFunction(key)}>{key}</li>);
}
var child = this.state.children[this.state.activeTab];
return (
<div className="Tabs">
<div className="TabsHeader"><ul>{titles}</ul></div>
<div className="TabsBody" key={this.state.activeTab}>{child}</div>
</div>
);
}
}
export class Tab {
}
|
.eslintrc.js
|
skystebnicki/chamel
|
module.exports = {
env: {
browser: true,
es6: true,
},
extends: ['eslint:recommended', 'plugin:react/recommended', 'prettier'],
parser: 'babel-eslint',
plugins: ['prettier', 'react'],
rules: {
'prettier/prettier': 'error',
},
};
|
node_modules/react-bootstrap/es/CarouselItem.js
|
rblin081/drafting-client
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import TransitionEvents from './utils/TransitionEvents';
// TODO: This should use a timeout instead of TransitionEvents, or else just
// not wait until transition end to trigger continuing animations.
var propTypes = {
direction: PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: PropTypes.func,
active: PropTypes.bool,
animateIn: PropTypes.bool,
animateOut: PropTypes.bool,
index: PropTypes.number
};
var defaultProps = {
active: false,
animateIn: false,
animateOut: false
};
var CarouselItem = function (_React$Component) {
_inherits(CarouselItem, _React$Component);
function CarouselItem(props, context) {
_classCallCheck(this, CarouselItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this);
_this.state = {
direction: null
};
_this.isUnmounted = false;
return _this;
}
CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({ direction: null });
}
};
CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var active = this.props.active;
var prevActive = prevProps.active;
if (!active && prevActive) {
TransitionEvents.addEndEventListener(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd);
}
if (active !== prevActive) {
setTimeout(function () {
return _this2.startAnimation();
}, 20);
}
};
CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() {
this.isUnmounted = true;
};
CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() {
if (this.isUnmounted) {
return;
}
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd(this.props.index);
}
};
CarouselItem.prototype.startAnimation = function startAnimation() {
if (this.isUnmounted) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
};
CarouselItem.prototype.render = function render() {
var _props = this.props,
direction = _props.direction,
active = _props.active,
animateIn = _props.animateIn,
animateOut = _props.animateOut,
className = _props.className,
props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']);
delete props.onAnimateOutEnd;
delete props.index;
var classes = {
item: true,
active: active && !animateIn || animateOut
};
if (direction && active && animateIn) {
classes[direction] = true;
}
if (this.state.direction && (animateIn || animateOut)) {
classes[this.state.direction] = true;
}
return React.createElement('div', _extends({}, props, {
className: classNames(className, classes)
}));
};
return CarouselItem;
}(React.Component);
CarouselItem.propTypes = propTypes;
CarouselItem.defaultProps = defaultProps;
export default CarouselItem;
|
src/svg-icons/hardware/tablet-mac.js
|
ngbrown/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareTabletMac = (props) => (
<SvgIcon {...props}>
<path d="M18.5 0h-14C3.12 0 2 1.12 2 2.5v19C2 22.88 3.12 24 4.5 24h14c1.38 0 2.5-1.12 2.5-2.5v-19C21 1.12 19.88 0 18.5 0zm-7 23c-.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.5zm7.5-4H4V3h15v16z"/>
</SvgIcon>
);
HardwareTabletMac = pure(HardwareTabletMac);
HardwareTabletMac.displayName = 'HardwareTabletMac';
HardwareTabletMac.muiName = 'SvgIcon';
export default HardwareTabletMac;
|
packages/material-ui-icons/src/MicOffSharp.js
|
allanalexandre/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M15 10.6V5c0-1.66-1.34-3-3-3-1.54 0-2.79 1.16-2.96 2.65L15 10.6zM19 11h-1.7c0 .58-.1 1.13-.27 1.64l1.27 1.27c.44-.88.7-1.87.7-2.91zM4.41 2.86L3 4.27l6 6V11c0 1.66 1.34 3 3 3 .23 0 .44-.03.65-.08l1.66 1.66c-.71.33-1.5.52-2.31.52-2.76 0-5.3-2.1-5.3-5.1H5c0 3.41 2.72 6.23 6 6.72V21h2v-3.28c.91-.13 1.77-.45 2.55-.9l4.2 4.2 1.41-1.41L4.41 2.86z" /></React.Fragment>
, 'MicOffSharp');
|
source/Table/defaultRowRenderer.js
|
edulan/react-virtualized
|
/** @flow */
import React from 'react'
import type { RowRendererParams } from './types'
/**
* Default row renderer for Table.
*/
export default function defaultRowRenderer ({
className,
columns,
index,
isScrolling,
key,
onRowClick,
onRowDoubleClick,
onRowMouseOver,
onRowMouseOut,
rowData,
style
}: RowRendererParams) {
const a11yProps = {}
if (
onRowClick ||
onRowDoubleClick ||
onRowMouseOver ||
onRowMouseOut
) {
a11yProps['aria-label'] = 'row'
a11yProps.role = 'row'
a11yProps.tabIndex = 0
if (onRowClick) {
a11yProps.onClick = () => onRowClick({ index, rowData })
}
if (onRowDoubleClick) {
a11yProps.onDoubleClick = () => onRowDoubleClick({ index, rowData })
}
if (onRowMouseOut) {
a11yProps.onMouseOut = () => onRowMouseOut({ index, rowData })
}
if (onRowMouseOver) {
a11yProps.onMouseOver = () => onRowMouseOver({ index, rowData })
}
}
return (
<div
{...a11yProps}
className={className}
key={key}
style={style}
>
{columns}
</div>
)
}
|
src/svg-icons/hardware/cast.js
|
IsenrichO/mui-with-arrows
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareCast = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11z"/>
</SvgIcon>
);
HardwareCast = pure(HardwareCast);
HardwareCast.displayName = 'HardwareCast';
HardwareCast.muiName = 'SvgIcon';
export default HardwareCast;
|
node_modules/react-dom/index.js
|
esteladiaz/esteladiaz.github.io
|
'use strict';
function checkDCE() {
/* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
) {
return;
}
if (process.env.NODE_ENV !== 'production') {
// This branch is unreachable because this function is only called
// in production, but the condition is true only in development.
// Therefore if the branch is still here, dead code elimination wasn't
// properly applied.
// Don't change the message. React DevTools relies on it. Also make sure
// this message doesn't occur elsewhere in this function, or it will cause
// a false positive.
throw new Error('^_^');
}
try {
// Verify that the code above has been dead code eliminated (DCE'd).
__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
} catch (err) {
// DevTools shouldn't crash React, no matter what.
// We should still report in case we break this code.
console.error(err);
}
}
if (process.env.NODE_ENV === 'production') {
// DCE check should happen before ReactDOM bundle executes so that
// DevTools can report bad minification during injection.
checkDCE();
module.exports = require('./cjs/react-dom.production.min.js');
} else {
module.exports = require('./cjs/react-dom.development.js');
}
|
ajax/libs/rxjs/2.3.18/rx.lite.extras.js
|
dc-js/cdnjs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (factory) {
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;
}
// Because of build optimizers
if (typeof define === 'function' && define.amd) {
define(['rx'], function (Rx, exports) {
return factory(root, exports, Rx);
});
} else if (typeof module === 'object' && module && module.exports === freeExports) {
module.exports = factory(root, module.exports, require('./rx'));
} else {
root.Rx = factory(root, {}, root.Rx);
}
}.call(this, function (root, exp, Rx, undefined) {
// References
var Observable = Rx.Observable,
observableProto = Observable.prototype,
observableNever = Observable.never,
observableThrow = Observable.throwException,
AnonymousObservable = Rx.AnonymousObservable,
Observer = Rx.Observer,
Subject = Rx.Subject,
internals = Rx.internals,
helpers = Rx.helpers,
ScheduledObserver = internals.ScheduledObserver,
SingleAssignmentDisposable = Rx.SingleAssignmentDisposable,
CompositeDisposable = Rx.CompositeDisposable,
RefCountDisposable = Rx.RefCountDisposable,
disposableEmpty = Rx.Disposable.empty,
immediateScheduler = Rx.Scheduler.immediate,
defaultKeySerializer = helpers.defaultKeySerializer,
addRef = Rx.internals.addRef,
identity = helpers.identity,
isPromise = helpers.isPromise,
inherits = internals.inherits,
noop = helpers.noop,
isScheduler = helpers.isScheduler,
observableFromPromise = Observable.fromPromise,
slice = Array.prototype.slice;
function argsOrArray(args, idx) {
return args.length === 1 && Array.isArray(args[idx]) ?
args[idx] :
slice.call(args);
}
var argumentOutOfRange = 'Argument out of range';
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
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));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver() {
__super__.apply(this, arguments);
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
/**
* 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;
});
};
/**
* 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) {
isScheduler(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();
}
});
});
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @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();
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 or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @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();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
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 or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @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;
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @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]);
* @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++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @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 (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @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;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new Error(argumentOutOfRange); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new Error(argumentOutOfRange); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
});
};
/**
* 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);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
observer.onNext(q);
observer.onCompleted();
});
});
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = 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();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* 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
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && observer.onNext(x);
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
return Rx;
}));
|
app/javascript/mastodon/components/dropdown_menu.js
|
salvadorpla/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from './icon_button';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../features/ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import detectPassiveEvents from 'detect-passive-events';
const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false;
let id = 0;
class DropdownMenu extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
items: PropTypes.array.isRequired,
onClose: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
openedViaKeyboard: PropTypes.bool,
};
static defaultProps = {
style: {},
placement: 'bottom',
};
state = {
mounted: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('keydown', this.handleKeyDown, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
if (this.focusedItem && this.props.openedViaKeyboard) this.focusedItem.focus();
this.setState({ mounted: true });
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('keydown', this.handleKeyDown, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
setFocusRef = c => {
this.focusedItem = c;
}
handleKeyDown = e => {
const items = Array.from(this.node.getElementsByTagName('a'));
const index = items.indexOf(document.activeElement);
let element;
switch(e.key) {
case 'ArrowDown':
element = items[index+1];
if (element) {
element.focus();
}
break;
case 'ArrowUp':
element = items[index-1];
if (element) {
element.focus();
}
break;
case 'Home':
element = items[0];
if (element) {
element.focus();
}
break;
case 'End':
element = items[items.length-1];
if (element) {
element.focus();
}
break;
}
}
handleItemKeyDown = e => {
if (e.key === 'Enter') {
this.handleClick(e);
}
}
handleClick = e => {
const i = Number(e.currentTarget.getAttribute('data-index'));
const { action, to } = this.props.items[i];
this.props.onClose();
if (typeof action === 'function') {
e.preventDefault();
action(e);
} else if (to) {
e.preventDefault();
this.context.router.history.push(to);
}
}
renderItem (option, i) {
if (option === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { text, href = '#' } = option;
return (
<li className='dropdown-menu__item' key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyDown={this.handleItemKeyDown} data-index={i}>
{text}
</a>
</li>
);
}
render () {
const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props;
const { mounted } = this.state;
return (
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
// It should not be transformed when mounting because the resulting
// size will be used to determine the coordinate of the menu by
// react-overlays
<div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}>
<div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} />
<ul>
{items.map((option, i) => this.renderItem(option, i))}
</ul>
</div>
)}
</Motion>
);
}
}
export default class Dropdown extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
icon: PropTypes.string.isRequired,
items: PropTypes.array.isRequired,
size: PropTypes.number.isRequired,
title: PropTypes.string,
disabled: PropTypes.bool,
status: ImmutablePropTypes.map,
isUserTouching: PropTypes.func,
isModalOpen: PropTypes.bool.isRequired,
onOpen: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
dropdownPlacement: PropTypes.string,
openDropdownId: PropTypes.number,
openedViaKeyboard: PropTypes.bool,
};
static defaultProps = {
title: 'Menu',
};
state = {
id: id++,
};
handleClick = ({ target, type }) => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
} else {
const { top } = target.getBoundingClientRect();
const placement = top * 2 < innerHeight ? 'bottom' : 'top';
this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click');
}
}
handleClose = () => {
this.props.onClose(this.state.id);
}
handleKeyDown = e => {
switch(e.key) {
case ' ':
case 'Enter':
this.handleClick(e);
e.preventDefault();
break;
case 'Escape':
this.handleClose();
break;
}
}
handleItemClick = e => {
const i = Number(e.currentTarget.getAttribute('data-index'));
const { action, to } = this.props.items[i];
this.handleClose();
if (typeof action === 'function') {
e.preventDefault();
action();
} else if (to) {
e.preventDefault();
this.context.router.history.push(to);
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
componentWillUnmount = () => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
}
}
render () {
const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId, openedViaKeyboard } = this.props;
const open = this.state.id === openDropdownId;
return (
<div onKeyDown={this.handleKeyDown}>
<IconButton
icon={icon}
title={title}
active={open}
disabled={disabled}
size={size}
ref={this.setTargetRef}
onClick={this.handleClick}
/>
<Overlay show={open} placement={dropdownPlacement} target={this.findTarget}>
<DropdownMenu items={items} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} />
</Overlay>
</div>
);
}
}
|
dispatch/static/manager/src/js/components/Tooltip.js
|
ubyssey/dispatch
|
import React from 'react'
class Tooltip extends React.Component{
constructor(props) {
super(props)
this.state = {
isTooltipDisplayed: false
}
this.hideTooltip = this.hideTooltip.bind(this)
this.showTooltip = this.showTooltip.bind(this)
}
hideTooltip () {
this.setState({isTooltipDisplayed: false})
}
showTooltip () {
this.setState({isTooltipDisplayed: true})
}
render(){
return (
<div
className='tooltip'
onMouseLeave={this.hideTooltip}>
{this.state.isTooltipDisplayed &&
<div className={`tooltip-bubble tooltip-${this.props.position}`}>
<div className='tooltip-text'>{this.props.text}</div>
</div>
}
{this.props.activateOnClick ?
<span className='tooltip-trigger' onClick={this.showTooltip}> {this.props.children}</span> :
<span className='tooltip-trigger' onMouseOver={this.showTooltip}> {this.props.children}</span>
}
</div>
)
}
}
export default Tooltip
|
ajax/libs/video.js/5.0.0-rc.92/video.novtt.js
|
honestree/cdnjs
|
(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 : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19
},{"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 : {})
//# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19
},{}],3:[function(_dereq_,module,exports){
},{}],4:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeNow = getNative(Date, 'now');
/**
* Gets the number of milliseconds that have elapsed since the Unix epoch
* (1 January 1970 00:00:00 UTC).
*
* @static
* @memberOf _
* @category Date
* @example
*
* _.defer(function(stamp) {
* console.log(_.now() - stamp);
* }, _.now());
* // => logs the number of milliseconds it took for the deferred function to be invoked
*/
var now = nativeNow || function() {
return new Date().getTime();
};
module.exports = now;
},{"../internal/getNative":20}],5:[function(_dereq_,module,exports){
var isObject = _dereq_('../lang/isObject'),
now = _dereq_('../date/now');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a debounced function that delays invoking `func` until after `wait`
* milliseconds have elapsed since the last time the debounced function was
* invoked. The debounced function comes with a `cancel` method to cancel
* delayed invocations. Provide an options object to indicate that `func`
* should be invoked on the leading and/or trailing edge of the `wait` timeout.
* Subsequent calls to the debounced function return the result of the last
* `func` invocation.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the debounced function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.debounce` and `_.throttle`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to debounce.
* @param {number} [wait=0] The number of milliseconds to delay.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=false] Specify invoking on the leading
* edge of the timeout.
* @param {number} [options.maxWait] The maximum time `func` is allowed to be
* delayed before it's invoked.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new debounced function.
* @example
*
* // avoid costly calculations while the window size is in flux
* jQuery(window).on('resize', _.debounce(calculateLayout, 150));
*
* // invoke `sendMail` when the click event is fired, debouncing subsequent calls
* jQuery('#postbox').on('click', _.debounce(sendMail, 300, {
* 'leading': true,
* 'trailing': false
* }));
*
* // ensure `batchLog` is invoked once after 1 second of debounced calls
* var source = new EventSource('/stream');
* jQuery(source).on('message', _.debounce(batchLog, 250, {
* 'maxWait': 1000
* }));
*
* // cancel a debounced call
* var todoChanges = _.debounce(batchLog, 1000);
* Object.observe(models.todo, todoChanges);
*
* Object.observe(models, function(changes) {
* if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {
* todoChanges.cancel();
* }
* }, ['delete']);
*
* // ...at some point `models.todo` is changed
* models.todo.completed = true;
*
* // ...before 1 second has passed `models.todo` is deleted
* // which cancels the debounced `todoChanges` call
* delete models.todo;
*/
function debounce(func, wait, options) {
var args,
maxTimeoutId,
result,
stamp,
thisArg,
timeoutId,
trailingCall,
lastCalled = 0,
maxWait = false,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
wait = wait < 0 ? 0 : (+wait || 0);
if (options === true) {
var leading = true;
trailing = false;
} else if (isObject(options)) {
leading = !!options.leading;
maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
function cancel() {
if (timeoutId) {
clearTimeout(timeoutId);
}
if (maxTimeoutId) {
clearTimeout(maxTimeoutId);
}
lastCalled = 0;
maxTimeoutId = timeoutId = trailingCall = undefined;
}
function complete(isCalled, id) {
if (id) {
clearTimeout(id);
}
maxTimeoutId = timeoutId = trailingCall = undefined;
if (isCalled) {
lastCalled = now();
result = func.apply(thisArg, args);
if (!timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
}
}
function delayed() {
var remaining = wait - (now() - stamp);
if (remaining <= 0 || remaining > wait) {
complete(trailingCall, maxTimeoutId);
} else {
timeoutId = setTimeout(delayed, remaining);
}
}
function maxDelayed() {
complete(trailing, timeoutId);
}
function debounced() {
args = arguments;
stamp = now();
thisArg = this;
trailingCall = trailing && (timeoutId || !leading);
if (maxWait === false) {
var leadingCall = leading && !timeoutId;
} else {
if (!maxTimeoutId && !leading) {
lastCalled = stamp;
}
var remaining = maxWait - (stamp - lastCalled),
isCalled = remaining <= 0 || remaining > maxWait;
if (isCalled) {
if (maxTimeoutId) {
maxTimeoutId = clearTimeout(maxTimeoutId);
}
lastCalled = stamp;
result = func.apply(thisArg, args);
}
else if (!maxTimeoutId) {
maxTimeoutId = setTimeout(maxDelayed, remaining);
}
}
if (isCalled && timeoutId) {
timeoutId = clearTimeout(timeoutId);
}
else if (!timeoutId && wait !== maxWait) {
timeoutId = setTimeout(delayed, wait);
}
if (leadingCall) {
isCalled = true;
result = func.apply(thisArg, args);
}
if (isCalled && !timeoutId && !maxTimeoutId) {
args = thisArg = undefined;
}
return result;
}
debounced.cancel = cancel;
return debounced;
}
module.exports = debounce;
},{"../date/now":4,"../lang/isObject":33}],6:[function(_dereq_,module,exports){
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
},{}],7:[function(_dereq_,module,exports){
var debounce = _dereq_('./debounce'),
isObject = _dereq_('../lang/isObject');
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/**
* Creates a throttled function that only invokes `func` at most once per
* every `wait` milliseconds. The throttled function comes with a `cancel`
* method to cancel delayed invocations. Provide an options object to indicate
* that `func` should be invoked on the leading and/or trailing edge of the
* `wait` timeout. Subsequent calls to the throttled function return the
* result of the last `func` call.
*
* **Note:** If `leading` and `trailing` options are `true`, `func` is invoked
* on the trailing edge of the timeout only if the the throttled function is
* invoked more than once during the `wait` timeout.
*
* See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)
* for details over the differences between `_.throttle` and `_.debounce`.
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to throttle.
* @param {number} [wait=0] The number of milliseconds to throttle invocations to.
* @param {Object} [options] The options object.
* @param {boolean} [options.leading=true] Specify invoking on the leading
* edge of the timeout.
* @param {boolean} [options.trailing=true] Specify invoking on the trailing
* edge of the timeout.
* @returns {Function} Returns the new throttled function.
* @example
*
* // avoid excessively updating the position while scrolling
* jQuery(window).on('scroll', _.throttle(updatePosition, 100));
*
* // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes
* jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {
* 'trailing': false
* }));
*
* // cancel a trailing throttled call
* jQuery(window).on('popstate', throttled.cancel);
*/
function throttle(func, wait, options) {
var leading = true,
trailing = true;
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
if (options === false) {
leading = false;
} else if (isObject(options)) {
leading = 'leading' in options ? !!options.leading : leading;
trailing = 'trailing' in options ? !!options.trailing : trailing;
}
return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing });
}
module.exports = throttle;
},{"../lang/isObject":33,"./debounce":5}],8:[function(_dereq_,module,exports){
/**
* Copies the values of `source` to `array`.
*
* @private
* @param {Array} source The array to copy values from.
* @param {Array} [array=[]] The array to copy values to.
* @returns {Array} Returns `array`.
*/
function arrayCopy(source, array) {
var index = -1,
length = source.length;
array || (array = Array(length));
while (++index < length) {
array[index] = source[index];
}
return array;
}
module.exports = arrayCopy;
},{}],9:[function(_dereq_,module,exports){
/**
* A specialized version of `_.forEach` for arrays without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Array} array The array to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Array} Returns `array`.
*/
function arrayEach(array, iteratee) {
var index = -1,
length = array.length;
while (++index < length) {
if (iteratee(array[index], index, array) === false) {
break;
}
}
return array;
}
module.exports = arrayEach;
},{}],10:[function(_dereq_,module,exports){
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],11:[function(_dereq_,module,exports){
var createBaseFor = _dereq_('./createBaseFor');
/**
* The base implementation of `baseForIn` and `baseForOwn` which iterates
* over `object` properties returned by `keysFunc` invoking `iteratee` for
* each property. Iteratee functions may exit iteration early by explicitly
* returning `false`.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @param {Function} keysFunc The function to get the keys of `object`.
* @returns {Object} Returns `object`.
*/
var baseFor = createBaseFor();
module.exports = baseFor;
},{"./createBaseFor":18}],12:[function(_dereq_,module,exports){
var baseFor = _dereq_('./baseFor'),
keysIn = _dereq_('../object/keysIn');
/**
* The base implementation of `_.forIn` without support for callback
* shorthands and `this` binding.
*
* @private
* @param {Object} object The object to iterate over.
* @param {Function} iteratee The function invoked per iteration.
* @returns {Object} Returns `object`.
*/
function baseForIn(object, iteratee) {
return baseFor(object, iteratee, keysIn);
}
module.exports = baseForIn;
},{"../object/keysIn":39,"./baseFor":11}],13:[function(_dereq_,module,exports){
var arrayEach = _dereq_('./arrayEach'),
baseMergeDeep = _dereq_('./baseMergeDeep'),
isArray = _dereq_('../lang/isArray'),
isArrayLike = _dereq_('./isArrayLike'),
isObject = _dereq_('../lang/isObject'),
isObjectLike = _dereq_('./isObjectLike'),
isTypedArray = _dereq_('../lang/isTypedArray'),
keys = _dereq_('../object/keys');
/**
* The base implementation of `_.merge` without support for argument juggling,
* multiple sources, and `this` binding `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {Object} Returns `object`.
*/
function baseMerge(object, source, customizer, stackA, stackB) {
if (!isObject(object)) {
return object;
}
var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)),
props = isSrcArr ? undefined : keys(source);
arrayEach(props || source, function(srcValue, key) {
if (props) {
key = srcValue;
srcValue = source[key];
}
if (isObjectLike(srcValue)) {
stackA || (stackA = []);
stackB || (stackB = []);
baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);
}
else {
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
}
if ((result !== undefined || (isSrcArr && !(key in object))) &&
(isCommon || (result === result ? (result !== value) : (value === value)))) {
object[key] = result;
}
}
});
return object;
}
module.exports = baseMerge;
},{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":9,"./baseMergeDeep":14,"./isArrayLike":21,"./isObjectLike":26}],14:[function(_dereq_,module,exports){
var arrayCopy = _dereq_('./arrayCopy'),
isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isArrayLike = _dereq_('./isArrayLike'),
isPlainObject = _dereq_('../lang/isPlainObject'),
isTypedArray = _dereq_('../lang/isTypedArray'),
toPlainObject = _dereq_('../lang/toPlainObject');
/**
* A specialized version of `baseMerge` for arrays and objects which performs
* deep merges and tracks traversed objects enabling objects with circular
* references to be merged.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @param {string} key The key of the value to merge.
* @param {Function} mergeFunc The function to merge values.
* @param {Function} [customizer] The function to customize merged values.
* @param {Array} [stackA=[]] Tracks traversed source objects.
* @param {Array} [stackB=[]] Associates values with source counterparts.
* @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
*/
function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {
var length = stackA.length,
srcValue = source[key];
while (length--) {
if (stackA[length] == srcValue) {
object[key] = stackB[length];
return;
}
}
var value = object[key],
result = customizer ? customizer(value, srcValue, key, object, source) : undefined,
isCommon = result === undefined;
if (isCommon) {
result = srcValue;
if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) {
result = isArray(value)
? value
: (isArrayLike(value) ? arrayCopy(value) : []);
}
else if (isPlainObject(srcValue) || isArguments(srcValue)) {
result = isArguments(value)
? toPlainObject(value)
: (isPlainObject(value) ? value : {});
}
else {
isCommon = false;
}
}
// Add the source value to the stack of traversed objects and associate
// it with its merged value.
stackA.push(srcValue);
stackB.push(result);
if (isCommon) {
// Recursively merge objects and arrays (susceptible to call stack limits).
object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);
} else if (result === result ? (result !== value) : (value === value)) {
object[key] = result;
}
}
module.exports = baseMergeDeep;
},{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":8,"./isArrayLike":21}],15:[function(_dereq_,module,exports){
var toObject = _dereq_('./toObject');
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : toObject(object)[key];
};
}
module.exports = baseProperty;
},{"./toObject":28}],16:[function(_dereq_,module,exports){
var identity = _dereq_('../utility/identity');
/**
* A specialized version of `baseCallback` which only supports `this` binding
* and specifying the number of arguments to provide to `func`.
*
* @private
* @param {Function} func The function to bind.
* @param {*} thisArg The `this` binding of `func`.
* @param {number} [argCount] The number of arguments to provide to `func`.
* @returns {Function} Returns the callback.
*/
function bindCallback(func, thisArg, argCount) {
if (typeof func != 'function') {
return identity;
}
if (thisArg === undefined) {
return func;
}
switch (argCount) {
case 1: return function(value) {
return func.call(thisArg, value);
};
case 3: return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
case 4: return function(accumulator, value, index, collection) {
return func.call(thisArg, accumulator, value, index, collection);
};
case 5: return function(value, other, key, object, source) {
return func.call(thisArg, value, other, key, object, source);
};
}
return function() {
return func.apply(thisArg, arguments);
};
}
module.exports = bindCallback;
},{"../utility/identity":42}],17:[function(_dereq_,module,exports){
var bindCallback = _dereq_('./bindCallback'),
isIterateeCall = _dereq_('./isIterateeCall'),
restParam = _dereq_('../function/restParam');
/**
* Creates a `_.assign`, `_.defaults`, or `_.merge` function.
*
* @private
* @param {Function} assigner The function to assign values.
* @returns {Function} Returns the new assigner function.
*/
function createAssigner(assigner) {
return restParam(function(object, sources) {
var index = -1,
length = object == null ? 0 : sources.length,
customizer = length > 2 ? sources[length - 2] : undefined,
guard = length > 2 ? sources[2] : undefined,
thisArg = length > 1 ? sources[length - 1] : undefined;
if (typeof customizer == 'function') {
customizer = bindCallback(customizer, thisArg, 5);
length -= 2;
} else {
customizer = typeof thisArg == 'function' ? thisArg : undefined;
length -= (customizer ? 1 : 0);
}
if (guard && isIterateeCall(sources[0], sources[1], guard)) {
customizer = length < 3 ? undefined : customizer;
length = 1;
}
while (++index < length) {
var source = sources[index];
if (source) {
assigner(object, source, customizer);
}
}
return object;
});
}
module.exports = createAssigner;
},{"../function/restParam":6,"./bindCallback":16,"./isIterateeCall":24}],18:[function(_dereq_,module,exports){
var toObject = _dereq_('./toObject');
/**
* Creates a base function for `_.forIn` or `_.forInRight`.
*
* @private
* @param {boolean} [fromRight] Specify iterating from right to left.
* @returns {Function} Returns the new base function.
*/
function createBaseFor(fromRight) {
return function(object, iteratee, keysFunc) {
var iterable = toObject(object),
props = keysFunc(object),
length = props.length,
index = fromRight ? length : -1;
while ((fromRight ? index-- : ++index < length)) {
var key = props[index];
if (iteratee(iterable[key], key, iterable) === false) {
break;
}
}
return object;
};
}
module.exports = createBaseFor;
},{"./toObject":28}],19:[function(_dereq_,module,exports){
var baseProperty = _dereq_('./baseProperty');
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
module.exports = getLength;
},{"./baseProperty":15}],20:[function(_dereq_,module,exports){
var isNative = _dereq_('../lang/isNative');
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
module.exports = getNative;
},{"../lang/isNative":32}],21:[function(_dereq_,module,exports){
var getLength = _dereq_('./getLength'),
isLength = _dereq_('./isLength');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
module.exports = isArrayLike;
},{"./getLength":19,"./isLength":25}],22:[function(_dereq_,module,exports){
/**
* Checks if `value` is a host object in IE < 9.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a host object, else `false`.
*/
var isHostObject = (function() {
try {
Object({ 'toString': 0 } + '');
} catch(e) {
return function() { return false; };
}
return function(value) {
// IE < 9 presents many host objects as `Object` objects that can coerce
// to strings despite having improperly defined `toString` methods.
return typeof value.toString != 'function' && typeof (value + '') == 'string';
};
}());
module.exports = isHostObject;
},{}],23:[function(_dereq_,module,exports){
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
module.exports = isIndex;
},{}],24:[function(_dereq_,module,exports){
var isArrayLike = _dereq_('./isArrayLike'),
isIndex = _dereq_('./isIndex'),
isObject = _dereq_('../lang/isObject');
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
module.exports = isIterateeCall;
},{"../lang/isObject":33,"./isArrayLike":21,"./isIndex":23}],25:[function(_dereq_,module,exports){
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
module.exports = isLength;
},{}],26:[function(_dereq_,module,exports){
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isObjectLike;
},{}],27:[function(_dereq_,module,exports){
var isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isIndex = _dereq_('./isIndex'),
isLength = _dereq_('./isLength'),
isString = _dereq_('../lang/isString'),
keysIn = _dereq_('../object/keysIn');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
module.exports = shimKeys;
},{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":23,"./isLength":25}],28:[function(_dereq_,module,exports){
var isObject = _dereq_('../lang/isObject'),
isString = _dereq_('../lang/isString'),
support = _dereq_('../support');
/**
* Converts `value` to an object if it's not one.
*
* @private
* @param {*} value The value to process.
* @returns {Object} Returns the object.
*/
function toObject(value) {
if (support.unindexedChars && isString(value)) {
var index = -1,
length = value.length,
result = Object(value);
while (++index < length) {
result[index] = value.charAt(index);
}
return result;
}
return isObject(value) ? value : Object(value);
}
module.exports = toObject;
},{"../lang/isObject":33,"../lang/isString":35,"../support":41}],29:[function(_dereq_,module,exports){
var isArrayLike = _dereq_('../internal/isArrayLike'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
return isObjectLike(value) && isArrayLike(value) &&
hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee');
}
module.exports = isArguments;
},{"../internal/isArrayLike":21,"../internal/isObjectLike":26}],30:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative'),
isLength = _dereq_('../internal/isLength'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var arrayTag = '[object Array]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
module.exports = isArray;
},{"../internal/getNative":20,"../internal/isLength":25,"../internal/isObjectLike":26}],31:[function(_dereq_,module,exports){
var isObject = _dereq_('./isObject');
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 which returns 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
module.exports = isFunction;
},{"./isObject":33}],32:[function(_dereq_,module,exports){
var isFunction = _dereq_('./isFunction'),
isHostObject = _dereq_('../internal/isHostObject'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value);
}
module.exports = isNative;
},{"../internal/isHostObject":22,"../internal/isObjectLike":26,"./isFunction":31}],33:[function(_dereq_,module,exports){
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isObject;
},{}],34:[function(_dereq_,module,exports){
var baseForIn = _dereq_('../internal/baseForIn'),
isArguments = _dereq_('./isArguments'),
isHostObject = _dereq_('../internal/isHostObject'),
isObjectLike = _dereq_('../internal/isObjectLike'),
support = _dereq_('../support');
/** `Object#toString` result references. */
var objectTag = '[object Object]';
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is a plain object, that is, an object created by the
* `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* **Note:** This method assumes objects created by the `Object` constructor
* have no inherited enumerable properties.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
* @example
*
* function Foo() {
* this.a = 1;
* }
*
* _.isPlainObject(new Foo);
* // => false
*
* _.isPlainObject([1, 2, 3]);
* // => false
*
* _.isPlainObject({ 'x': 0, 'y': 0 });
* // => true
*
* _.isPlainObject(Object.create(null));
* // => true
*/
function isPlainObject(value) {
var Ctor;
// Exit early for non `Object` objects.
if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) ||
(!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {
return false;
}
// IE < 9 iterates inherited properties before own properties. If the first
// iterated property is an object's own property then there are no inherited
// enumerable properties.
var result;
if (support.ownLast) {
baseForIn(value, function(subValue, key, object) {
result = hasOwnProperty.call(object, key);
return false;
});
return result !== false;
}
// In most environments an object's own properties are iterated before
// its inherited properties. If the last iterated property is an object's
// own property then there are no inherited enumerable properties.
baseForIn(value, function(subValue, key) {
result = key;
});
return result === undefined || hasOwnProperty.call(value, result);
}
module.exports = isPlainObject;
},{"../internal/baseForIn":12,"../internal/isHostObject":22,"../internal/isObjectLike":26,"../support":41,"./isArguments":29}],35:[function(_dereq_,module,exports){
var isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var stringTag = '[object String]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a `String` primitive or object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isString('abc');
* // => true
*
* _.isString(1);
* // => false
*/
function isString(value) {
return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag);
}
module.exports = isString;
},{"../internal/isObjectLike":26}],36:[function(_dereq_,module,exports){
var isLength = _dereq_('../internal/isLength'),
isObjectLike = _dereq_('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
mapTag = '[object Map]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
setTag = '[object Set]',
stringTag = '[object String]',
weakMapTag = '[object WeakMap]';
var arrayBufferTag = '[object ArrayBuffer]',
float32Tag = '[object Float32Array]',
float64Tag = '[object Float64Array]',
int8Tag = '[object Int8Array]',
int16Tag = '[object Int16Array]',
int32Tag = '[object Int32Array]',
uint8Tag = '[object Uint8Array]',
uint8ClampedTag = '[object Uint8ClampedArray]',
uint16Tag = '[object Uint16Array]',
uint32Tag = '[object Uint32Array]';
/** Used to identify `toStringTag` values of typed arrays. */
var typedArrayTags = {};
typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
typedArrayTags[uint32Tag] = true;
typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
typedArrayTags[dateTag] = typedArrayTags[errorTag] =
typedArrayTags[funcTag] = typedArrayTags[mapTag] =
typedArrayTags[numberTag] = typedArrayTags[objectTag] =
typedArrayTags[regexpTag] = typedArrayTags[setTag] =
typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as a typed array.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isTypedArray(new Uint8Array);
* // => true
*
* _.isTypedArray([]);
* // => false
*/
function isTypedArray(value) {
return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)];
}
module.exports = isTypedArray;
},{"../internal/isLength":25,"../internal/isObjectLike":26}],37:[function(_dereq_,module,exports){
var baseCopy = _dereq_('../internal/baseCopy'),
keysIn = _dereq_('../object/keysIn');
/**
* Converts `value` to a plain object flattening inherited enumerable
* properties of `value` to own properties of the plain object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to convert.
* @returns {Object} Returns the converted plain object.
* @example
*
* function Foo() {
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.assign({ 'a': 1 }, new Foo);
* // => { 'a': 1, 'b': 2 }
*
* _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
* // => { 'a': 1, 'b': 2, 'c': 3 }
*/
function toPlainObject(value) {
return baseCopy(value, keysIn(value));
}
module.exports = toPlainObject;
},{"../internal/baseCopy":10,"../object/keysIn":39}],38:[function(_dereq_,module,exports){
var getNative = _dereq_('../internal/getNative'),
isArrayLike = _dereq_('../internal/isArrayLike'),
isObject = _dereq_('../lang/isObject'),
shimKeys = _dereq_('../internal/shimKeys'),
support = _dereq_('../support');
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
module.exports = keys;
},{"../internal/getNative":20,"../internal/isArrayLike":21,"../internal/shimKeys":27,"../lang/isObject":33,"../support":41}],39:[function(_dereq_,module,exports){
var arrayEach = _dereq_('../internal/arrayEach'),
isArguments = _dereq_('../lang/isArguments'),
isArray = _dereq_('../lang/isArray'),
isFunction = _dereq_('../lang/isFunction'),
isIndex = _dereq_('../internal/isIndex'),
isLength = _dereq_('../internal/isLength'),
isObject = _dereq_('../lang/isObject'),
isString = _dereq_('../lang/isString'),
support = _dereq_('../support');
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
boolTag = '[object Boolean]',
dateTag = '[object Date]',
errorTag = '[object Error]',
funcTag = '[object Function]',
numberTag = '[object Number]',
objectTag = '[object Object]',
regexpTag = '[object RegExp]',
stringTag = '[object String]';
/** Used to fix the JScript `[[DontEnum]]` bug. */
var shadowProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable',
'toLocaleString', 'toString', 'valueOf'
];
/** Used for native method references. */
var errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to avoid iterating over non-enumerable properties in IE < 9. */
var nonEnumProps = {};
nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true };
nonEnumProps[objectTag] = { 'constructor': true };
arrayEach(shadowProps, function(key) {
for (var tag in nonEnumProps) {
if (hasOwnProperty.call(nonEnumProps, tag)) {
var props = nonEnumProps[tag];
props[key] = hasOwnProperty.call(props, key);
}
}
});
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object) || isString(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
proto = (isFunction(Ctor) && Ctor.prototype) || objectProto,
isProto = proto === object,
result = Array(length),
skipIndexes = length > 0,
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error),
skipProto = support.enumPrototypes && isFunction(object);
while (++index < length) {
result[index] = (index + '');
}
// lodash skips the `constructor` property when it infers it's iterating
// over a `prototype` object because IE < 9 can't set the `[[Enumerable]]`
// attribute of an existing property and the `constructor` property of a
// prototype defaults to non-enumerable.
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name')) &&
!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)),
nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag];
if (tag == objectTag) {
proto = objectProto;
}
length = shadowProps.length;
while (length--) {
key = shadowProps[length];
var nonEnum = nonEnums[key];
if (!(isProto && nonEnum) &&
(nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) {
result.push(key);
}
}
}
return result;
}
module.exports = keysIn;
},{"../internal/arrayEach":9,"../internal/isIndex":23,"../internal/isLength":25,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":41}],40:[function(_dereq_,module,exports){
var baseMerge = _dereq_('../internal/baseMerge'),
createAssigner = _dereq_('../internal/createAssigner');
/**
* Recursively merges own enumerable properties of the source object(s), that
* don't resolve to `undefined` into the destination object. Subsequent sources
* overwrite property assignments of previous sources. If `customizer` is
* provided it's invoked to produce the merged values of the destination and
* source properties. If `customizer` returns `undefined` merging is handled
* by the method instead. The `customizer` is bound to `thisArg` and invoked
* with five arguments: (objectValue, sourceValue, key, object, source).
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The destination object.
* @param {...Object} [sources] The source objects.
* @param {Function} [customizer] The function to customize assigned values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {Object} Returns `object`.
* @example
*
* var users = {
* 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]
* };
*
* var ages = {
* 'data': [{ 'age': 36 }, { 'age': 40 }]
* };
*
* _.merge(users, ages);
* // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }
*
* // using a customizer callback
* var object = {
* 'fruits': ['apple'],
* 'vegetables': ['beet']
* };
*
* var other = {
* 'fruits': ['banana'],
* 'vegetables': ['carrot']
* };
*
* _.merge(object, other, function(a, b) {
* if (_.isArray(a)) {
* return a.concat(b);
* }
* });
* // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }
*/
var merge = createAssigner(baseMerge);
module.exports = merge;
},{"../internal/baseMerge":13,"../internal/createAssigner":17}],41:[function(_dereq_,module,exports){
/** Used for native method references. */
var arrayProto = Array.prototype,
errorProto = Error.prototype,
objectProto = Object.prototype;
/** Native method references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable,
splice = arrayProto.splice;
/**
* An object environment feature flags.
*
* @static
* @memberOf _
* @type Object
*/
var support = {};
(function(x) {
var Ctor = function() { this.x = x; },
object = { '0': x, 'length': x },
props = [];
Ctor.prototype = { 'valueOf': x, 'y': x };
for (var key in new Ctor) { props.push(key); }
/**
* Detect if `name` or `message` properties of `Error.prototype` are
* enumerable by default (IE < 9, Safari < 5.1).
*
* @memberOf _.support
* @type boolean
*/
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') ||
propertyIsEnumerable.call(errorProto, 'name');
/**
* Detect if `prototype` properties are enumerable by default.
*
* Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1
* (if the prototype or a property on the prototype has been set)
* incorrectly set the `[[Enumerable]]` value of a function's `prototype`
* property to `true`.
*
* @memberOf _.support
* @type boolean
*/
support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype');
/**
* Detect if properties shadowing those on `Object.prototype` are non-enumerable.
*
* In IE < 9 an object's own properties, shadowing non-enumerable ones,
* are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug).
*
* @memberOf _.support
* @type boolean
*/
support.nonEnumShadows = !/valueOf/.test(props);
/**
* Detect if own properties are iterated after inherited properties (IE < 9).
*
* @memberOf _.support
* @type boolean
*/
support.ownLast = props[0] != 'x';
/**
* Detect if `Array#shift` and `Array#splice` augment array-like objects
* correctly.
*
* Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array
* `shift()` and `splice()` functions that fail to remove the last element,
* `value[0]`, of array-like objects even though the "length" property is
* set to `0`. The `shift()` method is buggy in compatibility modes of IE 8,
* while `splice()` is buggy regardless of mode in IE < 9.
*
* @memberOf _.support
* @type boolean
*/
support.spliceObjects = (splice.call(object, 0, 1), !object[0]);
/**
* Detect lack of support for accessing string characters by index.
*
* IE < 8 can't access characters by index. IE 8 can only access characters
* by index on string literals, not string objects.
*
* @memberOf _.support
* @type boolean
*/
support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx';
}(1, 0));
module.exports = support;
},{}],42:[function(_dereq_,module,exports){
/**
* This method returns the first argument provided to it.
*
* @static
* @memberOf _
* @category Utility
* @param {*} value Any value.
* @returns {*} Returns `value`.
* @example
*
* var object = { 'user': 'fred' };
*
* _.identity(object) === object;
* // => true
*/
function identity(value) {
return value;
}
module.exports = identity;
},{}],43:[function(_dereq_,module,exports){
'use strict';
// modified from https://github.com/es-shims/es6-shim
var keys = _dereq_('object-keys');
var canBeObject = function (obj) {
return typeof obj !== 'undefined' && obj !== null;
};
var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
var defineProperties = _dereq_('define-properties');
var toObject = Object;
var push = Array.prototype.push;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;
var assignShim = function assign(target, source1) {
if (!canBeObject(target)) { throw new TypeError('target must be an object'); }
var objTarget = toObject(target);
var s, source, i, props, syms;
for (s = 1; s < arguments.length; ++s) {
source = toObject(arguments[s]);
props = keys(source);
if (hasSymbols && Object.getOwnPropertySymbols) {
syms = Object.getOwnPropertySymbols(source);
for (i = 0; i < syms.length; ++i) {
if (propIsEnumerable.call(source, syms[i])) {
push.call(props, syms[i]);
}
}
}
for (i = 0; i < props.length; ++i) {
objTarget[props[i]] = source[props[i]];
}
}
return objTarget;
};
defineProperties(assignShim, {
shim: function shimObjectAssign() {
var assignHasPendingExceptions = function () {
if (!Object.assign || !Object.preventExtensions) {
return false;
}
// Firefox 37 still has "pending exception" logic in its Object.assign implementation,
// which is 72% slower than our shim, and Firefox 40's native implementation.
var thrower = Object.preventExtensions({ 1: 2 });
try {
Object.assign(thrower, 'xy');
} catch (e) {
return thrower[1] === 'y';
}
};
defineProperties(
Object,
{ assign: assignShim },
{ assign: assignHasPendingExceptions }
);
return Object.assign || assignShim;
}
});
module.exports = assignShim;
},{"define-properties":44,"object-keys":46}],44:[function(_dereq_,module,exports){
'use strict';
var keys = _dereq_('object-keys');
var foreach = _dereq_('foreach');
var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol';
var toStr = Object.prototype.toString;
var isFunction = function (fn) {
return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
};
var arePropertyDescriptorsSupported = function () {
var obj = {};
try {
Object.defineProperty(obj, 'x', { value: obj, enumerable: false });
/* eslint-disable no-unused-vars */
for (var _ in obj) { return false; }
/* eslint-enable no-unused-vars */
return obj.x === obj;
} catch (e) { /* this is IE 8. */
return false;
}
};
var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported();
var defineProperty = function (object, name, value, predicate) {
if (name in object && (!isFunction(predicate) || !predicate())) {
return;
}
if (supportsDescriptors) {
Object.defineProperty(object, name, {
configurable: true,
enumerable: false,
writable: true,
value: value
});
} else {
object[name] = value;
}
};
var defineProperties = function (object, map) {
var predicates = arguments.length > 2 ? arguments[2] : {};
var props = keys(map);
if (hasSymbols) {
props = props.concat(Object.getOwnPropertySymbols(map));
}
foreach(props, function (name) {
defineProperty(object, name, map[name], predicates[name]);
});
};
defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
},{"foreach":45,"object-keys":46}],45:[function(_dereq_,module,exports){
var hasOwn = Object.prototype.hasOwnProperty;
var toString = Object.prototype.toString;
module.exports = function forEach (obj, fn, ctx) {
if (toString.call(fn) !== '[object Function]') {
throw new TypeError('iterator must be a function');
}
var l = obj.length;
if (l === +l) {
for (var i = 0; i < l; i++) {
fn.call(ctx, obj[i], i, obj);
}
} else {
for (var k in obj) {
if (hasOwn.call(obj, k)) {
fn.call(ctx, obj[k], k, obj);
}
}
}
};
},{}],46:[function(_dereq_,module,exports){
'use strict';
// modified from https://github.com/es-shims/es5-shim
var has = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var slice = Array.prototype.slice;
var isArgs = _dereq_('./isArguments');
var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString');
var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype');
var dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
];
var equalsConstructorPrototype = function (o) {
var ctor = o.constructor;
return ctor && ctor.prototype === o;
};
var blacklistedKeys = {
$window: true,
$console: true,
$parent: true,
$self: true,
$frames: true,
$webkitIndexedDB: true,
$webkitStorageInfo: true
};
var hasAutomationEqualityBug = (function () {
/* global window */
if (typeof window === 'undefined') { return false; }
for (var k in window) {
if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
try {
equalsConstructorPrototype(window[k]);
} catch (e) {
return true;
}
}
}
return false;
}());
var equalsConstructorPrototypeIfNotBuggy = function (o) {
/* global window */
if (typeof window === 'undefined' && !hasAutomationEqualityBug) {
return equalsConstructorPrototype(o);
}
try {
return equalsConstructorPrototype(o);
} catch (e) {
return false;
}
};
var keysShim = function keys(object) {
var isObject = object !== null && typeof object === 'object';
var isFunction = toStr.call(object) === '[object Function]';
var isArguments = isArgs(object);
var isString = isObject && toStr.call(object) === '[object String]';
var theKeys = [];
if (!isObject && !isFunction && !isArguments) {
throw new TypeError('Object.keys called on a non-object');
}
var skipProto = hasProtoEnumBug && isFunction;
if (isString && object.length > 0 && !has.call(object, 0)) {
for (var i = 0; i < object.length; ++i) {
theKeys.push(String(i));
}
}
if (isArguments && object.length > 0) {
for (var j = 0; j < object.length; ++j) {
theKeys.push(String(j));
}
} else {
for (var name in object) {
if (!(skipProto && name === 'prototype') && has.call(object, name)) {
theKeys.push(String(name));
}
}
}
if (hasDontEnumBug) {
var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
for (var k = 0; k < dontEnums.length; ++k) {
if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
theKeys.push(dontEnums[k]);
}
}
}
return theKeys;
};
keysShim.shim = function shimObjectKeys() {
if (!Object.keys) {
Object.keys = keysShim;
} else {
var keysWorksWithArguments = (function () {
// Safari 5.0 bug
return (Object.keys(arguments) || '').length === 2;
}(1, 2));
if (!keysWorksWithArguments) {
var originalKeys = Object.keys;
Object.keys = function keys(object) {
if (isArgs(object)) {
return originalKeys(slice.call(object));
} else {
return originalKeys(object);
}
};
}
}
return Object.keys || keysShim;
};
module.exports = keysShim;
},{"./isArguments":47}],47:[function(_dereq_,module,exports){
'use strict';
var toStr = Object.prototype.toString;
module.exports = function isArguments(value) {
var str = toStr.call(value);
var isArgs = str === '[object Arguments]';
if (!isArgs) {
isArgs = str !== '[object Array]' &&
value !== null &&
typeof value === 'object' &&
typeof value.length === 'number' &&
value.length >= 0 &&
toStr.call(value.callee) === '[object Function]';
}
return isArgs;
};
},{}],48:[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]
}
},{}],49:[function(_dereq_,module,exports){
function clean (s) {
return s.replace(/\n\r?\s*/g, '')
}
module.exports = function tsml (sa) {
var s = ''
, i = 0
for (; i < arguments.length; i++)
s += clean(sa[i]) + (arguments[i + 1] || '')
return s
}
},{}],50:[function(_dereq_,module,exports){
"use strict";
var window = _dereq_("global/window")
var once = _dereq_("once")
var parseHeaders = _dereq_("parse-headers")
module.exports = createXHR
createXHR.XMLHttpRequest = window.XMLHttpRequest || noop
createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest
function isEmpty(obj){
for(var i in obj){
if(obj.hasOwnProperty(i)) return false
}
return true
}
function createXHR(options, callback) {
function readystatechange() {
if (xhr.readyState === 4) {
loadFunc()
}
}
function getBody() {
// Chrome with requestType=blob throws errors arround when even testing access to responseText
var body = undefined
if (xhr.response) {
body = xhr.response
} else if (xhr.responseType === "text" || !xhr.responseType) {
body = xhr.responseText || xhr.responseXML
}
if (isJson) {
try {
body = JSON.parse(body)
} catch (e) {}
}
return body
}
var failureResponse = {
body: undefined,
headers: {},
statusCode: 0,
method: method,
url: uri,
rawRequest: xhr
}
function errorFunc(evt) {
clearTimeout(timeoutTimer)
if(!(evt instanceof Error)){
evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") )
}
evt.statusCode = 0
callback(evt, failureResponse)
}
// will load the data & process the response in a special response object
function loadFunc() {
if (aborted) return
var status
clearTimeout(timeoutTimer)
if(options.useXDR && xhr.status===undefined) {
//IE8 CORS GET successful response doesn't have a status field, but body is fine
status = 200
} else {
status = (xhr.status === 1223 ? 204 : xhr.status)
}
var response = failureResponse
var err = null
if (status !== 0){
response = {
body: getBody(),
statusCode: status,
method: method,
headers: {},
url: uri,
rawRequest: xhr
}
if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE
response.headers = parseHeaders(xhr.getAllResponseHeaders())
}
} else {
err = new Error("Internal XMLHttpRequest Error")
}
callback(err, response, response.body)
}
if (typeof options === "string") {
options = { uri: options }
}
options = options || {}
if(typeof callback === "undefined"){
throw new Error("callback argument missing")
}
callback = once(callback)
var xhr = options.xhr || null
if (!xhr) {
if (options.cors || options.useXDR) {
xhr = new createXHR.XDomainRequest()
}else{
xhr = new createXHR.XMLHttpRequest()
}
}
var key
var aborted
var uri = xhr.url = options.uri || options.url
var method = xhr.method = options.method || "GET"
var body = options.body || options.data
var headers = xhr.headers = options.headers || {}
var sync = !!options.sync
var isJson = false
var timeoutTimer
if ("json" in options) {
isJson = true
headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user
if (method !== "GET" && method !== "HEAD") {
headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user
body = JSON.stringify(options.json)
}
}
xhr.onreadystatechange = readystatechange
xhr.onload = loadFunc
xhr.onerror = errorFunc
// IE9 must have onprogress be set to a unique function.
xhr.onprogress = function () {
// IE must die
}
xhr.ontimeout = errorFunc
xhr.open(method, uri, !sync, options.username, options.password)
//has to be after open
if(!sync) {
xhr.withCredentials = !!options.withCredentials
}
// Cannot set timeout with sync request
// not setting timeout on the xhr object, because of old webkits etc. not handling that correctly
// both npm's request and jquery 1.x use this kind of timeout, so this is being consistent
if (!sync && options.timeout > 0 ) {
timeoutTimer = setTimeout(function(){
aborted=true//IE9 may still call readystatechange
xhr.abort("timeout")
var e = new Error("XMLHttpRequest timeout")
e.code = "ETIMEDOUT"
errorFunc(e)
}, options.timeout )
}
if (xhr.setRequestHeader) {
for(key in headers){
if(headers.hasOwnProperty(key)){
xhr.setRequestHeader(key, headers[key])
}
}
} else if (options.headers && !isEmpty(options.headers)) {
throw new Error("Headers cannot be set on an XDomainRequest object")
}
if ("responseType" in options) {
xhr.responseType = options.responseType
}
if ("beforeSend" in options &&
typeof options.beforeSend === "function"
) {
options.beforeSend(xhr)
}
xhr.send(body)
return xhr
}
function noop() {}
},{"global/window":2,"once":51,"parse-headers":55}],51:[function(_dereq_,module,exports){
module.exports = once
once.proto = once(function () {
Object.defineProperty(Function.prototype, 'once', {
value: function () {
return once(this)
},
configurable: true
})
})
function once (fn) {
var called = false
return function () {
if (called) return
called = true
return fn.apply(this, arguments)
}
}
},{}],52:[function(_dereq_,module,exports){
var isFunction = _dereq_('is-function')
module.exports = forEach
var toString = Object.prototype.toString
var hasOwnProperty = Object.prototype.hasOwnProperty
function forEach(list, iterator, context) {
if (!isFunction(iterator)) {
throw new TypeError('iterator must be a function')
}
if (arguments.length < 3) {
context = this
}
if (toString.call(list) === '[object Array]')
forEachArray(list, iterator, context)
else if (typeof list === 'string')
forEachString(list, iterator, context)
else
forEachObject(list, iterator, context)
}
function forEachArray(array, iterator, context) {
for (var i = 0, len = array.length; i < len; i++) {
if (hasOwnProperty.call(array, i)) {
iterator.call(context, array[i], i, array)
}
}
}
function forEachString(string, iterator, context) {
for (var i = 0, len = string.length; i < len; i++) {
// no such thing as a sparse string.
iterator.call(context, string.charAt(i), i, string)
}
}
function forEachObject(object, iterator, context) {
for (var k in object) {
if (hasOwnProperty.call(object, k)) {
iterator.call(context, object[k], k, object)
}
}
}
},{"is-function":53}],53:[function(_dereq_,module,exports){
module.exports = isFunction
var toString = Object.prototype.toString
function isFunction (fn) {
var string = toString.call(fn)
return string === '[object Function]' ||
(typeof fn === 'function' && string !== '[object RegExp]') ||
(typeof window !== 'undefined' &&
// IE8 and below
(fn === window.setTimeout ||
fn === window.alert ||
fn === window.confirm ||
fn === window.prompt))
};
},{}],54:[function(_dereq_,module,exports){
exports = module.exports = trim;
function trim(str){
return str.replace(/^\s*|\s*$/g, '');
}
exports.left = function(str){
return str.replace(/^\s*/, '');
};
exports.right = function(str){
return str.replace(/\s*$/, '');
};
},{}],55:[function(_dereq_,module,exports){
var trim = _dereq_('trim')
, forEach = _dereq_('for-each')
, isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
}
module.exports = function (headers) {
if (!headers)
return {}
var result = {}
forEach(
trim(headers).split('\n')
, function (row) {
var index = row.indexOf(':')
, key = trim(row.slice(0, index)).toLowerCase()
, value = trim(row.slice(index + 1))
if (typeof(result[key]) === 'undefined') {
result[key] = value
} else if (isArray(result[key])) {
result[key].push(value)
} else {
result[key] = [ result[key], value ]
}
}
)
return result
}
},{"for-each":52,"trim":54}],56:[function(_dereq_,module,exports){
/**
* @file big-play-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('./button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Initial play button. Shows before the video has played. The hiding of the
* big play button is done via CSS and player states.
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Button
* @class BigPlayButton
*/
var BigPlayButton = (function (_Button) {
_inherits(BigPlayButton, _Button);
function BigPlayButton(player, options) {
_classCallCheck(this, BigPlayButton);
_Button.call(this, player, options);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
BigPlayButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-big-play-button';
};
/**
* Handles click for play
*
* @method handleClick
*/
BigPlayButton.prototype.handleClick = function handleClick() {
this.player_.play();
};
return BigPlayButton;
})(_buttonJs2['default']);
BigPlayButton.prototype.controlText_ = 'Play Video';
_componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton);
exports['default'] = BigPlayButton;
module.exports = exports['default'];
},{"./button.js":57,"./component.js":58}],57:[function(_dereq_,module,exports){
/**
* @file button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* Base class for all buttons
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class Button
*/
var Button = (function (_Component) {
_inherits(Button, _Component);
function Button(player, options) {
_classCallCheck(this, Button);
_Component.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);
}
/**
* Create the component's DOM element
*
* @param {String=} type Element's node type. e.g. 'div'
* @param {Object=} props An object of element attributes that should be set on the element Tag name
* @return {Element}
* @method createEl
*/
Button.prototype.createEl = function createEl() {
var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0];
var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
props = _objectAssign2['default']({
className: this.buildCSSClass(),
tabIndex: 0
}, props);
// Add standard Aria info
attributes = _objectAssign2['default']({
role: 'button',
type: 'button', // Necessary since the default button type is "submit"
'aria-live': 'polite' // let the screen reader user know that the text of the button may change
}, attributes);
var el = _Component.prototype.createEl.call(this, tag, props, attributes);
this.controlTextEl_ = Dom.createEl('span', {
className: 'vjs-control-text'
});
el.appendChild(this.controlTextEl_);
this.controlText(this.controlText_);
return el;
};
/**
* Controls text - both request and localize
*
* @param {String} text Text for button
* @return {String}
* @method controlText
*/
Button.prototype.controlText = function controlText(text) {
if (!text) return this.controlText_ || 'Need Text';
this.controlText_ = text;
this.controlTextEl_.innerHTML = this.localize(this.controlText_);
return this;
};
/**
* Allows sub components to stack CSS class names
*
* @return {String}
* @method buildCSSClass
*/
Button.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Handle Click - Override with specific functionality for button
*
* @method handleClick
*/
Button.prototype.handleClick = function handleClick() {};
/**
* Handle Focus - Add keyboard functionality to element
*
* @method handleFocus
*/
Button.prototype.handleFocus = function handleFocus() {
Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
};
/**
* Handle KeyPress (document level) - Trigger click when keys are pressed
*
* @method handleKeyPress
*/
Button.prototype.handleKeyPress = function handleKeyPress(event) {
// Check for space bar (32) or enter (13) keys
if (event.which === 32 || event.which === 13) {
event.preventDefault();
this.handleClick(event);
}
};
/**
* Handle Blur - Remove keyboard triggers
*
* @method handleBlur
*/
Button.prototype.handleBlur = function handleBlur() {
Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress));
};
return Button;
})(_component2['default']);
_component2['default'].registerComponent('Button', Button);
exports['default'] = Button;
module.exports = exports['default'];
},{"./component":58,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"global/document":1,"object.assign":43}],58:[function(_dereq_,module,exports){
/**
* @file component.js
*
* Player Component - Base class for all UI objects
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('./utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
/**
* 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.
* ```js
* // adding a button to the player
* var button = player.addChild('button');
* button.el(); // -> button element
* ```
* ```html
* <div class="video-js">
* <div class="vjs-button">Button</div>
* </div>
* ```
* Components are also event targets.
* ```js
* button.on('click', function(){
* console.log('Button Clicked!');
* });
* button.trigger('customevent');
* ```
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @class Component
*/
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; // eslint-disable-line
} else {
this.player_ = player;
}
// Make a copy of prototype.options_ to protect against overriding defaults
this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_);
// Updated options with supplied options
options = this.options_ = _utilsMergeOptionsJs2['default'](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 && player.id && player.id() || 'no_player';
this.id_ = id + '_component_' + Guid.newGUID();
}
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();
}
}
/**
* Dispose of the component and all child components
*
* @method dispose
*/
Component.prototype.dispose = 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_);
}
Dom.removeElData(this.el_);
this.el_ = null;
};
/**
* Return the component's player
*
* @return {Player}
* @method player
*/
Component.prototype.player = function player() {
return this.player_;
};
/**
* Deep merge of options objects
* Whenever a property is an object on both options objects
* the two properties will be merged using mergeOptions.
* 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.
* ```js
* 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
* ```js
* {
* 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
* @method options
*/
Component.prototype.options = function options(obj) {
_utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0');
if (!obj) {
return this.options_;
}
this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj);
return this.options_;
};
/**
* Get the component's DOM element
* ```js
* var domEl = myComponent.el();
* ```
*
* @return {Element}
* @method el
*/
Component.prototype.el = function el() {
return this.el_;
};
/**
* Create the component's DOM element
*
* @param {String=} tagName Element's node type. e.g. 'div'
* @param {Object=} properties An object of properties that should be set
* @param {Object=} attributes An object of attributes that should be set
* @return {Element}
* @method createEl
*/
Component.prototype.createEl = function createEl(tagName, properties, attributes) {
return Dom.createEl(tagName, properties, attributes);
};
Component.prototype.localize = function localize(string) {
var code = this.player_.language && this.player_.language();
var languages = this.player_.languages && this.player_.languages();
if (!code || !languages) {
return string;
}
var language = languages[code];
if (language && language[string]) {
return language[string];
}
var primaryCode = code.split('-')[0];
var primaryLang = languages[primaryCode];
if (primaryLang && primaryLang[string]) {
return primaryLang[string];
}
return string;
};
/**
* 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}
* @method contentEl
*/
Component.prototype.contentEl = function contentEl() {
return this.contentEl_ || this.el_;
};
/**
* Get the component's ID
* ```js
* var id = myComponent.id();
* ```
*
* @return {String}
* @method id
*/
Component.prototype.id = function id() {
return this.id_;
};
/**
* Get the component's name. The name is often used to reference the component.
* ```js
* var name = myComponent.name();
* ```
*
* @return {String}
* @method name
*/
Component.prototype.name = function name() {
return this.name_;
};
/**
* Get an array of all child components
* ```js
* var kids = myComponent.children();
* ```
*
* @return {Array} The children
* @method children
*/
Component.prototype.children = function children() {
return this.children_;
};
/**
* Returns a child component with the provided ID
*
* @return {Component}
* @method getChildById
*/
Component.prototype.getChildById = function getChildById(id) {
return this.childIndex_[id];
};
/**
* Returns a child component with the provided name
*
* @return {Component}
* @method getChild
*/
Component.prototype.getChild = function getChild(name) {
return this.childNameIndex_[name];
};
/**
* Adds a child component inside this component
* ```js
* 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
* ```js
* 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)
* @method addChild
*/
Component.prototype.addChild = function addChild(child) {
var options = arguments.length <= 1 || 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) {
_utilsLogJs2['default'].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 || _utilsToTitleCaseJs2['default'](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;
};
/**
* 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
* @method removeChild
*/
Component.prototype.removeChild = 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());
}
};
/**
* Add and initialize default child components from options
* ```js
* // 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
* ```js
* 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).
* ```js
* var myComp = new MyComponent(player, {
* children: [
* 'button',
* {
* name: 'button',
* someOtherOption: true
* }
* ]
* });
* ```
*
* @method initChildren
*/
Component.prototype.initChildren = function initChildren() {
var _this = this;
var children = this.options_.children;
if (children) {
(function () {
// `this` is `parent`
var parentOptions = _this.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;
}
// Allow options to be passed as a simple boolean if no configuration
// is necessary.
if (opts === true) {
opts = {};
}
// We also want to pass the original player options to each component as well so they don't need to
// reach back into the player for options later.
opts.playerOptions = _this.options_.playerOptions;
// 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
_this[name] = _this.addChild(name, opts);
};
// Allow for an array of children details to passed in the options
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
var _name = undefined;
var opts = undefined;
if (typeof child === 'string') {
// ['myComponent']
_name = child;
opts = {};
} else {
// [{ name: 'myComponent', otherOption: true }]
_name = child.name;
opts = child;
}
handleAdd(_name, opts);
}
} else {
Object.getOwnPropertyNames(children).forEach(function (name) {
handleAdd(name, children[name]);
});
}
})();
}
};
/**
* Allows sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
Component.prototype.buildCSSClass = function buildCSSClass() {
// Child classes can include a function that does:
// return 'CLASS NAME' + this._super();
return '';
};
/**
* Add an event listener to this component's element
* ```js
* 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.
* ```js
* 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}
* @method on
*/
Component.prototype.on = function on(first, second, third) {
var _this2 = this;
if (typeof first === 'string' || Array.isArray(first)) {
Events.on(this.el_, first, Fn.bind(this, second));
// Targeting another component or element
} else {
(function () {
var target = first;
var type = second;
var fn = Fn.bind(_this2, third);
// When this component is disposed, remove the listener from the other component
var removeOnDispose = function removeOnDispose() {
return _this2.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() {
return _this2.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;
};
/**
* Remove an event listener from this component's element
* ```js
* 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.
* ```js
* 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}
* @method off
*/
Component.prototype.off = function off(first, second, third) {
if (!first || typeof first === 'string' || Array.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 = Fn.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;
};
/**
* Add an event listener to be triggered only once and then removed
* ```js
* myComponent.one('eventName', myFunc);
* ```
* Alternatively you can add a listener to another element or component
* that will be triggered only once.
* ```js
* 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}
* @method one
*/
Component.prototype.one = function one(first, second, third) {
var _this3 = this,
_arguments = arguments;
if (typeof first === 'string' || Array.isArray(first)) {
Events.one(this.el_, first, Fn.bind(this, second));
} else {
(function () {
var target = first;
var type = second;
var fn = Fn.bind(_this3, third);
var newFunc = function newFunc() {
_this3.off(target, type, newFunc);
fn.apply(null, _arguments);
};
// Keep the same function ID so we can remove it later
newFunc.guid = fn.guid;
_this3.on(target, type, newFunc);
})();
}
return this;
};
/**
* Trigger an event on an element
* ```js
* myComponent.trigger('eventName');
* myComponent.trigger({'type':'eventName'});
* myComponent.trigger('eventName', {data: 'some data'});
* myComponent.trigger({'type':'eventName'}, {data: 'some data'});
* ```
*
* @param {Event|Object|String} event A string (the type) or an event object with a type attribute
* @param {Object} [hash] data hash to pass along with the event
* @return {Component} self
* @method trigger
*/
Component.prototype.trigger = function trigger(event, hash) {
Events.trigger(this.el_, event, hash);
return this;
};
/**
* 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
* @param {Boolean} sync Exec the listener synchronously if component is ready
* @return {Component}
* @method ready
*/
Component.prototype.ready = function ready(fn) {
var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (fn) {
if (this.isReady_) {
if (sync) {
fn.call(this);
} else {
// Call the function asynchronously by default for consistency
this.setTimeout(fn, 1);
}
} else {
this.readyQueue_ = this.readyQueue_ || [];
this.readyQueue_.push(fn);
}
}
return this;
};
/**
* Trigger the ready listeners
*
* @return {Component}
* @method triggerReady
*/
Component.prototype.triggerReady = function triggerReady() {
this.isReady_ = true;
// Ensure ready is triggerd asynchronously
this.setTimeout(function () {
var readyQueue = this.readyQueue_;
if (readyQueue && readyQueue.length > 0) {
readyQueue.forEach(function (fn) {
fn.call(this);
}, this);
// Reset Ready Queue
this.readyQueue_ = [];
}
// Allow for using event listeners also
this.trigger('ready');
}, 1);
};
/**
* Check if a component's element has a CSS class name
*
* @param {String} classToCheck Classname to check
* @return {Component}
* @method hasClass
*/
Component.prototype.hasClass = function hasClass(classToCheck) {
return Dom.hasElClass(this.el_, classToCheck);
};
/**
* Add a CSS class name to the component's element
*
* @param {String} classToAdd Classname to add
* @return {Component}
* @method addClass
*/
Component.prototype.addClass = function addClass(classToAdd) {
Dom.addElClass(this.el_, classToAdd);
return this;
};
/**
* Remove and return a CSS class name from the component's element
*
* @param {String} classToRemove Classname to remove
* @return {Component}
* @method removeClass
*/
Component.prototype.removeClass = function removeClass(classToRemove) {
Dom.removeElClass(this.el_, classToRemove);
return this;
};
/**
* Show the component element if hidden
*
* @return {Component}
* @method show
*/
Component.prototype.show = function show() {
this.removeClass('vjs-hidden');
return this;
};
/**
* Hide the component element if currently showing
*
* @return {Component}
* @method hide
*/
Component.prototype.hide = function hide() {
this.addClass('vjs-hidden');
return this;
};
/**
* Lock an item in its visible state
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
* @method lockShowing
*/
Component.prototype.lockShowing = function lockShowing() {
this.addClass('vjs-lock-showing');
return this;
};
/**
* Unlock an item to be hidden
* To be used with fadeIn/fadeOut.
*
* @return {Component}
* @private
* @method unlockShowing
*/
Component.prototype.unlockShowing = function unlockShowing() {
this.removeClass('vjs-lock-showing');
return this;
};
/**
* 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
* @method width
*/
Component.prototype.width = function width(num, skipListeners) {
return this.dimension('width', num, skipListeners);
};
/**
* 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
* @method height
*/
Component.prototype.height = function height(num, skipListeners) {
return this.dimension('height', num, skipListeners);
};
/**
* Set both width and height at the same time
*
* @param {Number|String} width Width of player
* @param {Number|String} height Height of player
* @return {Component} The component
* @method dimensions
*/
Component.prototype.dimensions = function dimensions(width, height) {
// Skip resize listeners on width for optimization
return this.width(width, true).height(height);
};
/**
* 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
* @method dimension
*/
Component.prototype.dimension = 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
return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10);
};
/**
* 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
* @method emitTapEvents
*/
Component.prototype.emitTapEvents = 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) {
// Copy the touches object to prevent modifying the original
firstTouch = _objectAssign2['default']({}, 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) {
// Don't let browser turn this into a click
event.preventDefault();
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
// Events.fixEvent runs (e.g. event.target)
}
}
});
};
/**
* 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.
*
* @method enableTouchActivity
*/
Component.prototype.enableTouchActivity = function enableTouchActivity() {
// Don't continue if the root player doesn't support reporting user activity
if (!this.player() || !this.player().reportUserActivity) {
return;
}
// listener for reporting that the user is active
var report = Fn.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);
};
/**
* 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
* @method setTimeout
*/
Component.prototype.setTimeout = function setTimeout(fn, timeout) {
fn = Fn.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 = _globalWindow2['default'].setTimeout(fn, timeout);
var disposeFn = function disposeFn() {
this.clearTimeout(timeoutId);
};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.on('dispose', disposeFn);
return timeoutId;
};
/**
* 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
* @method clearTimeout
*/
Component.prototype.clearTimeout = function clearTimeout(timeoutId) {
_globalWindow2['default'].clearTimeout(timeoutId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-timeout-' + timeoutId;
this.off('dispose', disposeFn);
return timeoutId;
};
/**
* 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
* @method setInterval
*/
Component.prototype.setInterval = function setInterval(fn, interval) {
fn = Fn.bind(this, fn);
var intervalId = _globalWindow2['default'].setInterval(fn, interval);
var disposeFn = function disposeFn() {
this.clearInterval(intervalId);
};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.on('dispose', disposeFn);
return intervalId;
};
/**
* 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
* @method clearInterval
*/
Component.prototype.clearInterval = function clearInterval(intervalId) {
_globalWindow2['default'].clearInterval(intervalId);
var disposeFn = function disposeFn() {};
disposeFn.guid = 'vjs-interval-' + intervalId;
this.off('dispose', disposeFn);
return intervalId;
};
/**
* Registers a component
*
* @param {String} name Name of the component to register
* @param {Object} comp The component to register
* @static
* @method registerComponent
*/
Component.registerComponent = function registerComponent(name, comp) {
if (!Component.components_) {
Component.components_ = {};
}
Component.components_[name] = comp;
return comp;
};
/**
* Gets a component by name
*
* @param {String} name Name of the component to get
* @return {Component}
* @static
* @method getComponent
*/
Component.getComponent = function getComponent(name) {
if (Component.components_ && Component.components_[name]) {
return Component.components_[name];
}
if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) {
_utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)');
return _globalWindow2['default'].videojs[name];
}
};
/**
* Sets up the constructor using the supplied init method
* or uses the init of the parent object
*
* @param {Object} props An object of properties
* @static
* @deprecated
* @method extend
*/
Component.extend = function extend(props) {
props = props || {};
_utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extends(Component, {}) instead');
// 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 = Object.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;
// Extend subObj's prototype with functions and other properties from props
for (var _name2 in props) {
if (props.hasOwnProperty(_name2)) {
subObj.prototype[_name2] = props[_name2];
}
}
return subObj;
};
return Component;
})();
Component.registerComponent('Component', Component);
exports['default'] = Component;
module.exports = exports['default'];
},{"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/guid.js":122,"./utils/log.js":123,"./utils/merge-options.js":124,"./utils/to-title-case.js":127,"global/window":2,"object.assign":43}],59:[function(_dereq_,module,exports){
/**
* @file control-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
// Required children
var _playToggleJs = _dereq_('./play-toggle.js');
var _playToggleJs2 = _interopRequireDefault(_playToggleJs);
var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js');
var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs);
var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js');
var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs);
var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js');
var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs);
var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js');
var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs);
var _liveDisplayJs = _dereq_('./live-display.js');
var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs);
var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js');
var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs);
var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js');
var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs);
var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js');
var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs);
var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js');
var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs);
var _muteToggleJs = _dereq_('./mute-toggle.js');
var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs);
var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js');
var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs);
var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js');
var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs);
var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js');
var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs);
var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js');
var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs);
var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js');
var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs);
/**
* Container of main controls
*
* @extends Component
* @class ControlBar
*/
var ControlBar = (function (_Component) {
_inherits(ControlBar, _Component);
function ControlBar() {
_classCallCheck(this, ControlBar);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ControlBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-control-bar'
});
};
return ControlBar;
})(_componentJs2['default']);
ControlBar.prototype.options_ = {
loadEvent: 'play',
children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle']
};
_componentJs2['default'].registerComponent('ControlBar', ControlBar);
exports['default'] = ControlBar;
module.exports = exports['default'];
},{"../component.js":58,"./fullscreen-toggle.js":60,"./live-display.js":61,"./mute-toggle.js":62,"./play-toggle.js":63,"./playback-rate-menu/playback-rate-menu-button.js":64,"./progress-control/progress-control.js":69,"./spacer-controls/custom-control-spacer.js":71,"./text-track-controls/captions-button.js":74,"./text-track-controls/chapters-button.js":75,"./text-track-controls/subtitles-button.js":78,"./time-controls/current-time-display.js":81,"./time-controls/duration-display.js":82,"./time-controls/remaining-time-display.js":83,"./time-controls/time-divider.js":84,"./volume-control/volume-control.js":86,"./volume-menu-button.js":88}],60:[function(_dereq_,module,exports){
/**
* @file fullscreen-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Toggle fullscreen video
*
* @extends Button
* @class FullscreenToggle
*/
var FullscreenToggle = (function (_Button) {
_inherits(FullscreenToggle, _Button);
function FullscreenToggle() {
_classCallCheck(this, FullscreenToggle);
_Button.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handles click for full screen
*
* @method handleClick
*/
FullscreenToggle.prototype.handleClick = function handleClick() {
if (!this.player_.isFullscreen()) {
this.player_.requestFullscreen();
this.controlText('Non-Fullscreen');
} else {
this.player_.exitFullscreen();
this.controlText('Fullscreen');
}
};
return FullscreenToggle;
})(_buttonJs2['default']);
FullscreenToggle.prototype.controlText_ = 'Fullscreen';
_componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle);
exports['default'] = FullscreenToggle;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58}],61:[function(_dereq_,module,exports){
/**
* @file live-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Displays the live indicator
* TODO - Future make it click to snap to live
*
* @extends Component
* @class LiveDisplay
*/
var LiveDisplay = (function (_Component) {
_inherits(LiveDisplay, _Component);
function LiveDisplay(player, options) {
_classCallCheck(this, LiveDisplay);
_Component.call(this, player, options);
this.updateShowing();
this.on(this.player(), 'durationchange', this.updateShowing);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
LiveDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-live-control vjs-control'
});
this.contentEl_ = Dom.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;
};
LiveDisplay.prototype.updateShowing = function updateShowing() {
if (this.player().duration() === Infinity) {
this.show();
} else {
this.hide();
}
};
return LiveDisplay;
})(_component2['default']);
_component2['default'].registerComponent('LiveDisplay', LiveDisplay);
exports['default'] = LiveDisplay;
module.exports = exports['default'];
},{"../component":58,"../utils/dom.js":118}],62:[function(_dereq_,module,exports){
/**
* @file mute-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _button = _dereq_('../button');
var _button2 = _interopRequireDefault(_button);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* A button component for muting the audio
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MuteToggle
*/
var MuteToggle = (function (_Button) {
_inherits(MuteToggle, _Button);
function MuteToggle(player, options) {
_classCallCheck(this, MuteToggle);
_Button.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 () {
this.update(); // We need to update the button to account for a default muted state.
if (player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
});
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
MuteToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handle click on mute
*
* @method handleClick
*/
MuteToggle.prototype.handleClick = function handleClick() {
this.player_.muted(this.player_.muted() ? false : true);
};
/**
* Update volume
*
* @method update
*/
MuteToggle.prototype.update = 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.controlText() !== localizedMute) {
this.controlText(localizedMute);
}
/* TODO improve muted icon classes */
for (var i = 0; i < 4; i++) {
Dom.removeElClass(this.el_, 'vjs-vol-' + i);
}
Dom.addElClass(this.el_, 'vjs-vol-' + level);
};
return MuteToggle;
})(_button2['default']);
MuteToggle.prototype.controlText_ = 'Mute';
_component2['default'].registerComponent('MuteToggle', MuteToggle);
exports['default'] = MuteToggle;
module.exports = exports['default'];
},{"../button":57,"../component":58,"../utils/dom.js":118}],63:[function(_dereq_,module,exports){
/**
* @file play-toggle.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Button to toggle between play and pause
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class PlayToggle
*/
var PlayToggle = (function (_Button) {
_inherits(PlayToggle, _Button);
function PlayToggle(player, options) {
_classCallCheck(this, PlayToggle);
_Button.call(this, player, options);
this.on(player, 'play', this.handlePlay);
this.on(player, 'pause', this.handlePause);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
PlayToggle.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* Handle click to toggle between play and pause
*
* @method handleClick
*/
PlayToggle.prototype.handleClick = function handleClick() {
if (this.player_.paused()) {
this.player_.play();
} else {
this.player_.pause();
}
};
/**
* Add the vjs-playing class to the element so it can change appearance
*
* @method handlePlay
*/
PlayToggle.prototype.handlePlay = function handlePlay() {
this.removeClass('vjs-paused');
this.addClass('vjs-playing');
this.controlText('Pause'); // change the button text to "Pause"
};
/**
* Add the vjs-paused class to the element so it can change appearance
*
* @method handlePause
*/
PlayToggle.prototype.handlePause = function handlePause() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.controlText('Play'); // change the button text to "Play"
};
return PlayToggle;
})(_buttonJs2['default']);
PlayToggle.prototype.controlText_ = 'Play';
_componentJs2['default'].registerComponent('PlayToggle', PlayToggle);
exports['default'] = PlayToggle;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58}],64:[function(_dereq_,module,exports){
/**
* @file playback-rate-menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _menuMenuJs = _dereq_('../../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js');
var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* The component for controlling the playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class PlaybackRateMenuButton
*/
var PlaybackRateMenuButton = (function (_MenuButton) {
_inherits(PlaybackRateMenuButton, _MenuButton);
function PlaybackRateMenuButton(player, options) {
_classCallCheck(this, PlaybackRateMenuButton);
_MenuButton.call(this, player, options);
this.updateVisibility();
this.updateLabel();
this.on(player, 'loadstart', this.updateVisibility);
this.on(player, 'ratechange', this.updateLabel);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
PlaybackRateMenuButton.prototype.createEl = function createEl() {
var el = _MenuButton.prototype.createEl.call(this);
this.labelEl_ = Dom.createEl('div', {
className: 'vjs-playback-rate-value',
innerHTML: 1.0
});
el.appendChild(this.labelEl_);
return el;
};
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this);
};
/**
* Create the playback rate menu
*
* @return {Menu} Menu object populated with items
* @method createMenu
*/
PlaybackRateMenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuMenuJs2['default'](this.player());
var rates = this.playbackRates();
if (rates) {
for (var i = rates.length - 1; i >= 0; i--) {
menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' }));
}
}
return menu;
};
/**
* Updates ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current playback rate
this.el().setAttribute('aria-valuenow', this.player().playbackRate());
};
/**
* Handle menu item click
*
* @method handleClick
*/
PlaybackRateMenuButton.prototype.handleClick = function handleClick() {
// select next rate option
var currentRate = this.player().playbackRate();
var rates = this.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);
};
/**
* Get possible playback rates
*
* @return {Array} Possible playback rates
* @method playbackRates
*/
PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() {
return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates'];
};
/**
* Get supported playback rates
*
* @return {Array} Supported playback rates
* @method playbackRateSupported
*/
PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() {
return this.player().tech_ && this.player().tech_['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0;
};
/**
* Hide playback rate controls when they're no playback rate options to select
*
* @method updateVisibility
*/
PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() {
if (this.playbackRateSupported()) {
this.removeClass('vjs-hidden');
} else {
this.addClass('vjs-hidden');
}
};
/**
* Update button label when rate changed
*
* @method updateLabel
*/
PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() {
if (this.playbackRateSupported()) {
this.labelEl_.innerHTML = this.player().playbackRate() + 'x';
}
};
return PlaybackRateMenuButton;
})(_menuMenuButtonJs2['default']);
PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate';
_componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton);
exports['default'] = PlaybackRateMenuButton;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-button.js":95,"../../menu/menu.js":97,"../../utils/dom.js":118,"./playback-rate-menu-item.js":65}],65:[function(_dereq_,module,exports){
/**
* @file playback-rate-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The specific menu item type for selecting a playback rate
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class PlaybackRateMenuItem
*/
var PlaybackRateMenuItem = (function (_MenuItem) {
_inherits(PlaybackRateMenuItem, _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;
_MenuItem.call(this, player, options);
this.label = label;
this.rate = rate;
this.on(player, 'ratechange', this.update);
}
/**
* Handle click on menu item
*
* @method handleClick
*/
PlaybackRateMenuItem.prototype.handleClick = function handleClick() {
_MenuItem.prototype.handleClick.call(this);
this.player().playbackRate(this.rate);
};
/**
* Update playback rate with selected rate
*
* @method update
*/
PlaybackRateMenuItem.prototype.update = function update() {
this.selected(this.player().playbackRate() === this.rate);
};
return PlaybackRateMenuItem;
})(_menuMenuItemJs2['default']);
PlaybackRateMenuItem.prototype.contentElType = 'button';
_componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem);
exports['default'] = PlaybackRateMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-item.js":96}],66:[function(_dereq_,module,exports){
/**
* @file load-progress-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Shows load progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class LoadProgressBar
*/
var LoadProgressBar = (function (_Component) {
_inherits(LoadProgressBar, _Component);
function LoadProgressBar(player, options) {
_classCallCheck(this, LoadProgressBar);
_Component.call(this, player, options);
this.on(player, 'progress', this.update);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
LoadProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-load-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>'
});
};
/**
* Update progress bar
*
* @method update
*/
LoadProgressBar.prototype.update = 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 >= 1 ? 1 : 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(Dom.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;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar);
exports['default'] = LoadProgressBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118}],67:[function(_dereq_,module,exports){
/**
* @file mouse-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _lodashCompatFunctionThrottle = _dereq_('lodash-compat/function/throttle');
var _lodashCompatFunctionThrottle2 = _interopRequireDefault(_lodashCompatFunctionThrottle);
/**
* The Mouse Time Display component shows the time you will seek to
* when hovering over the progress bar
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class MouseTimeDisplay
*/
var MouseTimeDisplay = (function (_Component) {
_inherits(MouseTimeDisplay, _Component);
function MouseTimeDisplay(player, options) {
var _this = this;
_classCallCheck(this, MouseTimeDisplay);
_Component.call(this, player, options);
this.update(0, 0);
player.on('ready', function () {
_this.on(player.controlBar.progressControl.el(), 'mousemove', _lodashCompatFunctionThrottle2['default'](Fn.bind(_this, _this.handleMouseMove), 25));
});
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
MouseTimeDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-mouse-display'
});
};
MouseTimeDisplay.prototype.handleMouseMove = function handleMouseMove(event) {
var duration = this.player_.duration();
var newTime = this.calculateDistance(event) * duration;
var position = event.pageX - Dom.findElPosition(this.el().parentNode).left;
this.update(newTime, position);
};
MouseTimeDisplay.prototype.update = function update(newTime, position) {
var time = _utilsFormatTimeJs2['default'](newTime, this.player_.duration());
this.el().style.left = position + 'px';
this.el().setAttribute('data-current-time', time);
};
MouseTimeDisplay.prototype.calculateDistance = function calculateDistance(event) {
return Dom.getPointerPosition(this.el().parentNode, event).x;
};
return MouseTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay);
exports['default'] = MouseTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/fn.js":120,"../../utils/format-time.js":121,"lodash-compat/function/throttle":7}],68:[function(_dereq_,module,exports){
/**
* @file play-progress-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Shows play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class PlayProgressBar
*/
var PlayProgressBar = (function (_Component) {
_inherits(PlayProgressBar, _Component);
function PlayProgressBar(player, options) {
_classCallCheck(this, PlayProgressBar);
_Component.call(this, player, options);
this.updateDataAttr();
this.on(player, 'timeupdate', this.updateDataAttr);
player.ready(Fn.bind(this, this.updateDataAttr));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
PlayProgressBar.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-play-progress',
innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>'
});
};
PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() {
var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime();
this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration()));
};
return PlayProgressBar;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar);
exports['default'] = PlayProgressBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/fn.js":120,"../../utils/format-time.js":121}],69:[function(_dereq_,module,exports){
/**
* @file progress-control.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _seekBarJs = _dereq_('./seek-bar.js');
var _seekBarJs2 = _interopRequireDefault(_seekBarJs);
var _mouseTimeDisplayJs = _dereq_('./mouse-time-display.js');
var _mouseTimeDisplayJs2 = _interopRequireDefault(_mouseTimeDisplayJs);
/**
* The Progress Control component contains the seek bar, load progress,
* and play progress
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class ProgressControl
*/
var ProgressControl = (function (_Component) {
_inherits(ProgressControl, _Component);
function ProgressControl() {
_classCallCheck(this, ProgressControl);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ProgressControl.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-control vjs-control'
});
};
return ProgressControl;
})(_componentJs2['default']);
ProgressControl.prototype.options_ = {
children: {
'seekBar': {}
}
};
_componentJs2['default'].registerComponent('ProgressControl', ProgressControl);
exports['default'] = ProgressControl;
module.exports = exports['default'];
},{"../../component.js":58,"./mouse-time-display.js":67,"./seek-bar.js":70}],70:[function(_dereq_,module,exports){
/**
* @file seek-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _sliderSliderJs = _dereq_('../../slider/slider.js');
var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _loadProgressBarJs = _dereq_('./load-progress-bar.js');
var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs);
var _playProgressBarJs = _dereq_('./play-progress-bar.js');
var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* Seek Bar and holder for the progress bars
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Slider
* @class SeekBar
*/
var SeekBar = (function (_Slider) {
_inherits(SeekBar, _Slider);
function SeekBar(player, options) {
_classCallCheck(this, SeekBar);
_Slider.call(this, player, options);
this.on(player, 'timeupdate', this.updateARIAAttributes);
player.ready(Fn.bind(this, this.updateARIAAttributes));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
SeekBar.prototype.createEl = function createEl() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-progress-holder'
}, {
'aria-label': 'video progress bar'
});
};
/**
* Update ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
SeekBar.prototype.updateARIAAttributes = 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', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete)
this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete)
};
/**
* Get percentage of video played
*
* @return {Number} Percentage played
* @method getPercent
*/
SeekBar.prototype.getPercent = function getPercent() {
var percent = this.player_.currentTime() / this.player_.duration();
return percent >= 1 ? 1 : percent;
};
/**
* Handle mouse down on seek bar
*
* @method handleMouseDown
*/
SeekBar.prototype.handleMouseDown = function handleMouseDown(event) {
_Slider.prototype.handleMouseDown.call(this, event);
this.player_.scrubbing(true);
this.videoWasPlaying = !this.player_.paused();
this.player_.pause();
};
/**
* Handle mouse move on seek bar
*
* @method handleMouseMove
*/
SeekBar.prototype.handleMouseMove = 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);
};
/**
* Handle mouse up on seek bar
*
* @method handleMouseUp
*/
SeekBar.prototype.handleMouseUp = function handleMouseUp(event) {
_Slider.prototype.handleMouseUp.call(this, event);
this.player_.scrubbing(false);
if (this.videoWasPlaying) {
this.player_.play();
}
};
/**
* Move more quickly fast forward for keyboard-only users
*
* @method stepForward
*/
SeekBar.prototype.stepForward = function stepForward() {
this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users
};
/**
* Move more quickly rewind for keyboard-only users
*
* @method stepBack
*/
SeekBar.prototype.stepBack = function stepBack() {
this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users
};
return SeekBar;
})(_sliderSliderJs2['default']);
SeekBar.prototype.options_ = {
children: {
'loadProgressBar': {},
'mouseTimeDisplay': {},
'playProgressBar': {}
},
'barName': 'playProgressBar'
};
SeekBar.prototype.playerEvent = 'timeupdate';
_componentJs2['default'].registerComponent('SeekBar', SeekBar);
exports['default'] = SeekBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../slider/slider.js":102,"../../utils/fn.js":120,"../../utils/format-time.js":121,"./load-progress-bar.js":66,"./play-progress-bar.js":68,"object.assign":43}],71:[function(_dereq_,module,exports){
/**
* @file custom-control-spacer.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _spacerJs = _dereq_('./spacer.js');
var _spacerJs2 = _interopRequireDefault(_spacerJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Spacer specifically meant to be used as an insertion point for new plugins, etc.
*
* @extends Spacer
* @class CustomControlSpacer
*/
var CustomControlSpacer = (function (_Spacer) {
_inherits(CustomControlSpacer, _Spacer);
function CustomControlSpacer() {
_classCallCheck(this, CustomControlSpacer);
_Spacer.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
CustomControlSpacer.prototype.createEl = function createEl() {
var el = _Spacer.prototype.createEl.call(this, {
className: this.buildCSSClass()
});
// No-flex/table-cell mode requires there be some content
// in the cell to fill the remaining space of the table.
el.innerHTML = ' ';
return el;
};
return CustomControlSpacer;
})(_spacerJs2['default']);
_componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer);
exports['default'] = CustomControlSpacer;
module.exports = exports['default'];
},{"../../component.js":58,"./spacer.js":72}],72:[function(_dereq_,module,exports){
/**
* @file spacer.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* 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.
*
* @extends Component
* @class Spacer
*/
var Spacer = (function (_Component) {
_inherits(Spacer, _Component);
function Spacer() {
_classCallCheck(this, Spacer);
_Component.apply(this, arguments);
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
Spacer.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Spacer.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
return Spacer;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Spacer', Spacer);
exports['default'] = Spacer;
module.exports = exports['default'];
},{"../../component.js":58}],73:[function(_dereq_,module,exports){
/**
* @file caption-settings-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The menu item for caption track settings menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends TextTrackMenuItem
* @class CaptionSettingsMenuItem
*/
var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) {
_inherits(CaptionSettingsMenuItem, _TextTrackMenuItem);
function CaptionSettingsMenuItem(player, options) {
_classCallCheck(this, CaptionSettingsMenuItem);
options['track'] = {
'kind': options['kind'],
'player': player,
'label': options['kind'] + ' settings',
'default': false,
mode: 'disabled'
};
_TextTrackMenuItem.call(this, player, options);
this.addClass('vjs-texttrack-settings');
}
/**
* Handle click on menu item
*
* @method handleClick
*/
CaptionSettingsMenuItem.prototype.handleClick = function handleClick() {
this.player().getChild('textTrackSettings').show();
};
return CaptionSettingsMenuItem;
})(_textTrackMenuItemJs2['default']);
_componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem);
exports['default'] = CaptionSettingsMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"./text-track-menu-item.js":80}],74:[function(_dereq_,module,exports){
/**
* @file captions-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js');
var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs);
/**
* The button component for toggling and selecting captions
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class CaptionsButton
*/
var CaptionsButton = (function (_TextTrackButton) {
_inherits(CaptionsButton, _TextTrackButton);
function CaptionsButton(player, options, ready) {
_classCallCheck(this, CaptionsButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Captions Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
CaptionsButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
/**
* Update caption menu items
*
* @method update
*/
CaptionsButton.prototype.update = function update() {
var threshold = 2;
_TextTrackButton.prototype.update.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();
}
};
/**
* Create caption menu items
*
* @return {Array} Array of menu items
* @method createItems
*/
CaptionsButton.prototype.createItems = function createItems() {
var items = [];
if (!(this.player().tech_ && this.player().tech_['featuresNativeTextTracks'])) {
items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ }));
}
return _TextTrackButton.prototype.createItems.call(this, items);
};
return CaptionsButton;
})(_textTrackButtonJs2['default']);
CaptionsButton.prototype.kind_ = 'captions';
CaptionsButton.prototype.controlText_ = 'Captions';
_componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton);
exports['default'] = CaptionsButton;
module.exports = exports['default'];
},{"../../component.js":58,"./caption-settings-menu-item.js":73,"./text-track-button.js":79}],75:[function(_dereq_,module,exports){
/**
* @file chapters-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js');
var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs);
var _menuMenuJs = _dereq_('../../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* The button component for toggling and selecting chapters
* Chapters act much differently than other text tracks
* Cues are navigation vs. other tracks of alternative languages
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class ChaptersButton
*/
var ChaptersButton = (function (_TextTrackButton) {
_inherits(ChaptersButton, _TextTrackButton);
function ChaptersButton(player, options, ready) {
_classCallCheck(this, ChaptersButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Chapters Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
ChaptersButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
/**
* Create a menu item for each text track
*
* @return {Array} Array of menu items
* @method createItems
*/
ChaptersButton.prototype.createItems = 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 _textTrackMenuItemJs2['default'](this.player_, {
'track': track
}));
}
}
return items;
};
/**
* Create menu from chapter buttons
*
* @return {Menu} Menu of chapter buttons
* @method createMenu
*/
ChaptersButton.prototype.createMenu = 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
_globalWindow2['default'].setTimeout(Fn.bind(this, function () {
this.createMenu();
}), 100);
/* jshint loopfunc:false */
} else {
chaptersTrack = track;
break;
}
}
}
var menu = this.menu;
if (menu === undefined) {
menu = new _menuMenuJs2['default'](this.player_);
menu.contentEl().appendChild(Dom.createEl('li', {
className: 'vjs-menu-title',
innerHTML: _utilsToTitleCaseJs2['default'](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 _chaptersTrackMenuItemJs2['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;
})(_textTrackButtonJs2['default']);
ChaptersButton.prototype.kind_ = 'chapters';
ChaptersButton.prototype.controlText_ = 'Chapters';
_componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton);
exports['default'] = ChaptersButton;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu.js":97,"../../utils/dom.js":118,"../../utils/fn.js":120,"../../utils/to-title-case.js":127,"./chapters-track-menu-item.js":76,"./text-track-button.js":79,"./text-track-menu-item.js":80,"global/window":2}],76:[function(_dereq_,module,exports){
/**
* @file chapters-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
/**
* The chapter track menu item
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class ChaptersTrackMenuItem
*/
var ChaptersTrackMenuItem = (function (_MenuItem) {
_inherits(ChaptersTrackMenuItem, _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'];
_MenuItem.call(this, player, options);
this.track = track;
this.cue = cue;
track.addEventListener('cuechange', Fn.bind(this, this.update));
}
/**
* Handle click on menu item
*
* @method handleClick
*/
ChaptersTrackMenuItem.prototype.handleClick = function handleClick() {
_MenuItem.prototype.handleClick.call(this);
this.player_.currentTime(this.cue.startTime);
this.update(this.cue.startTime);
};
/**
* Update chapter menu item
*
* @method update
*/
ChaptersTrackMenuItem.prototype.update = 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;
})(_menuMenuItemJs2['default']);
_componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem);
exports['default'] = ChaptersTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-item.js":96,"../../utils/fn.js":120}],77:[function(_dereq_,module,exports){
/**
* @file off-text-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* A special menu item for turning of a specific type of text track
*
* @param {Player|Object} player
* @param {Object=} options
* @extends TextTrackMenuItem
* @class OffTextTrackMenuItem
*/
var OffTextTrackMenuItem = (function (_TextTrackMenuItem) {
_inherits(OffTextTrackMenuItem, _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'
};
_TextTrackMenuItem.call(this, player, options);
this.selected(true);
}
/**
* Handle text track change
*
* @param {Object} event Event object
* @method handleTracksChange
*/
OffTextTrackMenuItem.prototype.handleTracksChange = 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;
})(_textTrackMenuItemJs2['default']);
_componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem);
exports['default'] = OffTextTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"./text-track-menu-item.js":80}],78:[function(_dereq_,module,exports){
/**
* @file subtitles-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _textTrackButtonJs = _dereq_('./text-track-button.js');
var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* The button component for toggling and selecting subtitles
*
* @param {Object} player Player object
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends TextTrackButton
* @class SubtitlesButton
*/
var SubtitlesButton = (function (_TextTrackButton) {
_inherits(SubtitlesButton, _TextTrackButton);
function SubtitlesButton(player, options, ready) {
_classCallCheck(this, SubtitlesButton);
_TextTrackButton.call(this, player, options, ready);
this.el_.setAttribute('aria-label', 'Subtitles Menu');
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() {
return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this);
};
return SubtitlesButton;
})(_textTrackButtonJs2['default']);
SubtitlesButton.prototype.kind_ = 'subtitles';
SubtitlesButton.prototype.controlText_ = 'Subtitles';
_componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton);
exports['default'] = SubtitlesButton;
module.exports = exports['default'];
},{"../../component.js":58,"./text-track-button.js":79}],79:[function(_dereq_,module,exports){
/**
* @file text-track-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js');
var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs);
var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js');
var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs);
/**
* The base class for buttons that toggle specific text track types (e.g. subtitles)
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class TextTrackButton
*/
var TextTrackButton = (function (_MenuButton) {
_inherits(TextTrackButton, _MenuButton);
function TextTrackButton(player, options) {
_classCallCheck(this, TextTrackButton);
_MenuButton.call(this, player, options);
var tracks = this.player_.textTracks();
if (this.items.length <= 1) {
this.hide();
}
if (!tracks) {
return;
}
var updateHandler = Fn.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);
});
}
// Create a menu item for each text track
TextTrackButton.prototype.createItems = function createItems() {
var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0];
// Add an OFF menu item to turn all tracks off
items.push(new _offTextTrackMenuItemJs2['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 _textTrackMenuItemJs2['default'](this.player_, {
'track': track
}));
}
}
return items;
};
return TextTrackButton;
})(_menuMenuButtonJs2['default']);
_componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton);
exports['default'] = TextTrackButton;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-button.js":95,"../../utils/fn.js":120,"./off-text-track-menu-item.js":77,"./text-track-menu-item.js":80}],80:[function(_dereq_,module,exports){
/**
* @file text-track-menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _menuMenuItemJs = _dereq_('../../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* The specific menu item type for selecting a language within a text track kind
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuItem
* @class TextTrackMenuItem
*/
var TextTrackMenuItem = (function (_MenuItem) {
_inherits(TextTrackMenuItem, _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';
_MenuItem.call(this, player, options);
this.track = track;
if (tracks) {
(function () {
var changeHandler = Fn.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 _globalWindow2['default'].Event !== 'object') {
// Android 2.3 throws an Illegal Constructor error for window.Event
try {
event = new _globalWindow2['default'].Event('change');
} catch (err) {}
}
if (!event) {
event = _globalDocument2['default'].createEvent('Event');
event.initEvent('change', true, true);
}
tracks.dispatchEvent(event);
});
})();
}
}
/**
* Handle click on text track
*
* @method handleClick
*/
TextTrackMenuItem.prototype.handleClick = function handleClick(event) {
var kind = this.track['kind'];
var tracks = this.player_.textTracks();
_MenuItem.prototype.handleClick.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';
}
}
};
/**
* Handle text track change
*
* @method handleTracksChange
*/
TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) {
this.selected(this.track['mode'] === 'showing');
};
return TextTrackMenuItem;
})(_menuMenuItemJs2['default']);
_componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem);
exports['default'] = TextTrackMenuItem;
module.exports = exports['default'];
},{"../../component.js":58,"../../menu/menu-item.js":96,"../../utils/fn.js":120,"global/document":1,"global/window":2}],81:[function(_dereq_,module,exports){
/**
* @file current-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the current time
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class CurrentTimeDisplay
*/
var CurrentTimeDisplay = (function (_Component) {
_inherits(CurrentTimeDisplay, _Component);
function CurrentTimeDisplay(player, options) {
_classCallCheck(this, CurrentTimeDisplay);
_Component.call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
CurrentTimeDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-current-time vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-current-time-display',
// label the current time for screen reader users
innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update current time display
*
* @method updateContent
*/
CurrentTimeDisplay.prototype.updateContent = 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 = _utilsFormatTimeJs2['default'](time, this.player_.duration());
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime;
};
return CurrentTimeDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay);
exports['default'] = CurrentTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],82:[function(_dereq_,module,exports){
/**
* @file duration-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the duration
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class DurationDisplay
*/
var DurationDisplay = (function (_Component) {
_inherits(DurationDisplay, _Component);
function DurationDisplay(player, options) {
_classCallCheck(this, DurationDisplay);
_Component.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);
this.on(player, 'loadedmetadata', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
DurationDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-duration vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-duration-display',
// label the duration time for screen reader users
innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update duration time display
*
* @method updateContent
*/
DurationDisplay.prototype.updateContent = function updateContent() {
var duration = this.player_.duration();
if (duration) {
var localizedText = this.localize('Duration Time');
var formattedTime = _utilsFormatTimeJs2['default'](duration);
this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users
}
};
return DurationDisplay;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay);
exports['default'] = DurationDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],83:[function(_dereq_,module,exports){
/**
* @file remaining-time-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
/**
* Displays the time left in the video
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class RemainingTimeDisplay
*/
var RemainingTimeDisplay = (function (_Component) {
_inherits(RemainingTimeDisplay, _Component);
function RemainingTimeDisplay(player, options) {
_classCallCheck(this, RemainingTimeDisplay);
_Component.call(this, player, options);
this.on(player, 'timeupdate', this.updateContent);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
RemainingTimeDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-remaining-time vjs-time-control vjs-control'
});
this.contentEl_ = Dom.createEl('div', {
className: 'vjs-remaining-time-display',
// label the remaining time for screen reader users
innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00'
}, {
// tell screen readers not to automatically read the time as it changes
'aria-live': 'off'
});
el.appendChild(this.contentEl_);
return el;
};
/**
* Update remaining time display
*
* @method updateContent
*/
RemainingTimeDisplay.prototype.updateContent = function updateContent() {
if (this.player_.duration()) {
var localizedText = this.localize('Remaining Time');
var formattedTime = _utilsFormatTimeJs2['default'](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;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay);
exports['default'] = RemainingTimeDisplay;
module.exports = exports['default'];
},{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],84:[function(_dereq_,module,exports){
/**
* @file time-divider.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* 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
* @extends Component
* @class TimeDivider
*/
var TimeDivider = (function (_Component) {
_inherits(TimeDivider, _Component);
function TimeDivider() {
_classCallCheck(this, TimeDivider);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TimeDivider.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-time-control vjs-time-divider',
innerHTML: '<div><span>/</span></div>'
});
};
return TimeDivider;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('TimeDivider', TimeDivider);
exports['default'] = TimeDivider;
module.exports = exports['default'];
},{"../../component.js":58}],85:[function(_dereq_,module,exports){
/**
* @file volume-bar.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _sliderSliderJs = _dereq_('../../slider/slider.js');
var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs);
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('../../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
// Required children
var _volumeLevelJs = _dereq_('./volume-level.js');
var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs);
/**
* The bar that contains the volume level and can be clicked on to adjust the level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Slider
* @class VolumeBar
*/
var VolumeBar = (function (_Slider) {
_inherits(VolumeBar, _Slider);
function VolumeBar(player, options) {
_classCallCheck(this, VolumeBar);
_Slider.call(this, player, options);
this.on(player, 'volumechange', this.updateARIAAttributes);
player.ready(Fn.bind(this, this.updateARIAAttributes));
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeBar.prototype.createEl = function createEl() {
return _Slider.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-bar'
}, {
'aria-label': 'volume level'
});
};
/**
* Handle mouse move on volume bar
*
* @method handleMouseMove
*/
VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) {
if (this.player_.muted()) {
this.player_.muted(false);
}
this.player_.volume(this.calculateDistance(event));
};
/**
* Get percent of volume level
*
* @retun {Number} Volume level percent
* @method getPercent
*/
VolumeBar.prototype.getPercent = function getPercent() {
if (this.player_.muted()) {
return 0;
} else {
return this.player_.volume();
}
};
/**
* Increase volume level for keyboard users
*
* @method stepForward
*/
VolumeBar.prototype.stepForward = function stepForward() {
this.player_.volume(this.player_.volume() + 0.1);
};
/**
* Decrease volume level for keyboard users
*
* @method stepBack
*/
VolumeBar.prototype.stepBack = function stepBack() {
this.player_.volume(this.player_.volume() - 0.1);
};
/**
* Update ARIA accessibility attributes
*
* @method updateARIAAttributes
*/
VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() {
// Current value of volume bar as a percentage
var volume = (this.player_.volume() * 100).toFixed(2);
this.el_.setAttribute('aria-valuenow', volume);
this.el_.setAttribute('aria-valuetext', volume + '%');
};
return VolumeBar;
})(_sliderSliderJs2['default']);
VolumeBar.prototype.options_ = {
children: {
'volumeLevel': {}
},
'barName': 'volumeLevel'
};
VolumeBar.prototype.playerEvent = 'volumechange';
_componentJs2['default'].registerComponent('VolumeBar', VolumeBar);
exports['default'] = VolumeBar;
module.exports = exports['default'];
},{"../../component.js":58,"../../slider/slider.js":102,"../../utils/fn.js":120,"./volume-level.js":87}],86:[function(_dereq_,module,exports){
/**
* @file volume-control.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
// Required children
var _volumeBarJs = _dereq_('./volume-bar.js');
var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs);
/**
* The component for controlling the volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class VolumeControl
*/
var VolumeControl = (function (_Component) {
_inherits(VolumeControl, _Component);
function VolumeControl(player, options) {
_classCallCheck(this, VolumeControl);
_Component.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');
}
});
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeControl.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-control vjs-control'
});
};
return VolumeControl;
})(_componentJs2['default']);
VolumeControl.prototype.options_ = {
children: {
'volumeBar': {}
}
};
_componentJs2['default'].registerComponent('VolumeControl', VolumeControl);
exports['default'] = VolumeControl;
module.exports = exports['default'];
},{"../../component.js":58,"./volume-bar.js":85}],87:[function(_dereq_,module,exports){
/**
* @file volume-level.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
/**
* Shows volume level
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class VolumeLevel
*/
var VolumeLevel = (function (_Component) {
_inherits(VolumeLevel, _Component);
function VolumeLevel() {
_classCallCheck(this, VolumeLevel);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
VolumeLevel.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-volume-level',
innerHTML: '<span class="vjs-control-text"></span>'
});
};
return VolumeLevel;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel);
exports['default'] = VolumeLevel;
module.exports = exports['default'];
},{"../../component.js":58}],88:[function(_dereq_,module,exports){
/**
* @file volume-menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _menuMenuJs = _dereq_('../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _menuMenuButtonJs = _dereq_('../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _muteToggleJs = _dereq_('./mute-toggle.js');
var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs);
var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js');
var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs);
/**
* Button for volume menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends MenuButton
* @class VolumeMenuButton
*/
var VolumeMenuButton = (function (_MenuButton) {
_inherits(VolumeMenuButton, _MenuButton);
function VolumeMenuButton(player) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, VolumeMenuButton);
// Default to inline
if (options.inline === undefined) {
options.inline = true;
}
// If the vertical option isn't passed at all, default to true.
if (options.vertical === undefined) {
// If an inline volumeMenuButton is used, we should default to using
// a horizontal slider for obvious reasons.
if (options.inline) {
options.vertical = false;
} else {
options.vertical = true;
}
}
// The vertical option needs to be set on the volumeBar as well,
// since that will need to be passed along to the VolumeBar constructor
options.volumeBar = options.volumeBar || {};
options.volumeBar.vertical = !!options.vertical;
_MenuButton.call(this, player, options);
// Same listeners as MuteToggle
this.on(player, 'volumechange', this.volumeUpdate);
this.on(player, 'loadstart', this.volumeUpdate);
// hide mute toggle if the current tech doesn't support volume control
function updateVisibility() {
if (player.tech_ && player.tech_['featuresVolumeControl'] === false) {
this.addClass('vjs-hidden');
} else {
this.removeClass('vjs-hidden');
}
}
updateVisibility.call(this);
this.on(player, 'loadstart', updateVisibility);
this.on(this.volumeBar, ['slideractive', 'focus'], function () {
this.addClass('vjs-slider-active');
});
this.on(this.volumeBar, ['sliderinactive', 'blur'], function () {
this.removeClass('vjs-slider-active');
});
}
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() {
var orientationClass = '';
if (!!this.options_.vertical) {
orientationClass = 'vjs-volume-menu-button-vertical';
} else {
orientationClass = 'vjs-volume-menu-button-horizontal';
}
return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass;
};
/**
* Allow sub components to stack CSS class names
*
* @return {Menu} The volume menu button
* @method createMenu
*/
VolumeMenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuMenuJs2['default'](this.player_, {
contentElType: 'div'
});
var vb = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar);
menu.addChild(vb);
this.volumeBar = vb;
return menu;
};
/**
* Handle click on volume menu and calls super
*
* @method handleClick
*/
VolumeMenuButton.prototype.handleClick = function handleClick() {
_muteToggleJs2['default'].prototype.handleClick.call(this);
_MenuButton.prototype.handleClick.call(this);
};
return VolumeMenuButton;
})(_menuMenuButtonJs2['default']);
VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update;
VolumeMenuButton.prototype.controlText_ = 'Mute';
_componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton);
exports['default'] = VolumeMenuButton;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58,"../menu/menu-button.js":95,"../menu/menu.js":97,"./mute-toggle.js":62,"./volume-control/volume-bar.js":85}],89:[function(_dereq_,module,exports){
/**
* @file error-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
/**
* Display that an error has occurred making the video unplayable
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class ErrorDisplay
*/
var ErrorDisplay = (function (_Component) {
_inherits(ErrorDisplay, _Component);
function ErrorDisplay(player, options) {
_classCallCheck(this, ErrorDisplay);
_Component.call(this, player, options);
this.update();
this.on(player, 'error', this.update);
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
ErrorDisplay.prototype.createEl = function createEl() {
var el = _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-error-display'
});
this.contentEl_ = Dom.createEl('div');
el.appendChild(this.contentEl_);
return el;
};
/**
* Update the error message in localized language
*
* @method update
*/
ErrorDisplay.prototype.update = function update() {
if (this.player().error()) {
this.contentEl_.innerHTML = this.localize(this.player().error().message);
}
};
return ErrorDisplay;
})(_component2['default']);
_component2['default'].registerComponent('ErrorDisplay', ErrorDisplay);
exports['default'] = ErrorDisplay;
module.exports = exports['default'];
},{"./component":58,"./utils/dom.js":118}],90:[function(_dereq_,module,exports){
/**
* @file event-target.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var EventTarget = function EventTarget() {};
EventTarget.prototype.allowedEvents_ = {};
EventTarget.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;
};
EventTarget.prototype.addEventListener = EventTarget.prototype.on;
EventTarget.prototype.off = function (type, fn) {
Events.off(this, type, fn);
};
EventTarget.prototype.removeEventListener = EventTarget.prototype.off;
EventTarget.prototype.one = function (type, fn) {
Events.one(this, type, fn);
};
EventTarget.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()
EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger;
exports['default'] = EventTarget;
module.exports = exports['default'];
},{"./utils/events.js":119}],91:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _utilsLog = _dereq_('./utils/log');
var _utilsLog2 = _interopRequireDefault(_utilsLog);
/*
* @file extends.js
*
* 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
* ```js
* var Button = videojs.getComponent('Button');
* ```
* ```js
* 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.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var subClass = function subClass() {
superClass.apply(this, arguments);
};
var methods = {};
if (typeof subClassMethods === 'object') {
if (typeof subClassMethods.init === 'function') {
_utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.');
subClassMethods.constructor = subClassMethods.init;
}
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'];
},{"./utils/log":123}],92:[function(_dereq_,module,exports){
/**
* @file fullscreen-api.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* 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 _globalDocument2['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}],93:[function(_dereq_,module,exports){
/**
* @file loading-spinner.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
/* Loading Spinner
================================================================================ */
/**
* Loading spinner for waiting events
*
* @extends Component
* @class LoadingSpinner
*/
var LoadingSpinner = (function (_Component) {
_inherits(LoadingSpinner, _Component);
function LoadingSpinner() {
_classCallCheck(this, LoadingSpinner);
_Component.apply(this, arguments);
}
/**
* Create the component's DOM element
*
* @method createEl
*/
LoadingSpinner.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-loading-spinner'
});
};
return LoadingSpinner;
})(_component2['default']);
_component2['default'].registerComponent('LoadingSpinner', LoadingSpinner);
exports['default'] = LoadingSpinner;
module.exports = exports['default'];
},{"./component":58}],94:[function(_dereq_,module,exports){
/**
* @file media-error.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/*
* Custom MediaError to mimic the HTML5 MediaError
*
* @param {Number} code The media error code
*/
var MediaError = function MediaError(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
_objectAssign2['default'](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 {Array}
*/
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 media playback',
2: 'A network error caused the media download to fail part-way.',
3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.',
4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.',
5: 'The media 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'];
},{"object.assign":43}],95:[function(_dereq_,module,exports){
/**
* @file menu-button.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _menuJs = _dereq_('./menu.js');
var _menuJs2 = _interopRequireDefault(_menuJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
/**
* A button class with a popup menu
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MenuButton
*/
var MenuButton = (function (_Button) {
_inherits(MenuButton, _Button);
function MenuButton(player) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
_classCallCheck(this, MenuButton);
_Button.call(this, player, options);
this.update();
this.on('keydown', this.handleKeyPress);
this.el_.setAttribute('aria-haspopup', true);
this.el_.setAttribute('role', 'button');
}
/**
* Update menu
*
* @method update
*/
MenuButton.prototype.update = 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();
}
};
/**
* Create menu
*
* @return {Menu} The constructed menu
* @method createMenu
*/
MenuButton.prototype.createMenu = function createMenu() {
var menu = new _menuJs2['default'](this.player_);
// Add a title list item to the top
if (this.options_.title) {
menu.contentEl().appendChild(Dom.createEl('li', {
className: 'vjs-menu-title',
innerHTML: _utilsToTitleCaseJs2['default'](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;
};
/**
* Create the list of menu items. Specific to each subclass.
*
* @method createItems
*/
MenuButton.prototype.createItems = function createItems() {};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
MenuButton.prototype.createEl = function createEl() {
return _Button.prototype.createEl.call(this, 'div', {
className: this.buildCSSClass()
});
};
/**
* Allow sub components to stack CSS class names
*
* @return {String} The constructed class name
* @method buildCSSClass
*/
MenuButton.prototype.buildCSSClass = function buildCSSClass() {
var menuButtonClass = 'vjs-menu-button';
// If the inline option is passed, we want to use different styles altogether.
if (this.options_.inline === true) {
menuButtonClass += '-inline';
} else {
menuButtonClass += '-popup';
}
return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this);
};
/**
* 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.
*
* @method handleFocus
*/
MenuButton.prototype.handleFocus = function handleFocus() {};
/**
* Can't turn off list display that we turned
* on with focus, because list would go away.
*
* @method handleBlur
*/
MenuButton.prototype.handleBlur = function handleBlur() {};
/**
* 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.
* Allow sub components to stack CSS class names
*
* @method handleClick
*/
MenuButton.prototype.handleClick = function handleClick() {
this.one('mouseout', Fn.bind(this, function () {
this.menu.unlockShowing();
this.el_.blur();
}));
if (this.buttonPressed_) {
this.unpressButton();
} else {
this.pressButton();
}
};
/**
* Handle key press on menu
*
* @param {Object} Key press event
* @method handleKeyPress
*/
MenuButton.prototype.handleKeyPress = 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();
}
};
/**
* Makes changes based on button pressed
*
* @method pressButton
*/
MenuButton.prototype.pressButton = 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
}
};
/**
* Makes changes based on button unpressed
*
* @method unpressButton
*/
MenuButton.prototype.unpressButton = function unpressButton() {
this.buttonPressed_ = false;
this.menu.unlockShowing();
this.el_.setAttribute('aria-pressed', false);
};
return MenuButton;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('MenuButton', MenuButton);
exports['default'] = MenuButton;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58,"../utils/dom.js":118,"../utils/fn.js":120,"../utils/to-title-case.js":127,"./menu.js":97}],96:[function(_dereq_,module,exports){
/**
* @file menu-item.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('../button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* The component for a menu item. `<li>`
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class MenuItem
*/
var MenuItem = (function (_Button) {
_inherits(MenuItem, _Button);
function MenuItem(player, options) {
_classCallCheck(this, MenuItem);
_Button.call(this, player, options);
this.selected(options['selected']);
}
/**
* Create the component's DOM element
*
* @param {String=} type Desc
* @param {Object=} props Desc
* @return {Element}
* @method createEl
*/
MenuItem.prototype.createEl = function createEl(type, props, attrs) {
return _Button.prototype.createEl.call(this, 'li', _objectAssign2['default']({
className: 'vjs-menu-item',
innerHTML: this.localize(this.options_['label'])
}, props), attrs);
};
/**
* Handle a click on the menu item, and set it to selected
*
* @method handleClick
*/
MenuItem.prototype.handleClick = function handleClick() {
this.selected(true);
};
/**
* Set this menu item as selected or not
*
* @param {Boolean} selected
* @method selected
*/
MenuItem.prototype.selected = function selected(_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;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('MenuItem', MenuItem);
exports['default'] = MenuItem;
module.exports = exports['default'];
},{"../button.js":57,"../component.js":58,"object.assign":43}],97:[function(_dereq_,module,exports){
/**
* @file menu.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsEventsJs = _dereq_('../utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
/**
* The Menu component is used to build pop up menus, including subtitle and
* captions selection menus.
*
* @extends Component
* @class Menu
*/
var Menu = (function (_Component) {
_inherits(Menu, _Component);
function Menu() {
_classCallCheck(this, Menu);
_Component.apply(this, arguments);
}
/**
* Add a menu item to the menu
*
* @param {Object|String} component Component or component type to add
* @method addItem
*/
Menu.prototype.addItem = function addItem(component) {
this.addChild(component);
component.on('click', Fn.bind(this, function () {
this.unlockShowing();
}));
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Menu.prototype.createEl = function createEl() {
var contentElType = this.options_.contentElType || 'ul';
this.contentEl_ = Dom.createEl(contentElType, {
className: 'vjs-menu-content'
});
var el = _Component.prototype.createEl.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;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Menu', Menu);
exports['default'] = Menu;
module.exports = exports['default'];
},{"../component.js":58,"../utils/dom.js":118,"../utils/events.js":119,"../utils/fn.js":120}],98:[function(_dereq_,module,exports){
/**
* @file player.js
*/
// Subclasses Component
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('./utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js');
var _utilsBufferJs = _dereq_('./utils/buffer.js');
var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js');
var stylesheet = _interopRequireWildcard(_utilsStylesheetJs);
var _fullscreenApiJs = _dereq_('./fullscreen-api.js');
var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs);
var _mediaErrorJs = _dereq_('./media-error.js');
var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs);
var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple');
var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js');
var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs);
// Include required child components (importing also registers them)
var _techLoaderJs = _dereq_('./tech/loader.js');
var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs);
var _posterImageJs = _dereq_('./poster-image.js');
var _posterImageJs2 = _interopRequireDefault(_posterImageJs);
var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js');
var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs);
var _loadingSpinnerJs = _dereq_('./loading-spinner.js');
var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs);
var _bigPlayButtonJs = _dereq_('./big-play-button.js');
var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs);
var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js');
var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs);
var _errorDisplayJs = _dereq_('./error-display.js');
var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs);
var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js');
var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs);
// Require html5 tech, at least for disposing the original video tag
var _techHtml5Js = _dereq_('./tech/html5.js');
var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js);
/**
* 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')`.
*
* @param {Element} tag The original video tag used for configuring options
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class Player
*/
var Player = (function (_Component) {
_inherits(Player, _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) {
var _this = this;
_classCallCheck(this, Player);
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + Guid.newGUID();
// 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 = _objectAssign2['default'](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
_Component.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 && Dom.getElAttributes(tag);
// Update current language
this.language(this.options_.language);
// Update Supported Languages
if (options.languages) {
(function () {
// Normalise player option languages to lowercase
var languagesToLower = {};
Object.getOwnPropertyNames(options.languages).forEach(function (name) {
languagesToLower[name.toLowerCase()] = options.languages[name];
});
_this.languages_ = languagesToLower;
})();
} else {
this.languages_ = Player.prototype.options_.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();
// We also want to pass the original player options to each component and plugin
// as well so they don't need to reach back into the player for options later.
// We also need to do another copy of this.options_ so we don't end up with
// an infinite loop.
var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_);
// Load plugins
if (options.plugins) {
(function () {
var plugins = options.plugins;
Object.getOwnPropertyNames(plugins).forEach(function (name) {
if (typeof this[name] === 'function') {
this[name](plugins[name]);
} else {
_utilsLogJs2['default'].error('Unable to find plugin:', name);
}
}, _this);
})();
}
this.options_.playerOptions = playerOptionsCopy;
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 (browser.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_();
this.on('fullscreenchange', this.handleFullscreenChange_);
this.on('stageclick', this.handleStageClick_);
}
/*
* Global player list
*
* @type {Object}
*/
/**
* Destroys the video player and does any necessary cleanup
* ```js
* myPlayer.dispose();
* ```
* This is especially helpful if you are dynamically adding and removing videos
* to/from the DOM.
*
* @method dispose
*/
Player.prototype.dispose = function dispose() {
this.trigger('dispose');
// prevent dispose from being called twice
this.off('dispose');
if (this.styleEl_) {
this.styleEl_.parentNode.removeChild(this.styleEl_);
}
// 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();
}
_Component.prototype.dispose.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Player.prototype.createEl = function createEl() {
var el = this.el_ = _Component.prototype.createEl.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 = Dom.getElAttributes(tag);
Object.getOwnPropertyNames(attrs).forEach(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');
// Add a style element in the player that we'll use to set the width/height
// of the player in a way that's still overrideable by CSS, just like the
// video element
this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions');
var defaultsStyleEl = _globalDocument2['default'].querySelector('.vjs-styles-defaults');
var head = _globalDocument2['default'].querySelector('head');
head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild);
// Pass in the width/height/aspectRatio options which will update the style el
this.width(this.options_.width);
this.height(this.options_.height);
this.fluid(this.options_.fluid);
this.aspectRatio(this.options_.aspectRatio);
// insertElFirst 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);
}
Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup.
this.el_ = el;
return el;
};
/**
* Get/set player width
*
* @param {Number=} value Value for width
* @return {Number} Width when getting
* @method width
*/
Player.prototype.width = function width(value) {
return this.dimension('width', value);
};
/**
* Get/set player height
*
* @param {Number=} value Value for height
* @return {Number} Height when getting
* @method height
*/
Player.prototype.height = function height(value) {
return this.dimension('height', value);
};
/**
* Get/set dimension for player
*
* @param {String} dimension Either width or height
* @param {Number=} value Value for dimension
* @return {Component}
* @method dimension
*/
Player.prototype.dimension = function dimension(_dimension, value) {
var privDimension = _dimension + '_';
if (value === undefined) {
return this[privDimension] || 0;
}
if (value === '') {
// If an empty string is given, reset the dimension to be automatic
this[privDimension] = undefined;
} else {
var parsedVal = parseFloat(value);
if (isNaN(parsedVal)) {
_utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension);
return this;
}
this[privDimension] = parsedVal;
}
this.updateStyleEl_();
return this;
};
/**
* Add/remove the vjs-fluid class
*
* @param {Boolean} bool Value of true adds the class, value of false removes the class
* @method fluid
*/
Player.prototype.fluid = function fluid(bool) {
if (bool === undefined) {
return !!this.fluid_;
}
this.fluid_ = !!bool;
if (bool) {
this.addClass('vjs-fluid');
} else {
this.removeClass('vjs-fluid');
}
};
/**
* Get/Set the aspect ratio
*
* @param {String=} ratio Aspect ratio for player
* @return aspectRatio
* @method aspectRatio
*/
Player.prototype.aspectRatio = function aspectRatio(ratio) {
if (ratio === undefined) {
return this.aspectRatio_;
}
// Check for width:height format
if (!/^\d+\:\d+$/.test(ratio)) {
throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.');
}
this.aspectRatio_ = ratio;
// We're assuming if you set an aspect ratio you want fluid mode,
// because in fixed mode you could calculate width and height yourself.
this.fluid(true);
this.updateStyleEl_();
};
/**
* Update styles of the player element (height, width and aspect ratio)
*
* @method updateStyleEl_
*/
Player.prototype.updateStyleEl_ = function updateStyleEl_() {
var width = undefined;
var height = undefined;
var aspectRatio = undefined;
// The aspect ratio is either used directly or to calculate width and height.
if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') {
// Use any aspectRatio that's been specifically set
aspectRatio = this.aspectRatio_;
} else if (this.videoWidth()) {
// Otherwise try to get the aspect ratio from the video metadata
aspectRatio = this.videoWidth() + ':' + this.videoHeight();
} else {
// Or use a default. The video element's is 2:1, but 16:9 is more common.
aspectRatio = '16:9';
}
// Get the ratio as a decimal we can use to calculate dimensions
var ratioParts = aspectRatio.split(':');
var ratioMultiplier = ratioParts[1] / ratioParts[0];
if (this.width_ !== undefined) {
// Use any width that's been specifically set
width = this.width_;
} else if (this.height_ !== undefined) {
// Or calulate the width from the aspect ratio if a height has been set
width = this.height_ / ratioMultiplier;
} else {
// Or use the video's metadata, or use the video el's default of 300
width = this.videoWidth() || 300;
}
if (this.height_ !== undefined) {
// Use any height that's been specifically set
height = this.height_;
} else {
// Otherwise calculate the height from the ratio and the width
height = width * ratioMultiplier;
}
var idClass = this.id() + '-dimensions';
// Ensure the right class is still on the player for the style element
this.addClass(idClass);
stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n ');
};
/**
* 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.
*
* @param {String} techName Name of the playback technology
* @param {String} source Video source
* @method loadTech_
* @private
*/
Player.prototype.loadTech_ = 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) {
_componentJs2['default'].getComponent('Html5').disposeMediaElement(this.tag);
this.tag.player = null;
this.tag = null;
}
this.techName_ = techName;
// Turn off API access because we're loading a new tech that might load asynchronously
this.isReady_ = false;
// Grab tech-specific options from player options and add source and parent element to use.
var techOptions = _objectAssign2['default']({
'nativeControlsForTouch': this.options_.nativeControlsForTouch,
'source': source,
'playerId': this.id(),
'techId': this.id() + '_' + techName + '_api',
'textTracks': this.textTracks_,
'autoplay': this.options_.autoplay,
'preload': this.options_.preload,
'loop': this.options_.loop,
'muted': this.options_.muted,
'poster': this.poster(),
'language': this.language(),
'vtt.js': this.options_['vtt.js']
}, this.options_[techName.toLowerCase()]);
if (this.tag) {
techOptions.tag = this.tag;
}
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 = _componentJs2['default'].getComponent(techName);
this.tech_ = new techComponent(techOptions);
// player.triggerReady is always async, so don't need this to be async
this.tech_.ready(Fn.bind(this, this.handleTechReady_), true);
_tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_);
// Listen to all HTML5-defined events and trigger them on the player
this.on(this.tech_, 'loadstart', this.handleTechLoadStart_);
this.on(this.tech_, 'waiting', this.handleTechWaiting_);
this.on(this.tech_, 'canplay', this.handleTechCanPlay_);
this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_);
this.on(this.tech_, 'playing', this.handleTechPlaying_);
this.on(this.tech_, 'ended', this.handleTechEnded_);
this.on(this.tech_, 'seeking', this.handleTechSeeking_);
this.on(this.tech_, 'seeked', this.handleTechSeeked_);
this.on(this.tech_, 'play', this.handleTechPlay_);
this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_);
this.on(this.tech_, 'pause', this.handleTechPause_);
this.on(this.tech_, 'progress', this.handleTechProgress_);
this.on(this.tech_, 'durationchange', this.handleTechDurationChange_);
this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_);
this.on(this.tech_, 'error', this.handleTechError_);
this.on(this.tech_, 'suspend', this.handleTechSuspend_);
this.on(this.tech_, 'abort', this.handleTechAbort_);
this.on(this.tech_, 'emptied', this.handleTechEmptied_);
this.on(this.tech_, 'stalled', this.handleTechStalled_);
this.on(this.tech_, 'loadedmetadata', this.handleTechLoadedMetaData_);
this.on(this.tech_, 'loadeddata', this.handleTechLoadedData_);
this.on(this.tech_, 'timeupdate', this.handleTechTimeUpdate_);
this.on(this.tech_, 'ratechange', this.handleTechRateChange_);
this.on(this.tech_, 'volumechange', this.handleTechVolumeChange_);
this.on(this.tech_, 'texttrackchange', this.handleTechTextTrackChange_);
this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_);
this.usingNativeControls(this.techGet_('controls'));
if (this.controls() && !this.usingNativeControls()) {
this.addTechControlsListeners_();
}
// Add the tech element in the DOM if it was not already there
// Make sure to not insert the original video element if using Html5
if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) {
Dom.insertElFirst(this.tech_.el(), this.el());
}
// Get rid of the original video tag reference after the first tech is loaded
if (this.tag) {
this.tag.player = null;
this.tag = null;
}
};
/**
* Unload playback technology
*
* @method unloadTech_
* @private
*/
Player.prototype.unloadTech_ = function unloadTech_() {
// Save the current text tracks so that we can reuse the same text tracks with the next tech
this.textTracks_ = this.textTracks();
this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this);
this.isReady_ = false;
this.tech_.dispose();
this.tech_ = false;
};
/**
* 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
*
* @private
* @method addTechControlsListeners_
*/
Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() {
// Make sure to remove all the previous listeners in case we are called multiple times.
this.removeTechControlsListeners_();
// 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(this.tech_, 'mousedown', this.handleTechClick_);
// 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(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.on(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.on(this.tech_, 'touchend', this.handleTechTouchEnd_);
// The tap listener needs to come after the touchend listener because the tap
// listener cancels out any reportedUserActivity when setting userActive(false)
this.on(this.tech_, 'tap', this.handleTechTap_);
};
/**
* Remove the listeners used for click and tap controls. This is needed for
* toggling to controls disabled, where a tap/touch should do nothing.
*
* @method removeTechControlsListeners_
* @private
*/
Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() {
// We don't want to just use `this.off()` because there might be other needed
// listeners added by techs that extend this.
this.off(this.tech_, 'tap', this.handleTechTap_);
this.off(this.tech_, 'touchstart', this.handleTechTouchStart_);
this.off(this.tech_, 'touchmove', this.handleTechTouchMove_);
this.off(this.tech_, 'touchend', this.handleTechTouchEnd_);
this.off(this.tech_, 'mousedown', this.handleTechClick_);
};
/**
* Player waits for the tech to be ready
*
* @method handleTechReady_
* @private
*/
Player.prototype.handleTechReady_ = function handleTechReady_() {
this.triggerReady();
// Keep the same volume as before
if (this.cache_.volume) {
this.techCall_('setVolume', this.cache_.volume);
}
// Update the duration if available
this.handleTechDurationChange_();
// 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
if (this.tag && this.options_.autoplay && this.paused()) {
delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16.
this.play();
}
};
/**
* Fired when the user agent begins looking for media data
*
* @private
* @method handleTechLoadStart_
*/
Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() {
// 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('loadstart');
this.trigger('firstplay');
} else {
// reset the hasStarted state
this.hasStarted(false);
this.trigger('loadstart');
}
};
/**
* Add/remove the vjs-has-started class
*
* @param {Boolean} hasStarted The value of true adds the class the value of false remove the class
* @return {Boolean} Boolean value if has started
* @private
* @method hasStarted
*/
Player.prototype.hasStarted = function hasStarted(_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_;
};
/**
* Fired whenever the media begins or resumes playback
*
* @private
* @method handleTechPlay_
*/
Player.prototype.handleTechPlay_ = function handleTechPlay_() {
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);
this.trigger('play');
};
/**
* Fired whenever the media begins waiting
*
* @private
* @method handleTechWaiting_
*/
Player.prototype.handleTechWaiting_ = function handleTechWaiting_() {
this.addClass('vjs-waiting');
this.trigger('waiting');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechCanPlay_
*/
Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() {
this.removeClass('vjs-waiting');
this.trigger('canplay');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechCanPlayThrough_
*/
Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() {
this.removeClass('vjs-waiting');
this.trigger('canplaythrough');
};
/**
* A handler for events that signal that waiting has ended
* which is not consistent between browsers. See #1351
*
* @private
* @method handleTechPlaying_
*/
Player.prototype.handleTechPlaying_ = function handleTechPlaying_() {
this.removeClass('vjs-waiting');
this.trigger('playing');
};
/**
* Fired whenever the player is jumping to a new time
*
* @private
* @method handleTechSeeking_
*/
Player.prototype.handleTechSeeking_ = function handleTechSeeking_() {
this.addClass('vjs-seeking');
this.trigger('seeking');
};
/**
* Fired when the player has finished jumping to a new time
*
* @private
* @method handleTechSeeked_
*/
Player.prototype.handleTechSeeked_ = function handleTechSeeked_() {
this.removeClass('vjs-seeking');
this.trigger('seeked');
};
/**
* 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.
*
* @private
* @method handleTechFirstPlay_
*/
Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() {
//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');
this.trigger('firstplay');
};
/**
* Fired whenever the media has been paused
*
* @private
* @method handleTechPause_
*/
Player.prototype.handleTechPause_ = function handleTechPause_() {
this.removeClass('vjs-playing');
this.addClass('vjs-paused');
this.trigger('pause');
};
/**
* Fired while the user agent is downloading media data
*
* @private
* @method handleTechProgress_
*/
Player.prototype.handleTechProgress_ = function handleTechProgress_() {
this.trigger('progress');
};
/**
* Fired when the end of the media resource is reached (currentTime == duration)
*
* @private
* @method handleTechEnded_
*/
Player.prototype.handleTechEnded_ = function handleTechEnded_() {
this.addClass('vjs-ended');
if (this.options_.loop) {
this.currentTime(0);
this.play();
} else if (!this.paused()) {
this.pause();
}
this.trigger('ended');
};
/**
* Fired when the duration of the media resource is first known or changed
*
* @private
* @method handleTechDurationChange_
*/
Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() {
this.duration(this.techGet_('duration'));
};
/**
* Handle a click on the media element to play/pause
*
* @param {Object=} event Event object
* @private
* @method handleTechClick_
*/
Player.prototype.handleTechClick_ = function handleTechClick_(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.controls()) {
if (this.paused()) {
this.play();
} else {
this.pause();
}
}
};
/**
* Handle a tap on the media element. It will toggle the user
* activity state, which hides and shows the controls.
*
* @private
* @method handleTechTap_
*/
Player.prototype.handleTechTap_ = function handleTechTap_() {
this.userActive(!this.userActive());
};
/**
* Handle touch to start
*
* @private
* @method handleTechTouchStart_
*/
Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() {
this.userWasActive = this.userActive();
};
/**
* Handle touch to move
*
* @private
* @method handleTechTouchMove_
*/
Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() {
if (this.userWasActive) {
this.reportUserActivity();
}
};
/**
* Handle touch to end
*
* @private
* @method handleTechTouchEnd_
*/
Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) {
// Stop the mouse events from also happening
event.preventDefault();
};
/**
* Fired when the player switches in or out of fullscreen mode
*
* @private
* @method handleFullscreenChange_
*/
Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() {
if (this.isFullscreen()) {
this.addClass('vjs-fullscreen');
} else {
this.removeClass('vjs-fullscreen');
}
};
/**
* native click events on the SWF aren't triggered on IE11, Win8.1RT
* use stageclick events triggered from inside the SWF instead
*
* @private
* @method handleStageClick_
*/
Player.prototype.handleStageClick_ = function handleStageClick_() {
this.reportUserActivity();
};
/**
* Handle Tech Fullscreen Change
*
* @private
* @method handleTechFullscreenChange_
*/
Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) {
if (data) {
this.isFullscreen(data.isFullscreen);
}
this.trigger('fullscreenchange');
};
/**
* Fires when an error occurred during the loading of an audio/video
*
* @private
* @method handleTechError_
*/
Player.prototype.handleTechError_ = function handleTechError_() {
var error = this.tech_.error();
this.error(error && error.code);
};
/**
* Fires when the browser is intentionally not getting media data
*
* @private
* @method handleTechSuspend_
*/
Player.prototype.handleTechSuspend_ = function handleTechSuspend_() {
this.trigger('suspend');
};
/**
* Fires when the loading of an audio/video is aborted
*
* @private
* @method handleTechAbort_
*/
Player.prototype.handleTechAbort_ = function handleTechAbort_() {
this.trigger('abort');
};
/**
* Fires when the current playlist is empty
*
* @private
* @method handleTechEmptied_
*/
Player.prototype.handleTechEmptied_ = function handleTechEmptied_() {
this.trigger('emptied');
};
/**
* Fires when the browser is trying to get media data, but data is not available
*
* @private
* @method handleTechStalled_
*/
Player.prototype.handleTechStalled_ = function handleTechStalled_() {
this.trigger('stalled');
};
/**
* Fires when the browser has loaded meta data for the audio/video
*
* @private
* @method handleTechLoadedMetaData_
*/
Player.prototype.handleTechLoadedMetaData_ = function handleTechLoadedMetaData_() {
this.trigger('loadedmetadata');
};
/**
* Fires when the browser has loaded the current frame of the audio/video
*
* @private
* @method handleTechLoadedData_
*/
Player.prototype.handleTechLoadedData_ = function handleTechLoadedData_() {
this.trigger('loadeddata');
};
/**
* Fires when the current playback position has changed
*
* @private
* @method handleTechTimeUpdate_
*/
Player.prototype.handleTechTimeUpdate_ = function handleTechTimeUpdate_() {
this.trigger('timeupdate');
};
/**
* Fires when the playing speed of the audio/video is changed
*
* @private
* @method handleTechRateChange_
*/
Player.prototype.handleTechRateChange_ = function handleTechRateChange_() {
this.trigger('ratechange');
};
/**
* Fires when the volume has been changed
*
* @private
* @method handleTechVolumeChange_
*/
Player.prototype.handleTechVolumeChange_ = function handleTechVolumeChange_() {
this.trigger('volumechange');
};
/**
* Fires when the text track has been changed
*
* @private
* @method handleTechTextTrackChange_
*/
Player.prototype.handleTechTextTrackChange_ = function handleTechTextTrackChange_() {
this.trigger('texttrackchange');
};
/**
* Get object for cached values.
*
* @return {Object}
* @method getCache
*/
Player.prototype.getCache = function getCache() {
return this.cache_;
};
/**
* Pass values to the playback tech
*
* @param {String=} method Method
* @param {Object=} arg Argument
* @private
* @method techCall_
*/
Player.prototype.techCall_ = 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);
}, true);
// Otherwise call method now
} else {
try {
this.tech_[method](arg);
} catch (e) {
_utilsLogJs2['default'](e);
throw e;
}
}
};
/**
* Get calls can't wait for the tech, and sometimes don't need to.
*
* @param {String} method Tech method
* @return {Method}
* @private
* @method techGet_
*/
Player.prototype.techGet_ = 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) {
_utilsLogJs2['default']('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') {
_utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e);
this.tech_.isReady_ = false;
} else {
_utilsLogJs2['default'](e);
}
}
throw e;
}
}
return;
};
/**
* start media playback
* ```js
* myPlayer.play();
* ```
*
* @return {Player} self
* @method play
*/
Player.prototype.play = function play() {
this.techCall_('play');
return this;
};
/**
* Pause the video playback
* ```js
* myPlayer.pause();
* ```
*
* @return {Player} self
* @method pause
*/
Player.prototype.pause = function pause() {
this.techCall_('pause');
return this;
};
/**
* Check if the player is paused
* ```js
* var isPaused = myPlayer.paused();
* var isPlaying = !myPlayer.paused();
* ```
*
* @return {Boolean} false if the media is currently playing, or true otherwise
* @method paused
*/
Player.prototype.paused = function paused() {
// The initial state of paused should be true (in Safari it's actually false)
return this.techGet_('paused') === false ? false : true;
};
/**
* 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
* @method scrubbing
*/
Player.prototype.scrubbing = 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_;
};
/**
* Get or set the current time (in seconds)
* ```js
* // 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
* @method currentTime
*/
Player.prototype.currentTime = 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;
};
/**
* Get the length in time of the video in seconds
* ```js
* 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.
*
* @param {Number} seconds Duration when setting
* @return {Number} The duration of the video in seconds when getting
* @method duration
*/
Player.prototype.duration = function duration(seconds) {
if (seconds === undefined) {
return this.cache_.duration || 0;
}
seconds = parseFloat(seconds) || 0;
// Standardize on Inifity for signaling video is live
if (seconds < 0) {
seconds = Infinity;
}
if (seconds !== this.cache_.duration) {
// Cache the last set value for optimized scrubbing (esp. Flash)
this.cache_.duration = seconds;
if (seconds === Infinity) {
this.addClass('vjs-live');
} else {
this.removeClass('vjs-live');
}
this.trigger('durationchange');
}
return this;
};
/**
* Calculates how much time is left.
* ```js
* var timeLeft = myPlayer.remainingTime();
* ```
* Not a native video element function, but useful
*
* @return {Number} The time remaining in seconds
* @method remainingTime
*/
Player.prototype.remainingTime = function remainingTime() {
return this.duration() - this.currentTime();
};
// 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.
* ```js
* // 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)
* @method buffered
*/
Player.prototype.buffered = function buffered() {
var buffered = this.techGet_('buffered');
if (!buffered || !buffered.length) {
buffered = _utilsTimeRangesJs.createTimeRange(0, 0);
}
return buffered;
};
/**
* Get the percent (as a decimal) of the video that's been downloaded
* ```js
* 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
* @method bufferedPercent
*/
Player.prototype.bufferedPercent = function bufferedPercent() {
return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration());
};
/**
* 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
* @method bufferedEnd
*/
Player.prototype.bufferedEnd = function bufferedEnd() {
var buffered = this.buffered(),
duration = this.duration(),
end = buffered.end(buffered.length - 1);
if (end > duration) {
end = duration;
}
return end;
};
/**
* Get or set the current volume of the media
* ```js
* // 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
* @method volume
*/
Player.prototype.volume = 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);
return this;
}
// Default to 1 when returning current volume.
vol = parseFloat(this.techGet_('volume'));
return isNaN(vol) ? 1 : vol;
};
/**
* Get the current muted state, or turn mute on or off
* ```js
* // 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
* @method muted
*/
Player.prototype.muted = function muted(_muted) {
if (_muted !== undefined) {
this.techCall_('setMuted', _muted);
return this;
}
return this.techGet_('muted') || false; // Default to false
};
// Check if current tech can support native fullscreen
// (e.g. with built in controls like iOS, so not our flash swf)
/**
* Check to see if fullscreen is supported
*
* @return {Boolean}
* @method supportsFullScreen
*/
Player.prototype.supportsFullScreen = function supportsFullScreen() {
return this.techGet_('supportsFullScreen') || false;
};
/**
* Check if the player is in fullscreen mode
* ```js
* // 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 when getting
* @return {Player} self when setting
* @method isFullscreen
*/
Player.prototype.isFullscreen = function isFullscreen(isFS) {
if (isFS !== undefined) {
this.isFullscreen_ = !!isFS;
return this;
}
return !!this.isFullscreen_;
};
/**
* Increase the size of the video to full screen
* ```js
* 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
* @method requestFullscreen
*/
Player.prototype.requestFullscreen = function requestFullscreen() {
var fsApi = _fullscreenApiJs2['default'];
this.isFullscreen(true);
if (fsApi.requestFullscreen) {
// 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(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) {
this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]);
// If cancelling fullscreen, remove event listener.
if (this.isFullscreen() === false) {
Events.off(_globalDocument2['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;
};
/**
* Return the video to its normal size after having been in full screen mode
* ```js
* myPlayer.exitFullscreen();
* ```
*
* @return {Player} self
* @method exitFullscreen
*/
Player.prototype.exitFullscreen = function exitFullscreen() {
var fsApi = _fullscreenApiJs2['default'];
this.isFullscreen(false);
// Check for browser element fullscreen support
if (fsApi.requestFullscreen) {
_globalDocument2['default'][fsApi.exitFullscreen]();
} else if (this.tech_.supportsFullScreen()) {
this.techCall_('exitFullScreen');
} else {
this.exitFullWindow();
this.trigger('fullscreenchange');
}
return this;
};
/**
* When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us.
*
* @method enterFullWindow
*/
Player.prototype.enterFullWindow = function enterFullWindow() {
this.isFullWindow = true;
// Storing original doc overflow value to return to when fullscreen is off
this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow;
// Add listener for esc key to exit fullscreen
Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey));
// Hide any scroll bars
_globalDocument2['default'].documentElement.style.overflow = 'hidden';
// Apply fullscreen styles
Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window');
this.trigger('enterFullWindow');
};
/**
* Check for call to either exit full window or full screen on ESC key
*
* @param {String} event Event to check for key press
* @method fullWindowOnEscKey
*/
Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) {
if (event.keyCode === 27) {
if (this.isFullscreen() === true) {
this.exitFullscreen();
} else {
this.exitFullWindow();
}
}
};
/**
* Exit full window
*
* @method exitFullWindow
*/
Player.prototype.exitFullWindow = function exitFullWindow() {
this.isFullWindow = false;
Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey);
// Unhide scroll bars.
_globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow;
// Remove fullscreen styles
Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window');
// Resize the box, controller, and poster to original sizes
// this.positionAll();
this.trigger('exitFullWindow');
};
/**
* Select source based on tech order
*
* @param {Array} sources The sources for a media asset
* @return {Object|Boolean} Object of source and tech order, otherwise false
* @method selectSource
*/
Player.prototype.selectSource = 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 = _utilsToTitleCaseJs2['default'](j[i]);
var tech = _componentJs2['default'].getComponent(techName);
// Check if the current tech is defined before continuing
if (!tech) {
_utilsLogJs2['default'].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;
};
/**
* 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.
* ```js
* 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.
* ```js
* 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.
* ```js
* 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
* @method src
*/
Player.prototype.src = function src(source) {
if (source === undefined) {
return this.techGet_('src');
}
var currentTech = _componentJs2['default'].getComponent(this.techName_);
// case: Array of source objects to choose from and pick the best to play
if (Array.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();
}
// Set the source synchronously if possible (#2326)
}, true);
}
}
return this;
};
/**
* Handle an array of source objects
*
* @param {Array} sources Array of source objects
* @private
* @method sourceList_
*/
Player.prototype.sourceList_ = 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();
}
};
/**
* Begin loading the src data.
*
* @return {Player} Returns the player
* @method load
*/
Player.prototype.load = function load() {
this.techCall_('load');
return this;
};
/**
* 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
* @method currentSrc
*/
Player.prototype.currentSrc = function currentSrc() {
return this.techGet_('currentSrc') || this.cache_.src || '';
};
/**
* 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
* @method currentType
*/
Player.prototype.currentType = function currentType() {
return this.currentType_ || '';
};
/**
* Get or set the preload attribute
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The preload attribute value when getting
* @return {Player} Returns the player when setting
* @method preload
*/
Player.prototype.preload = function preload(value) {
if (value !== undefined) {
this.techCall_('setPreload', value);
this.options_.preload = value;
return this;
}
return this.techGet_('preload');
};
/**
* Get or set the autoplay attribute.
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The autoplay attribute value when getting
* @return {Player} Returns the player when setting
* @method autoplay
*/
Player.prototype.autoplay = function autoplay(value) {
if (value !== undefined) {
this.techCall_('setAutoplay', value);
this.options_.autoplay = value;
return this;
}
return this.techGet_('autoplay', value);
};
/**
* Get or set the loop attribute on the video element.
*
* @param {Boolean} value Boolean to determine if preload should be used
* @return {String} The loop attribute value when getting
* @return {Player} Returns the player when setting
* @method loop
*/
Player.prototype.loop = function loop(value) {
if (value !== undefined) {
this.techCall_('setLoop', value);
this.options_['loop'] = value;
return this;
}
return this.techGet_('loop');
};
/**
* get or set the poster image source url
* ##### EXAMPLE:
* ```js
* // get
* var currentPoster = myPlayer.poster();
* // set
* 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
* @method poster
*/
Player.prototype.poster = 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;
};
/**
* Get or set whether or not the controls are showing.
*
* @param {Boolean} bool Set controls to showing or not
* @return {Boolean} Controls are showing
* @method controls
*/
Player.prototype.controls = 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 (this.usingNativeControls()) {
this.techCall_('setControls', bool);
}
if (bool) {
this.removeClass('vjs-controls-disabled');
this.addClass('vjs-controls-enabled');
this.trigger('controlsenabled');
if (!this.usingNativeControls()) {
this.addTechControlsListeners_();
}
} else {
this.removeClass('vjs-controls-enabled');
this.addClass('vjs-controls-disabled');
this.trigger('controlsdisabled');
if (!this.usingNativeControls()) {
this.removeTechControlsListeners_();
}
}
}
return this;
}
return !!this.controls_;
};
/**
* 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
* @method usingNativeControls
*/
Player.prototype.usingNativeControls = 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_;
};
/**
* 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
* @method error
*/
Player.prototype.error = 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 _mediaErrorJs2['default']) {
this.error_ = err;
} else {
this.error_ = new _mediaErrorJs2['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
_utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_);
return this;
};
/**
* 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.
* @method ended
*/
Player.prototype.ended = function ended() {
return this.techGet_('ended');
};
/**
* 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.
* @method seeking
*/
Player.prototype.seeking = function seeking() {
return this.techGet_('seeking');
};
/**
* Returns the TimeRanges of the media that are currently available
* for seeking to.
*
* @return {TimeRanges} the seekable intervals of the media timeline
* @method seekable
*/
Player.prototype.seekable = function seekable() {
return this.techGet_('seekable');
};
/**
* Report user activity
*
* @param {Object} event Event object
* @method reportUserActivity
*/
Player.prototype.reportUserActivity = function reportUserActivity(event) {
this.userActivity_ = true;
};
/**
* Get/set if user is active
*
* @param {Boolean} bool Value when setting
* @return {Boolean} Value if user is active user when getting
* @method userActive
*/
Player.prototype.userActive = 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_;
};
/**
* Listen for user activity based on timeout value
*
* @private
* @method listenForUserActivity_
*/
Player.prototype.listenForUserActivity_ = function listenForUserActivity_() {
var mouseInProgress = undefined,
lastMoveX = undefined,
lastMoveY = undefined;
var handleActivity = Fn.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 inactivityTimeout = undefined;
var activityCheck = this.setInterval(function () {
// 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);
};
/**
* 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.
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate
*
* @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
* @method playbackRate
*/
Player.prototype.playbackRate = 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.0;
}
};
/**
* 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
* @method isAudio
*/
Player.prototype.isAudio = function isAudio(bool) {
if (bool !== undefined) {
this.isAudio_ = !!bool;
return this;
}
return !!this.isAudio_;
};
/**
* 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.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states
* @return {Number} the current network activity state
* @method networkState
*/
Player.prototype.networkState = function networkState() {
return this.techGet_('networkState');
};
/**
* 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.
*
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate
* @return {Number} the current playback rendering state
* @method readyState
*/
Player.prototype.readyState = function readyState() {
return this.techGet_('readyState');
};
/*
* 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
* @method textTracks
*/
Player.prototype.textTracks = 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']();
};
/**
* Get an array of remote text tracks
*
* @return {Array}
* @method remoteTextTracks
*/
Player.prototype.remoteTextTracks = function remoteTextTracks() {
return this.tech_ && this.tech_['remoteTextTracks']();
};
/**
* 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
* @method addTextTrack
*/
Player.prototype.addTextTrack = function addTextTrack(kind, label, language) {
return this.tech_ && this.tech_['addTextTrack'](kind, label, language);
};
/**
* Add a remote text track
*
* @param {Object} options Options for remote text track
* @method addRemoteTextTrack
*/
Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) {
return this.tech_ && this.tech_['addRemoteTextTrack'](options);
};
/**
* Remove a remote text track
*
* @param {Object} track Remote text track to remove
* @method removeRemoteTextTrack
*/
Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
this.tech_ && this.tech_['removeRemoteTextTrack'](track);
};
/**
* Get video width
*
* @return {Number} Video width
* @method videoWidth
*/
Player.prototype.videoWidth = function videoWidth() {
return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0;
};
/**
* Get video height
*
* @return {Number} Video height
* @method videoHeight
*/
Player.prototype.videoHeight = function videoHeight() {
return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0;
};
// Methods to add support for
// initialTime: function(){ return this.techCall_('initialTime'); },
// startOffsetTime: function(){ return this.techCall_('startOffsetTime'); },
// played: function(){ return this.techCall_('played'); },
// videoTracks: function(){ return this.techCall_('videoTracks'); },
// audioTracks: function(){ return this.techCall_('audioTracks'); },
// defaultPlaybackRate: function(){ return this.techCall_('defaultPlaybackRate'); },
// defaultMuted: function(){ return this.techCall_('defaultMuted'); }
/**
* The player's language code
* NOTE: The language should be set in the player options if you want the
* the controls to be built with a specific language. Changing the lanugage
* later will not update controls text.
*
* @param {String} code The locale string
* @return {String} The locale string when getting
* @return {Player} self when setting
* @method language
*/
Player.prototype.language = function language(code) {
if (code === undefined) {
return this.language_;
}
this.language_ = ('' + code).toLowerCase();
return this;
};
/**
* Get the player's language dictionary
* Merge every time, because a newly added plugin might call videojs.addLanguage() at any time
* Languages specified directly in the player options have precedence
*
* @return {Array} Array of languages
* @method languages
*/
Player.prototype.languages = function languages() {
return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_);
};
/**
* Converts track info to JSON
*
* @return {Object} JSON object of options
* @method toJSON
*/
Player.prototype.toJSON = function toJSON() {
var options = _utilsMergeOptionsJs2['default'](this.options_);
var tracks = options.tracks;
options.tracks = [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
// deep merge tracks and null out player so no circular references
track = _utilsMergeOptionsJs2['default'](track);
track.player = undefined;
options.tracks[i] = track;
}
return options;
};
/**
* Gets tag settings
*
* @param {Element} tag The player tag
* @return {Array} An array of sources and track objects
* @static
* @method getTagSettings
*/
Player.getTagSettings = function getTagSettings(tag) {
var baseOptions = {
'sources': [],
'tracks': []
};
var tagOptions = Dom.getElAttributes(tag);
var dataSetup = tagOptions['data-setup'];
// Check if data-setup attr exists.
if (dataSetup !== null) {
// Parse options JSON
var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}');
var err = _safeParseTuple[0];
var data = _safeParseTuple[1];
if (err) {
_utilsLogJs2['default'].error(err);
}
_objectAssign2['default'](tagOptions, data);
}
_objectAssign2['default'](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(Dom.getElAttributes(child));
} else if (childName === 'track') {
baseOptions.tracks.push(Dom.getElAttributes(child));
}
}
}
return baseOptions;
};
return Player;
})(_componentJs2['default']);
Player.players = {};
var navigator = _globalWindow2['default'].navigator;
/*
* Player instance options, surfaced using options
* options = Player.prototype.options_
* Make changes in options, not here.
*
* @type {Object}
* @private
*/
Player.prototype.options_ = {
// Default order of fallback technology
techOrder: ['html5', 'flash'],
// techOrder: ['flash','html5'],
html5: {},
flash: {},
// defaultVolume: 0.85,
defaultVolume: 0.00, // 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: _globalDocument2['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.'
};
/**
* 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 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 = _globalDocument2['default'].createElement('i');
// Note: We don't actually use flexBasis (or flexOrder), but it's one of the more
// common flex features that we can rely on when checking for flex support.
return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */;
};
_componentJs2['default'].registerComponent('Player', Player);
exports['default'] = Player;
module.exports = exports['default'];
// If empty string, make it a parsable json object.
},{"./big-play-button.js":56,"./component.js":58,"./control-bar/control-bar.js":59,"./error-display.js":89,"./fullscreen-api.js":92,"./loading-spinner.js":93,"./media-error.js":94,"./poster-image.js":100,"./tech/html5.js":105,"./tech/loader.js":106,"./tracks/text-track-display.js":109,"./tracks/text-track-list-converter.js":111,"./tracks/text-track-settings.js":113,"./utils/browser.js":115,"./utils/buffer.js":116,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/guid.js":122,"./utils/log.js":123,"./utils/merge-options.js":124,"./utils/stylesheet.js":125,"./utils/time-ranges.js":126,"./utils/to-title-case.js":127,"global/document":1,"global/window":2,"object.assign":43,"safe-json-parse/tuple":48}],99:[function(_dereq_,module,exports){
/**
* @file plugins.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _playerJs = _dereq_('./player.js');
var _playerJs2 = _interopRequireDefault(_playerJs);
/**
* 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
* @method plugin
*/
var plugin = function plugin(name, init) {
_playerJs2['default'].prototype[name] = init;
};
exports['default'] = plugin;
module.exports = exports['default'];
},{"./player.js":98}],100:[function(_dereq_,module,exports){
/**
* @file poster-image.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _buttonJs = _dereq_('./button.js');
var _buttonJs2 = _interopRequireDefault(_buttonJs);
var _componentJs = _dereq_('./component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
/**
* The component that handles showing the poster image.
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Button
* @class PosterImage
*/
var PosterImage = (function (_Button) {
_inherits(PosterImage, _Button);
function PosterImage(player, options) {
_classCallCheck(this, PosterImage);
_Button.call(this, player, options);
this.update();
player.on('posterchange', Fn.bind(this, this.update));
}
/**
* Clean up the poster image
*
* @method dispose
*/
PosterImage.prototype.dispose = function dispose() {
this.player().off('posterchange', this.update);
_Button.prototype.dispose.call(this);
};
/**
* Create the poster's image element
*
* @return {Element}
* @method createEl
*/
PosterImage.prototype.createEl = function createEl() {
var el = Dom.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 (!browser.BACKGROUND_SIZE_SUPPORTED) {
this.fallbackImg_ = Dom.createEl('img');
el.appendChild(this.fallbackImg_);
}
return el;
};
/**
* Event handler for updates to the player's poster source
*
* @method update
*/
PosterImage.prototype.update = 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();
}
};
/**
* Set the poster source depending on the display method
*
* @param {String} url The URL to the poster source
* @method setSrc
*/
PosterImage.prototype.setSrc = 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;
}
};
/**
* Event handler for clicks on the poster image
*
* @method handleClick
*/
PosterImage.prototype.handleClick = 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;
})(_buttonJs2['default']);
_componentJs2['default'].registerComponent('PosterImage', PosterImage);
exports['default'] = PosterImage;
module.exports = exports['default'];
},{"./button.js":57,"./component.js":58,"./utils/browser.js":115,"./utils/dom.js":118,"./utils/fn.js":120}],101:[function(_dereq_,module,exports){
/**
* @file setup.js
*
* Functions for automatically setting up a player
* based on the data-setup attribute of the video tag
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _windowLoaded = false;
var videojs = undefined;
// 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 = _globalDocument2['default'].getElementsByTagName('video');
var audios = _globalDocument2['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 (_globalDocument2['default'].readyState === 'complete') {
_windowLoaded = true;
} else {
Events.one(_globalWindow2['default'], 'load', function () {
_windowLoaded = true;
});
}
var hasLoaded = function hasLoaded() {
return _windowLoaded;
};
exports.autoSetup = autoSetup;
exports.autoSetupTimeout = autoSetupTimeout;
exports.hasLoaded = hasLoaded;
},{"./utils/events.js":119,"global/document":1,"global/window":2}],102:[function(_dereq_,module,exports){
/**
* @file slider.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _componentJs = _dereq_('../component.js');
var _componentJs2 = _interopRequireDefault(_componentJs);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
/**
* The base functionality for sliders like the volume bar and seek bar
*
* @param {Player|Object} player
* @param {Object=} options
* @extends Component
* @class Slider
*/
var Slider = (function (_Component) {
_inherits(Slider, _Component);
function Slider(player, options) {
_classCallCheck(this, Slider);
_Component.call(this, player, options);
// Set property names to bar to match with the child Slider class is looking for
this.bar = this.getChild(this.options_.barName);
// 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);
}
/**
* Create the component's DOM element
*
* @param {String} type Type of element to create
* @param {Object=} props List of properties in Object form
* @return {Element}
* @method createEl
*/
Slider.prototype.createEl = function createEl(type) {
var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
// Add the slider element class to all sub classes
props.className = props.className + ' vjs-slider';
props = _objectAssign2['default']({
tabIndex: 0
}, props);
attributes = _objectAssign2['default']({
'role': 'slider',
'aria-valuenow': 0,
'aria-valuemin': 0,
'aria-valuemax': 100,
tabIndex: 0
}, attributes);
return _Component.prototype.createEl.call(this, type, props, attributes);
};
/**
* Handle mouse down on slider
*
* @param {Object} event Mouse down event object
* @method handleMouseDown
*/
Slider.prototype.handleMouseDown = function handleMouseDown(event) {
event.preventDefault();
Dom.blockTextSelection();
this.addClass('vjs-sliding');
this.trigger('slideractive');
this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove);
this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp);
this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove);
this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp);
this.handleMouseMove(event);
};
/**
* To be overridden by a subclass
*
* @method handleMouseMove
*/
Slider.prototype.handleMouseMove = function handleMouseMove() {};
/**
* Handle mouse up on Slider
*
* @method handleMouseUp
*/
Slider.prototype.handleMouseUp = function handleMouseUp() {
Dom.unblockTextSelection();
this.removeClass('vjs-sliding');
this.trigger('sliderinactive');
this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove);
this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp);
this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove);
this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp);
this.update();
};
/**
* Update slider
*
* @method update
*/
Slider.prototype.update = 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;
}
// Convert to a percentage for setting
var percentage = (progress * 100).toFixed(2) + '%';
// Set the new bar width or height
if (this.vertical()) {
bar.el().style.height = percentage;
} else {
bar.el().style.width = percentage;
}
};
/**
* Calculate distance for slider
*
* @param {Object} event Event object
* @method calculateDistance
*/
Slider.prototype.calculateDistance = function calculateDistance(event) {
var position = Dom.getPointerPosition(this.el_, event);
if (this.vertical()) {
return position.y;
}
return position.x;
};
/**
* Handle on focus for slider
*
* @method handleFocus
*/
Slider.prototype.handleFocus = function handleFocus() {
this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress);
};
/**
* Handle key press for slider
*
* @param {Object} event Event object
* @method handleKeyPress
*/
Slider.prototype.handleKeyPress = 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();
}
};
/**
* Handle on blur for slider
*
* @method handleBlur
*/
Slider.prototype.handleBlur = function handleBlur() {
this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress);
};
/**
* Listener for click events on slider, used to prevent clicks
* from bubbling up to parent elements like button menus.
*
* @param {Object} event Event object
* @method handleClick
*/
Slider.prototype.handleClick = function handleClick(event) {
event.stopImmediatePropagation();
event.preventDefault();
};
/**
* Get/set if slider is horizontal for vertical
*
* @param {Boolean} bool True if slider is vertical, false is horizontal
* @return {Boolean} True if slider is vertical, false is horizontal
* @method vertical
*/
Slider.prototype.vertical = 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;
})(_componentJs2['default']);
_componentJs2['default'].registerComponent('Slider', Slider);
exports['default'] = Slider;
module.exports = exports['default'];
},{"../component.js":58,"../utils/dom.js":118,"global/document":1,"object.assign":43}],103:[function(_dereq_,module,exports){
/**
* @file flash-rtmp.js
*/
'use strict';
exports.__esModule = 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'];
},{}],104:[function(_dereq_,module,exports){
/**
* @file flash.js
* 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
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _tech = _dereq_('./tech');
var _tech2 = _interopRequireDefault(_tech);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsUrlJs = _dereq_('../utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js');
var _flashRtmp = _dereq_('./flash-rtmp');
var _flashRtmp2 = _interopRequireDefault(_flashRtmp);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var navigator = _globalWindow2['default'].navigator;
/**
* Flash Media Controller - Wrapper for fallback SWF API
*
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Tech
* @class Flash
*/
var Flash = (function (_Tech) {
_inherits(Flash, _Tech);
function Flash(options, ready) {
_classCallCheck(this, Flash);
_Tech.call(this, options, ready);
// Set the source when ready
if (options.source) {
this.ready(function () {
this.setSource(options.source);
}, true);
}
// 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);
}, true);
}
// Add global window functions that the swf expects
// A 4.x workflow we weren't able to solve for in 5.0
// because of the need to hard code these functions
// into the swf for security reasons
_globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {};
_globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {};
_globalWindow2['default'].videojs.Flash.onReady = Flash.onReady;
_globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent;
_globalWindow2['default'].videojs.Flash.onError = Flash.onError;
this.on('seeked', function () {
this.lastSeekTarget_ = undefined;
});
}
// Create setters and getters for attributes
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Flash.prototype.createEl = function createEl() {
var options = this.options_;
// If video.js is hosted locally you should also set the location
// for the hosted swf, which should be relative to the page (not video.js)
// Otherwise this adds a CDN url.
// The CDN also auto-adds a swf URL for that specific version.
if (!options.swf) {
options.swf = '//vjs.zencdn.net/swf/5.0.0-rc1/video-js.swf';
}
// Generate ID for swf object
var objId = options.techId;
// Merge default flashvars with ones passed in to init
var flashVars = _objectAssign2['default']({
// SWF Callback Functions
'readyFunction': 'videojs.Flash.onReady',
'eventProxyFunction': 'videojs.Flash.onEvent',
'errorEventProxyFunction': 'videojs.Flash.onError',
// Player Settings
'autoplay': options.autoplay,
'preload': options.preload,
'loop': options.loop,
'muted': options.muted
}, options.flashVars);
// Merge default parames with ones passed in
var params = _objectAssign2['default']({
'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 = _objectAssign2['default']({
'id': objId,
'name': objId, // Both ID and Name needed or swf to identify itself
'class': 'vjs-tech'
}, options.attributes);
this.el_ = Flash.embed(options.swf, flashVars, params, attributes);
this.el_.tech = this;
return this.el_;
};
/**
* Play for flash tech
*
* @method play
*/
Flash.prototype.play = function play() {
if (this.ended()) {
this.setCurrentTime(0);
}
this.el_.vjs_play();
};
/**
* Pause for flash tech
*
* @method pause
*/
Flash.prototype.pause = function pause() {
this.el_.vjs_pause();
};
/**
* Get/set video
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
Flash.prototype.src = function src(_src) {
if (_src === undefined) {
return this.currentSrc();
}
// Setting src through `src` not `setSrc` will be deprecated
return this.setSrc(_src);
};
/**
* Set video
*
* @param {Object=} src Source object
* @deprecated
* @method setSrc
*/
Flash.prototype.setSrc = function setSrc(src) {
// Make sure source URL is absolute.
src = Url.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.autoplay()) {
var tech = this;
this.setTimeout(function () {
tech.play();
}, 0);
}
};
/**
* Returns true if the tech is currently seeking.
* @return {boolean} true if seeking
*/
Flash.prototype.seeking = function seeking() {
return this.lastSeekTarget_ !== undefined;
};
/**
* Set current time
*
* @param {Number} time Current time of video
* @method setCurrentTime
*/
Flash.prototype.setCurrentTime = function setCurrentTime(time) {
var seekable = this.seekable();
if (seekable.length) {
// clamp to the current seekable range
time = time > seekable.start(0) ? time : seekable.start(0);
time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1);
this.lastSeekTarget_ = time;
this.trigger('seeking');
this.el_.vjs_setProperty('currentTime', time);
_Tech.prototype.setCurrentTime.call(this);
}
};
/**
* Get current time
*
* @param {Number=} time Current time of video
* @return {Number} Current time
* @method currentTime
*/
Flash.prototype.currentTime = 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');
};
/**
* Get current source
*
* @method currentSrc
*/
Flash.prototype.currentSrc = function currentSrc() {
if (this.currentSource_) {
return this.currentSource_.src;
} else {
return this.el_.vjs_getProperty('currentSrc');
}
};
/**
* Load media into player
*
* @method load
*/
Flash.prototype.load = function load() {
this.el_.vjs_load();
};
/**
* Get poster
*
* @method poster
*/
Flash.prototype.poster = function poster() {
this.el_.vjs_getProperty('poster');
};
/**
* Poster images are not handled by the Flash tech so make this a no-op
*
* @method setPoster
*/
Flash.prototype.setPoster = function setPoster() {};
/**
* Determine if can seek in media
*
* @return {TimeRangeObject}
* @method seekable
*/
Flash.prototype.seekable = function seekable() {
var duration = this.duration();
if (duration === 0) {
return _utilsTimeRangesJs.createTimeRange();
}
return _utilsTimeRangesJs.createTimeRange(0, duration);
};
/**
* Get buffered time range
*
* @return {TimeRangeObject}
* @method buffered
*/
Flash.prototype.buffered = function buffered() {
var ranges = this.el_.vjs_getProperty('buffered');
if (ranges.length === 0) {
return _utilsTimeRangesJs.createTimeRange();
}
return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]);
};
/**
* Get fullscreen support -
* Flash does not allow fullscreen through javascript
* so always returns false
*
* @return {Boolean} false
* @method supportsFullScreen
*/
Flash.prototype.supportsFullScreen = function supportsFullScreen() {
return false; // Flash does not allow fullscreen through javascript
};
/**
* Request to enter fullscreen
* Flash does not allow fullscreen through javascript
* so always returns false
*
* @return {Boolean} false
* @method enterFullScreen
*/
Flash.prototype.enterFullScreen = function enterFullScreen() {
return false;
};
return Flash;
})(_tech2['default']);
var _api = Flash.prototype;
var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(',');
var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,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
_tech2['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 = Url.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 = Dom.getEl(currSwf);
var tech = el && el.tech;
// if there is no el then the tech has been disposed
// and the tech element was removed from the player div
if (tech && tech.el()) {
// check that the flash object is really ready
Flash.checkReady(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 tech = Dom.getEl(swfID).tech;
tech.trigger(eventName);
};
// Log errors from the swf
Flash.onError = function (swfID, err) {
var tech = Dom.getEl(swfID).tech;
// trigger MEDIA_ERR_SRC_NOT_SUPPORTED
if (err === 'srcnotfound') {
return tech.error(4);
}
// trigger a custom error
tech.error('FLASH: ' + err);
};
// Flash Version Check
Flash.version = function () {
var version = '0,0,0';
// IE
try {
version = new _globalWindow2['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, flashVars, params, attributes) {
var code = Flash.getEmbedCode(swf, flashVars, params, attributes);
// Get element by embedding code and retrieving created element
var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0];
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) {
Object.getOwnPropertyNames(flashVars).forEach(function (key) {
flashVarsString += key + '=' + flashVars[key] + '&';
});
}
// Add swf, flashVars, and other default params
params = _objectAssign2['default']({
'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
Object.getOwnPropertyNames(params).forEach(function (key) {
paramsString += '<param name="' + key + '" value="' + params[key] + '" />';
});
attributes = _objectAssign2['default']({
// 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
Object.getOwnPropertyNames(attributes).forEach(function (key) {
attrsString += key + '="' + attributes[key] + '" ';
});
return '' + objTag + attrsString + '>' + paramsString + '</object>';
};
// Run Flash through the RTMP decorator
_flashRtmp2['default'](Flash);
_component2['default'].registerComponent('Flash', Flash);
exports['default'] = Flash;
module.exports = exports['default'];
},{"../component":58,"../utils/dom.js":118,"../utils/time-ranges.js":126,"../utils/url.js":128,"./flash-rtmp":103,"./tech":107,"global/window":2,"object.assign":43}],105:[function(_dereq_,module,exports){
/**
* @file html5.js
* HTML5 Media Controller - Wrapper for HTML5 Media API
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _techJs = _dereq_('./tech.js');
var _techJs2 = _interopRequireDefault(_techJs);
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsDomJs = _dereq_('../utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsUrlJs = _dereq_('../utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js');
var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs);
/**
* HTML5 Media Controller - Wrapper for HTML5 Media API
*
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Tech
* @class Html5
*/
var Html5 = (function (_Tech) {
_inherits(Html5, _Tech);
function Html5(options, ready) {
_classCallCheck(this, Html5);
_Tech.call(this, options, ready);
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 || options.tag && options.tag.initNetworkState_ === 3)) {
this.setSource(source);
} else {
this.handleLateInit_(this.el_);
}
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.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange);
this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd);
this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove);
this.proxyNativeTextTracks_();
}
// 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 (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) {
this.setControls(true);
}
this.triggerReady();
}
/* HTML5 Support Testing ---------------------------------------------------- */
/*
* Element for testing browser HTML5 video capabilities
*
* @type {Element}
* @constant
* @private
*/
/**
* Dispose of html5 media element
*
* @method dispose
*/
Html5.prototype.dispose = function dispose() {
var tt = this.el().textTracks;
var emulatedTt = this.textTracks();
// remove native event listeners
if (tt && tt.removeEventListener) {
tt.removeEventListener('change', this.handleTextTrackChange_);
tt.removeEventListener('addtrack', this.handleTextTrackAdd_);
tt.removeEventListener('removetrack', this.handleTextTrackRemove_);
}
// clearout the emulated text track list.
var i = emulatedTt.length;
while (i--) {
emulatedTt.removeTrack_(emulatedTt[i]);
}
Html5.disposeMediaElement(this.el_);
_Tech.prototype.dispose.call(this);
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
Html5.prototype.createEl = function createEl() {
var el = this.options_.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(true);
el.parentNode.insertBefore(clone, el);
Html5.disposeMediaElement(el);
el = clone;
} else {
el = _globalDocument2['default'].createElement('video');
// determine if native controls should be used
var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag);
var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes);
if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) {
delete attributes.controls;
}
Dom.setElAttributes(el, _objectAssign2['default'](attributes, {
id: this.options_.techId,
'class': 'vjs-tech'
}));
}
}
// 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 this.options_[attr] !== 'undefined') {
overwriteAttrs[attr] = this.options_[attr];
}
Dom.setElAttributes(el, overwriteAttrs);
}
return el;
// jenniisawesome = true;
};
// 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.
Html5.prototype.handleLateInit_ = function handleLateInit_(el) {
var _this = this;
if (el.networkState === 0 || el.networkState === 3) {
// The video element hasn't started loading the source yet
// or didn't find a source
return;
}
if (el.readyState === 0) {
var _ret = (function () {
// NetworkState is set synchronously BUT loadstart is fired at the
// end of the current stack, usually before setInterval(fn, 0).
// So at this point we know loadstart may have already fired or is
// about to fire, and either way the player hasn't seen it yet.
// We don't want to fire loadstart prematurely here and cause a
// double loadstart so we'll wait and see if it happens between now
// and the next loop, and fire it if not.
// HOWEVER, we also want to make sure it fires before loadedmetadata
// which could also happen between now and the next loop, so we'll
// watch for that also.
var loadstartFired = false;
var setLoadstartFired = function setLoadstartFired() {
loadstartFired = true;
};
_this.on('loadstart', setLoadstartFired);
var triggerLoadstart = function triggerLoadstart() {
// We did miss the original loadstart. Make sure the player
// sees loadstart before loadedmetadata
if (!loadstartFired) {
this.trigger('loadstart');
}
};
_this.on('loadedmetadata', triggerLoadstart);
_this.ready(function () {
this.off('loadstart', setLoadstartFired);
this.off('loadedmetadata', triggerLoadstart);
if (!loadstartFired) {
// We did miss the original native loadstart. Fire it now.
this.trigger('loadstart');
}
});
return {
v: undefined
};
})();
if (typeof _ret === 'object') return _ret.v;
}
// From here on we know that loadstart already fired and we missed it.
// The other readyState events aren't as much of a problem if we double
// them, so not going to go to as much trouble as loadstart to prevent
// that unless we find reason to.
var eventsToTrigger = ['loadstart'];
// loadedmetadata: newly equal to HAVE_METADATA (1) or greater
eventsToTrigger.push('loadedmetadata');
// loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater
if (el.readyState >= 2) {
eventsToTrigger.push('loadeddata');
}
// canplay: newly increased to HAVE_FUTURE_DATA (3) or greater
if (el.readyState >= 3) {
eventsToTrigger.push('canplay');
}
// canplaythrough: newly equal to HAVE_ENOUGH_DATA (4)
if (el.readyState >= 4) {
eventsToTrigger.push('canplaythrough');
}
// We still need to give the player time to add event listeners
this.ready(function () {
eventsToTrigger.forEach(function (type) {
this.trigger(type);
}, this);
});
};
Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() {
var tt = this.el().textTracks;
if (tt && tt.addEventListener) {
tt.addEventListener('change', this.handleTextTrackChange_);
tt.addEventListener('addtrack', this.handleTextTrackAdd_);
tt.addEventListener('removetrack', this.handleTextTrackRemove_);
}
};
Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) {
var tt = this.textTracks();
this.textTracks().trigger({
type: 'change',
target: tt,
currentTarget: tt,
srcElement: tt
});
};
Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) {
this.textTracks().addTrack_(e.track);
};
Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) {
this.textTracks().removeTrack_(e.track);
};
/**
* Play for html5 tech
*
* @method play
*/
Html5.prototype.play = function play() {
this.el_.play();
};
/**
* Pause for html5 tech
*
* @method pause
*/
Html5.prototype.pause = function pause() {
this.el_.pause();
};
/**
* Paused for html5 tech
*
* @return {Boolean}
* @method paused
*/
Html5.prototype.paused = function paused() {
return this.el_.paused;
};
/**
* Get current time
*
* @return {Number}
* @method currentTime
*/
Html5.prototype.currentTime = function currentTime() {
return this.el_.currentTime;
};
/**
* Set current time
*
* @param {Number} seconds Current time of video
* @method setCurrentTime
*/
Html5.prototype.setCurrentTime = function setCurrentTime(seconds) {
try {
this.el_.currentTime = seconds;
} catch (e) {
_utilsLogJs2['default'](e, 'Video is not ready. (Video.js)');
// this.warning(VideoJS.warnings.videoNotReady);
}
};
/**
* Get duration
*
* @return {Number}
* @method duration
*/
Html5.prototype.duration = function duration() {
return this.el_.duration || 0;
};
/**
* Get a TimeRange object that represents the intersection
* of the time ranges for which the user agent has all
* relevant media
*
* @return {TimeRangeObject}
* @method buffered
*/
Html5.prototype.buffered = function buffered() {
return this.el_.buffered;
};
/**
* Get volume level
*
* @return {Number}
* @method volume
*/
Html5.prototype.volume = function volume() {
return this.el_.volume;
};
/**
* Set volume level
*
* @param {Number} percentAsDecimal Volume percent as a decimal
* @method setVolume
*/
Html5.prototype.setVolume = function setVolume(percentAsDecimal) {
this.el_.volume = percentAsDecimal;
};
/**
* Get if muted
*
* @return {Boolean}
* @method muted
*/
Html5.prototype.muted = function muted() {
return this.el_.muted;
};
/**
* Set muted
*
* @param {Boolean} If player is to be muted or note
* @method setMuted
*/
Html5.prototype.setMuted = function setMuted(muted) {
this.el_.muted = muted;
};
/**
* Get player width
*
* @return {Number}
* @method width
*/
Html5.prototype.width = function width() {
return this.el_.offsetWidth;
};
/**
* Get player height
*
* @return {Number}
* @method height
*/
Html5.prototype.height = function height() {
return this.el_.offsetHeight;
};
/**
* Get if there is fullscreen support
*
* @return {Boolean}
* @method supportsFullScreen
*/
Html5.prototype.supportsFullScreen = function supportsFullScreen() {
if (typeof this.el_.webkitEnterFullScreen === 'function') {
var userAgent = _globalWindow2['default'].navigator.userAgent;
// Seems to be broken in Chromium/Chrome && Safari in Leopard
if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) {
return true;
}
}
return false;
};
/**
* Request to enter fullscreen
*
* @method enterFullScreen
*/
Html5.prototype.enterFullScreen = function enterFullScreen() {
var video = this.el_;
if ('webkitDisplayingFullscreen' in video) {
this.one('webkitbeginfullscreen', function () {
this.one('webkitendfullscreen', function () {
this.trigger('fullscreenchange', { isFullscreen: false });
});
this.trigger('fullscreenchange', { isFullscreen: true });
});
}
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();
}
};
/**
* Request to exit fullscreen
*
* @method exitFullScreen
*/
Html5.prototype.exitFullScreen = function exitFullScreen() {
this.el_.webkitExitFullScreen();
};
/**
* Get/set video
*
* @param {Object=} src Source object
* @return {Object}
* @method src
*/
Html5.prototype.src = function src(_src) {
if (_src === undefined) {
return this.el_.src;
} else {
// Setting src through `src` instead of `setSrc` will be deprecated
this.setSrc(_src);
}
};
/**
* Set video
*
* @param {Object} src Source object
* @deprecated
* @method setSrc
*/
Html5.prototype.setSrc = function setSrc(src) {
this.el_.src = src;
};
/**
* Load media into player
*
* @method load
*/
Html5.prototype.load = function load() {
this.el_.load();
};
/**
* Get current source
*
* @return {Object}
* @method currentSrc
*/
Html5.prototype.currentSrc = function currentSrc() {
return this.el_.currentSrc;
};
/**
* Get poster
*
* @return {String}
* @method poster
*/
Html5.prototype.poster = function poster() {
return this.el_.poster;
};
/**
* Set poster
*
* @param {String} val URL to poster image
* @method
*/
Html5.prototype.setPoster = function setPoster(val) {
this.el_.poster = val;
};
/**
* Get preload attribute
*
* @return {String}
* @method preload
*/
Html5.prototype.preload = function preload() {
return this.el_.preload;
};
/**
* Set preload attribute
*
* @param {String} val Value for preload attribute
* @method setPreload
*/
Html5.prototype.setPreload = function setPreload(val) {
this.el_.preload = val;
};
/**
* Get autoplay attribute
*
* @return {String}
* @method autoplay
*/
Html5.prototype.autoplay = function autoplay() {
return this.el_.autoplay;
};
/**
* Set autoplay attribute
*
* @param {String} val Value for preload attribute
* @method setAutoplay
*/
Html5.prototype.setAutoplay = function setAutoplay(val) {
this.el_.autoplay = val;
};
/**
* Get controls attribute
*
* @return {String}
* @method controls
*/
Html5.prototype.controls = function controls() {
return this.el_.controls;
};
/**
* Set controls attribute
*
* @param {String} val Value for controls attribute
* @method setControls
*/
Html5.prototype.setControls = function setControls(val) {
this.el_.controls = !!val;
};
/**
* Get loop attribute
*
* @return {String}
* @method loop
*/
Html5.prototype.loop = function loop() {
return this.el_.loop;
};
/**
* Set loop attribute
*
* @param {String} val Value for loop attribute
* @method setLoop
*/
Html5.prototype.setLoop = function setLoop(val) {
this.el_.loop = val;
};
/**
* Get error value
*
* @return {String}
* @method error
*/
Html5.prototype.error = function error() {
return this.el_.error;
};
/**
* Get whether or not the player is in the "seeking" state
*
* @return {Boolean}
* @method seeking
*/
Html5.prototype.seeking = function seeking() {
return this.el_.seeking;
};
/**
* Get a TimeRanges object that represents the
* ranges of the media resource to which it is possible
* for the user agent to seek.
*
* @return {TimeRangeObject}
* @method seekable
*/
Html5.prototype.seekable = function seekable() {
return this.el_.seekable;
};
/**
* Get if video ended
*
* @return {Boolean}
* @method ended
*/
Html5.prototype.ended = function ended() {
return this.el_.ended;
};
/**
* Get the value of the muted content attribute
* This attribute has no dynamic effect, it only
* controls the default state of the element
*
* @return {Boolean}
* @method defaultMuted
*/
Html5.prototype.defaultMuted = function defaultMuted() {
return this.el_.defaultMuted;
};
/**
* Get desired speed at which the media resource is to play
*
* @return {Number}
* @method playbackRate
*/
Html5.prototype.playbackRate = function playbackRate() {
return this.el_.playbackRate;
};
/**
* Returns a TimeRanges object that represents the ranges of the
* media resource that the user agent has played.
* @return {TimeRangeObject} the range of points on the media
* timeline that has been reached through normal playback
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played
*/
Html5.prototype.played = function played() {
return this.el_.played;
};
/**
* Set desired speed at which the media resource is to play
*
* @param {Number} val Speed at which the media resource is to play
* @method setPlaybackRate
*/
Html5.prototype.setPlaybackRate = function setPlaybackRate(val) {
this.el_.playbackRate = val;
};
/**
* Get the current state of network activity for the element, from
* the list below
* NETWORK_EMPTY (numeric value 0)
* NETWORK_IDLE (numeric value 1)
* NETWORK_LOADING (numeric value 2)
* NETWORK_NO_SOURCE (numeric value 3)
*
* @return {Number}
* @method networkState
*/
Html5.prototype.networkState = function networkState() {
return this.el_.networkState;
};
/**
* Get 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)
* HAVE_METADATA (numeric value 1)
* HAVE_CURRENT_DATA (numeric value 2)
* HAVE_FUTURE_DATA (numeric value 3)
* HAVE_ENOUGH_DATA (numeric value 4)
*
* @return {Number}
* @method readyState
*/
Html5.prototype.readyState = function readyState() {
return this.el_.readyState;
};
/**
* Get width of video
*
* @return {Number}
* @method videoWidth
*/
Html5.prototype.videoWidth = function videoWidth() {
return this.el_.videoWidth;
};
/**
* Get height of video
*
* @return {Number}
* @method videoHeight
*/
Html5.prototype.videoHeight = function videoHeight() {
return this.el_.videoHeight;
};
/**
* Get text tracks
*
* @return {TextTrackList}
* @method textTracks
*/
Html5.prototype.textTracks = function textTracks() {
return _Tech.prototype.textTracks.call(this);
};
/**
* Creates and returns a text track object
*
* @param {String} kind Text track kind (subtitles, captions, descriptions
* chapters and metadata)
* @param {String=} label Label to identify the text track
* @param {String=} language Two letter language abbreviation
* @return {TextTrackObject}
* @method addTextTrack
*/
Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.addTextTrack.call(this, kind, label, language);
}
return this.el_.addTextTrack(kind, label, language);
};
/**
* Creates and returns a remote text track object
*
* @param {Object} options The object should contain values for
* kind, language, label and src (location of the WebVTT file)
* @return {TextTrackObject}
* @method addRemoteTextTrack
*/
Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.addRemoteTextTrack.call(this, options);
}
var track = _globalDocument2['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);
this.remoteTextTracks().addTrack_(track.track);
return track;
};
/**
* Remove remote text track from TextTrackList object
*
* @param {TextTrackObject} track Texttrack object to remove
* @method removeRemoteTextTrack
*/
Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
if (!this['featuresNativeTextTracks']) {
return _Tech.prototype.removeRemoteTextTrack.call(this, track);
}
var tracks, i;
this.remoteTextTracks().removeTrack_(track);
tracks = this.el().querySelectorAll('track');
i = tracks.length;
while (i--) {
if (track === tracks[i] || track === tracks[i].track) {
this.el().removeChild(tracks[i]);
}
}
};
return Html5;
})(_techJs2['default']);
Html5.TEST_VID = _globalDocument2['default'].createElement('video');
var track = _globalDocument2['default'].createElement('track');
track.kind = 'captions';
track.srclang = 'en';
track.label = 'English';
Html5.TEST_VID.appendChild(track);
/*
* 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 {
Html5.TEST_VID['volume'] = 0.5;
} catch (e) {
return false;
}
return !!Html5.TEST_VID.canPlayType;
};
// Add Source Handler pattern functions to this tech
_techJs2['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 Html5.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 = Url.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 = Html5.TEST_VID.volume;
Html5.TEST_VID.volume = volume / 2 + 0.1;
return volume !== Html5.TEST_VID.volume;
};
/*
* Check if playbackRate is supported in this browser/device.
*
* @return {Number} [description]
*/
Html5.canControlPlaybackRate = function () {
var playbackRate = Html5.TEST_VID.playbackRate;
Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1;
return playbackRate !== Html5.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 = !!Html5.TEST_VID.textTracks;
if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) {
supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number';
}
if (supportsTextTracks && browser.IS_FIREFOX) {
supportsTextTracks = false;
}
if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) {
supportsTextTracks = false;
}
return supportsTextTracks;
};
/**
* An array of events available on the Html5 tech.
*
* @private
* @type {Array}
*/
Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange'];
/*
* 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'] = !browser.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 (browser.ANDROID_VERSION >= 4.0) {
if (!canPlayType) {
canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
}
Html5.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 (browser.IS_OLD_ANDROID) {
if (!canPlayType) {
canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType;
}
Html5.TEST_VID.constructor.prototype.canPlayType = function (type) {
if (type && mp4RE.test(type)) {
return 'maybe';
}
return canPlayType.call(this, type);
};
}
};
Html5.unpatchCanPlayType = function () {
var r = Html5.TEST_VID.constructor.prototype.canPlayType;
Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType;
canPlayType = null;
return r;
};
// by default, patch the video element
Html5.patchCanPlayType();
Html5.disposeMediaElement = function (el) {
if (!el) {
return;
}
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) {
// not supported
}
})();
}
};
_component2['default'].registerComponent('Html5', Html5);
exports['default'] = Html5;
module.exports = exports['default'];
},{"../component":58,"../utils/browser.js":115,"../utils/dom.js":118,"../utils/fn.js":120,"../utils/log.js":123,"../utils/merge-options.js":124,"../utils/url.js":128,"./tech.js":107,"global/document":1,"global/window":2,"object.assign":43}],106:[function(_dereq_,module,exports){
/**
* @file loader.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js');
var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs);
/**
* The Media Loader is the component that decides which playback technology to load
* when the player is initialized.
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class MediaLoader
*/
var MediaLoader = (function (_Component) {
_inherits(MediaLoader, _Component);
function MediaLoader(player, options, ready) {
_classCallCheck(this, MediaLoader);
_Component.call(this, player, options, ready);
// If there are no sources when the player is initialized,
// load the first supported playback technology.
if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) {
for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) {
var techName = _utilsToTitleCaseJs2['default'](j[i]);
var tech = _component2['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(options.playerOptions['sources']);
}
}
return MediaLoader;
})(_component2['default']);
_component2['default'].registerComponent('MediaLoader', MediaLoader);
exports['default'] = MediaLoader;
module.exports = exports['default'];
},{"../component":58,"../utils/to-title-case.js":127,"global/window":2}],107:[function(_dereq_,module,exports){
/**
* @file tech.js
* Media Technology Controller - Base class for media playback
* technology controllers like Flash and HTML5
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _tracksTextTrack = _dereq_('../tracks/text-track');
var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack);
var _tracksTextTrackList = _dereq_('../tracks/text-track-list');
var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js');
var _utilsBufferJs = _dereq_('../utils/buffer.js');
var _mediaErrorJs = _dereq_('../media-error.js');
var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* Base class for media (HTML5 Video, Flash) controllers
*
* @param {Object=} options Options object
* @param {Function=} ready Ready callback function
* @extends Component
* @class Tech
*/
var Tech = (function (_Component) {
_inherits(Tech, _Component);
function Tech() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1];
_classCallCheck(this, Tech);
// we don't want the tech to report user activity automatically.
// This is done manually in addControlsListeners
options.reportTouchActivity = false;
_Component.call(this, null, options, ready);
// keep track of whether the current source has played at all to
// implement a very limited played()
this.hasStarted_ = false;
this.on('playing', function () {
this.hasStarted_ = true;
});
this.on('loadstart', function () {
this.hasStarted_ = false;
});
this.textTracks_ = options.textTracks;
// 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();
}
if (options.nativeCaptions === false || options.nativeTextTracks === false) {
this.featuresNativeTextTracks = false;
}
if (!this.featuresNativeTextTracks) {
this.emulateTextTracks();
}
this.initTextTrackListeners();
// Turn on component tap events
this.emitTapEvents();
}
/*
* List of associated text tracks
*
* @type {Array}
* @private
*/
/* 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
/**
* Turn on progress events
*
* @method manualProgressOn
*/
Tech.prototype.manualProgressOn = function manualProgressOn() {
this.on('durationchange', this.onDurationChange);
this.manualProgress = true;
// Trigger progress watching when a source begins loading
this.one('ready', this.trackProgress);
};
/**
* Turn off progress events
*
* @method manualProgressOff
*/
Tech.prototype.manualProgressOff = function manualProgressOff() {
this.manualProgress = false;
this.stopTrackingProgress();
this.off('durationchange', this.onDurationChange);
};
/**
* Track progress
*
* @method trackProgress
*/
Tech.prototype.trackProgress = function trackProgress() {
this.stopTrackingProgress();
this.progressInterval = this.setInterval(Fn.bind(this, function () {
// Don't trigger unless buffered amount is greater than last time
var numBufferedPercent = this.bufferedPercent();
if (this.bufferedPercent_ !== numBufferedPercent) {
this.trigger('progress');
}
this.bufferedPercent_ = numBufferedPercent;
if (numBufferedPercent === 1) {
this.stopTrackingProgress();
}
}), 500);
};
/**
* Update duration
*
* @method onDurationChange
*/
Tech.prototype.onDurationChange = function onDurationChange() {
this.duration_ = this.duration();
};
/**
* Create and get TimeRange object for buffering
*
* @return {TimeRangeObject}
* @method buffered
*/
Tech.prototype.buffered = function buffered() {
return _utilsTimeRangesJs.createTimeRange(0, 0);
};
/**
* Get buffered percent
*
* @return {Number}
* @method bufferedPercent
*/
Tech.prototype.bufferedPercent = function bufferedPercent() {
return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_);
};
/**
* Stops tracking progress by clearing progress interval
*
* @method stopTrackingProgress
*/
Tech.prototype.stopTrackingProgress = function stopTrackingProgress() {
this.clearInterval(this.progressInterval);
};
/*! Time Tracking -------------------------------------------------------------- */
/**
* Set event listeners for on play and pause and tracking current time
*
* @method manualTimeUpdatesOn
*/
Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() {
this.manualTimeUpdates = true;
this.on('play', this.trackCurrentTime);
this.on('pause', this.stopTrackingCurrentTime);
};
/**
* Remove event listeners for on play and pause and tracking current time
*
* @method manualTimeUpdatesOff
*/
Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() {
this.manualTimeUpdates = false;
this.stopTrackingCurrentTime();
this.off('play', this.trackCurrentTime);
this.off('pause', this.stopTrackingCurrentTime);
};
/**
* Tracks current time
*
* @method trackCurrentTime
*/
Tech.prototype.trackCurrentTime = function trackCurrentTime() {
if (this.currentTimeInterval) {
this.stopTrackingCurrentTime();
}
this.currentTimeInterval = this.setInterval(function () {
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15
};
/**
* Turn off play progress tracking (when paused or dragging)
*
* @method stopTrackingCurrentTime
*/
Tech.prototype.stopTrackingCurrentTime = 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.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
};
/**
* Turn off any manual progress or timeupdate tracking
*
* @method dispose
*/
Tech.prototype.dispose = function dispose() {
// clear out text tracks because we can't reuse them between techs
var textTracks = this.textTracks();
if (textTracks) {
var i = textTracks.length;
while (i--) {
this.removeRemoteTextTrack(textTracks[i]);
}
}
// Turn off any manual progress or timeupdate tracking
if (this.manualProgress) {
this.manualProgressOff();
}
if (this.manualTimeUpdates) {
this.manualTimeUpdatesOff();
}
_Component.prototype.dispose.call(this);
};
/**
* When invoked without an argument, returns a MediaError object
* representing the current error state of the player or null if
* there is no error. When invoked with an argument, set the current
* error state of the player.
* @param {MediaError=} err Optional an error object
* @return {MediaError} the current error object or null
* @method error
*/
Tech.prototype.error = function error(err) {
if (err !== undefined) {
if (err instanceof _mediaErrorJs2['default']) {
this.error_ = err;
} else {
this.error_ = new _mediaErrorJs2['default'](err);
}
this.trigger('error');
}
return this.error_;
};
/**
* Return the time ranges that have been played through for the
* current source. This implementation is incomplete. It does not
* track the played time ranges, only whether the source has played
* at all or not.
* @return {TimeRangeObject} a single time range if this video has
* played or an empty set of ranges if not.
* @method played
*/
Tech.prototype.played = function played() {
if (this.hasStarted_) {
return _utilsTimeRangesJs.createTimeRange(0, 0);
}
return _utilsTimeRangesJs.createTimeRange();
};
/**
* Set current time
*
* @method setCurrentTime
*/
Tech.prototype.setCurrentTime = function setCurrentTime() {
// improve the accuracy of manual timeupdates
if (this.manualTimeUpdates) {
this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true });
}
};
/**
* Initialize texttrack listeners
*
* @method initTextTrackListeners
*/
Tech.prototype.initTextTrackListeners = function initTextTrackListeners() {
var textTrackListChanges = Fn.bind(this, function () {
this.trigger('texttrackchange');
});
var tracks = this.textTracks();
if (!tracks) return;
tracks.addEventListener('removetrack', textTrackListChanges);
tracks.addEventListener('addtrack', textTrackListChanges);
this.on('dispose', Fn.bind(this, function () {
tracks.removeEventListener('removetrack', textTrackListChanges);
tracks.removeEventListener('addtrack', textTrackListChanges);
}));
};
/**
* Emulate texttracks
*
* @method emulateTextTracks
*/
Tech.prototype.emulateTextTracks = function emulateTextTracks() {
if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) {
var script = _globalDocument2['default'].createElement('script');
script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js';
this.el().parentNode.appendChild(script);
_globalWindow2['default']['WebVTT'] = true;
}
var tracks = this.textTracks();
if (!tracks) {
return;
}
var textTracksChanges = Fn.bind(this, function () {
var _this = this;
var updateDisplay = function updateDisplay() {
return _this.trigger('texttrackchange');
};
updateDisplay();
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
track.removeEventListener('cuechange', updateDisplay);
if (track.mode === 'showing') {
track.addEventListener('cuechange', updateDisplay);
}
}
});
tracks.addEventListener('change', textTracksChanges);
this.on('dispose', function () {
tracks.removeEventListener('change', textTracksChanges);
});
};
/*
* Provide default methods for text tracks.
*
* Html5 tech overrides these.
*/
/**
* Get texttracks
*
* @returns {TextTrackList}
* @method textTracks
*/
Tech.prototype.textTracks = function textTracks() {
this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default']();
return this.textTracks_;
};
/**
* Get remote texttracks
*
* @returns {TextTrackList}
* @method remoteTextTracks
*/
Tech.prototype.remoteTextTracks = function remoteTextTracks() {
this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default']();
return this.remoteTextTracks_;
};
/**
* Creates and returns a remote text track object
*
* @param {String} kind Text track kind (subtitles, captions, descriptions
* chapters and metadata)
* @param {String=} label Label to identify the text track
* @param {String=} language Two letter language abbreviation
* @return {TextTrackObject}
* @method addTextTrack
*/
Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) {
if (!kind) {
throw new Error('TextTrack kind is required but was not provided');
}
return createTrackHelper(this, kind, label, language);
};
/**
* Creates and returns a remote text track object
*
* @param {Object} options The object should contain values for
* kind, language, label and src (location of the WebVTT file)
* @return {TextTrackObject}
* @method addRemoteTextTrack
*/
Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) {
var track = createTrackHelper(this, options.kind, options.label, options.language, options);
this.remoteTextTracks().addTrack_(track);
return {
track: track
};
};
/**
* Remove remote texttrack
*
* @param {TextTrackObject} track Texttrack to remove
* @method removeRemoteTextTrack
*/
Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) {
this.textTracks().removeTrack_(track);
this.remoteTextTracks().removeTrack_(track);
};
/**
* 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.
*
* @method setPoster
*/
Tech.prototype.setPoster = function setPoster() {};
return Tech;
})(_component2['default']);
Tech.prototype.textTracks_;
var createTrackHelper = function createTrackHelper(self, kind, label, language) {
var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4];
var tracks = self.textTracks();
options.kind = kind;
if (label) {
options.label = label;
}
if (language) {
options.language = language;
}
options.tech = self;
var track = new _tracksTextTrack2['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 '';
};
var originalSeekable = _Tech.prototype.seekable;
// when a source handler is registered, prefer its implementation of
// seekable when present.
_Tech.prototype.seekable = function () {
if (this.sourceHandler_ && this.sourceHandler_.seekable) {
return this.sourceHandler_.seekable();
}
return originalSeekable.call(this);
};
/*
* 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 {
_utilsLogJs2['default'].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();
}
};
};
_component2['default'].registerComponent('Tech', Tech);
// Old name for Tech
_component2['default'].registerComponent('MediaTechController', Tech);
exports['default'] = Tech;
module.exports = exports['default'];
},{"../component":58,"../media-error.js":94,"../tracks/text-track":114,"../tracks/text-track-list":112,"../utils/buffer.js":116,"../utils/fn.js":120,"../utils/log.js":123,"../utils/time-ranges.js":126,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){
/**
* @file text-track-cue-list.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* 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(cues) {
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['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 (browser.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'];
},{"../utils/browser.js":115,"global/document":1}],109:[function(_dereq_,module,exports){
/**
* @file text-track-display.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _menuMenuJs = _dereq_('../menu/menu.js');
var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs);
var _menuMenuItemJs = _dereq_('../menu/menu-item.js');
var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs);
var _menuMenuButtonJs = _dereq_('../menu/menu-button.js');
var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
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
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @param {Function=} ready Ready callback function
* @extends Component
* @class TextTrackDisplay
*/
var TextTrackDisplay = (function (_Component) {
_inherits(TextTrackDisplay, _Component);
function TextTrackDisplay(player, options, ready) {
_classCallCheck(this, TextTrackDisplay);
_Component.call(this, player, options, ready);
player.on('loadstart', Fn.bind(this, this.toggleDisplay));
player.on('texttrackchange', Fn.bind(this, this.updateDisplay));
// 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(Fn.bind(this, function () {
if (player.tech_ && player.tech_['featuresNativeTextTracks']) {
this.hide();
return;
}
player.on('fullscreenchange', Fn.bind(this, this.updateDisplay));
var tracks = this.options_.playerOptions['tracks'] || [];
for (var i = 0; i < tracks.length; i++) {
var track = tracks[i];
this.player_.addRemoteTextTrack(track);
}
}));
}
/**
* Add cue HTML to display
*
* @param {Number} color Hex number for color, like #f0e
* @param {Number} opacity Value for opacity,0.0 - 1.0
* @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)'
* @method constructColor
*/
/**
* Toggle display texttracks
*
* @method toggleDisplay
*/
TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() {
if (this.player_.tech_ && this.player_.tech_['featuresNativeTextTracks']) {
this.hide();
} else {
this.show();
}
};
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TextTrackDisplay.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-text-track-display'
});
};
/**
* Clear display texttracks
*
* @method clearDisplay
*/
TextTrackDisplay.prototype.clearDisplay = function clearDisplay() {
if (typeof _globalWindow2['default']['WebVTT'] === 'function') {
_globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_);
}
};
/**
* Update display texttracks
*
* @method updateDisplay
*/
TextTrackDisplay.prototype.updateDisplay = 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);
}
}
};
/**
* Add texttrack to texttrack list
*
* @param {TextTrackObject} track Texttrack object to be added to list
* @method updateForTrack
*/
TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) {
if (typeof _globalWindow2['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]);
}
_globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['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 = _globalWindow2['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;
})(_component2['default']);
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 + ')';
}
/**
* Try to update style
* Some style changes will throw an error, particularly in IE8. Those should be noops.
*
* @param {Element} el The element to be styles
* @param {CSSProperty} style The CSS property to be styled
* @param {CSSStyle} rule The actual style to be applied to the property
* @method tryUpdateStyle
*/
function tryUpdateStyle(el, style, rule) {
//
try {
el.style[style] = rule;
} catch (e) {}
}
_component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay);
exports['default'] = TextTrackDisplay;
module.exports = exports['default'];
},{"../component":58,"../menu/menu-button.js":95,"../menu/menu-item.js":96,"../menu/menu.js":97,"../utils/fn.js":120,"global/document":1,"global/window":2}],110:[function(_dereq_,module,exports){
/**
* @file text-track-enums.js
*
* https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode
*
* enum TextTrackMode { "disabled", "hidden", "showing" };
*/
'use strict';
exports.__esModule = true;
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;
},{}],111:[function(_dereq_,module,exports){
/**
* Utilities for capturing text track state and re-creating tracks
* based on a capture.
*
* @file text-track-list-converter.js
*/
/**
* Examine a single text track and return a JSON-compatible javascript
* object that represents the text track's state.
* @param track {TextTrackObject} the text track to query
* @return {Object} a serializable javascript representation of the
* @private
*/
'use strict';
exports.__esModule = true;
var trackToJson_ = function trackToJson_(track) {
return {
kind: track.kind,
label: track.label,
language: track.language,
id: track.id,
inBandMetadataTrackDispatchType: track.inBandMetadataTrackDispatchType,
mode: track.mode,
cues: track.cues && Array.prototype.map.call(track.cues, function (cue) {
return {
startTime: cue.startTime,
endTime: cue.endTime,
text: cue.text,
id: cue.id
};
}),
src: track.src
};
};
/**
* Examine a tech and return a JSON-compatible javascript array that
* represents the state of all text tracks currently configured. The
* return array is compatible with `jsonToTextTracks`.
* @param tech {tech} the tech object to query
* @return {Array} a serializable javascript representation of the
* @function textTracksToJson
*/
var textTracksToJson = function textTracksToJson(tech) {
var trackEls = tech.el().querySelectorAll('track');
var trackObjs = Array.prototype.map.call(trackEls, function (t) {
return t.track;
});
var tracks = Array.prototype.map.call(trackEls, function (trackEl) {
var json = trackToJson_(trackEl.track);
json.src = trackEl.src;
return json;
});
return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) {
return trackObjs.indexOf(track) === -1;
}).map(trackToJson_));
};
/**
* Creates a set of remote text tracks on a tech based on an array of
* javascript text track representations.
* @param json {Array} an array of text track representation objects,
* like those that would be produced by `textTracksToJson`
* @param tech {tech} the tech to create text tracks on
* @function jsonToTextTracks
*/
var jsonToTextTracks = function jsonToTextTracks(json, tech) {
json.forEach(function (track) {
var addedTrack = tech.addRemoteTextTrack(track).track;
if (!track.src && track.cues) {
track.cues.forEach(function (cue) {
return addedTrack.addCue(cue);
});
}
});
return tech.textTracks();
};
exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ };
module.exports = exports['default'];
},{}],112:[function(_dereq_,module,exports){
/**
* @file text-track-list.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/*
* 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(tracks) {
var list = this;
if (browser.IS_IE8) {
list = _globalDocument2['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 (browser.IS_IE8) {
return list;
}
};
TextTrackList.prototype = Object.create(_eventTarget2['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', Fn.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-target":90,"../utils/browser.js":115,"../utils/fn.js":120,"global/document":1}],113:[function(_dereq_,module,exports){
/**
* @file text-track-settings.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _component = _dereq_('../component');
var _component2 = _interopRequireDefault(_component);
var _utilsEventsJs = _dereq_('../utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple');
var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* Manipulate settings of texttracks
*
* @param {Object} player Main Player
* @param {Object=} options Object of option names and values
* @extends Component
* @class TextTrackSettings
*/
var TextTrackSettings = (function (_Component) {
_inherits(TextTrackSettings, _Component);
function TextTrackSettings(player, options) {
_classCallCheck(this, TextTrackSettings);
_Component.call(this, player, options);
this.hide();
// Grab `persistTextTrackSettings` from the player options if not passed in child options
if (options.persistTextTrackSettings === undefined) {
this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings;
}
Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () {
this.saveSettings();
this.hide();
}));
Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.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', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay));
Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay));
if (this.options_.persistTextTrackSettings) {
this.restoreSettings();
}
}
/**
* Create the component's DOM element
*
* @return {Element}
* @method createEl
*/
TextTrackSettings.prototype.createEl = function createEl() {
return _Component.prototype.createEl.call(this, 'div', {
className: 'vjs-caption-settings vjs-modal-overlay',
innerHTML: captionOptionsMenuTemplate()
});
};
/**
* Get texttrack settings
* Settings are
* .vjs-edge-style
* .vjs-font-family
* .vjs-fg-color
* .vjs-text-opacity
* .vjs-bg-color
* .vjs-bg-opacity
* .window-color
* .vjs-window-opacity
*
* @return {Object}
* @method getValues
*/
TextTrackSettings.prototype.getValues = 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 = _globalWindow2['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.00) {
delete result[_name];
}
}
return result;
};
/**
* Set texttrack settings
* Settings are
* .vjs-edge-style
* .vjs-font-family
* .vjs-fg-color
* .vjs-text-opacity
* .vjs-bg-color
* .vjs-bg-opacity
* .window-color
* .vjs-window-opacity
*
* @param {Object} values Object with texttrack setting values
* @method setValues
*/
TextTrackSettings.prototype.setValues = 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);
};
/**
* Restore texttrack settings
*
* @method restoreSettings
*/
TextTrackSettings.prototype.restoreSettings = function restoreSettings() {
var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings'));
var err = _safeParseTuple[0];
var values = _safeParseTuple[1];
if (err) {
_utilsLogJs2['default'].error(err);
}
if (values) {
this.setValues(values);
}
};
/**
* Save texttrack settings to local storage
*
* @method saveSettings
*/
TextTrackSettings.prototype.saveSettings = function saveSettings() {
if (!this.options_.persistTextTrackSettings) {
return;
}
var values = this.getValues();
try {
if (Object.getOwnPropertyNames(values).length > 0) {
_globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values));
} else {
_globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings');
}
} catch (e) {}
};
/**
* Update display of texttrack settings
*
* @method updateDisplay
*/
TextTrackSettings.prototype.updateDisplay = function updateDisplay() {
var ttDisplay = this.player_.getChild('textTrackDisplay');
if (ttDisplay) {
ttDisplay.updateDisplay();
}
};
return TextTrackSettings;
})(_component2['default']);
_component2['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":58,"../utils/events.js":119,"../utils/fn.js":120,"../utils/log.js":123,"global/window":2,"safe-json-parse/tuple":48}],114:[function(_dereq_,module,exports){
/**
* @file text-track.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _textTrackCueList = _dereq_('./text-track-cue-list');
var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList);
var _utilsFnJs = _dereq_('../utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _utilsGuidJs = _dereq_('../utils/guid.js');
var Guid = _interopRequireWildcard(_utilsGuidJs);
var _utilsBrowserJs = _dereq_('../utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _textTrackEnums = _dereq_('./text-track-enums');
var TextTrackEnum = _interopRequireWildcard(_textTrackEnums);
var _utilsLogJs = _dereq_('../utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _eventTarget = _dereq_('../event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _xhr = _dereq_('xhr');
var _xhr2 = _interopRequireDefault(_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() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
if (!options.tech) {
throw new Error('A tech was not provided.');
}
var tt = this;
if (browser.IS_IE8) {
tt = _globalDocument2['default'].createElement('custom');
for (var prop in TextTrack.prototype) {
tt[prop] = TextTrack.prototype[prop];
}
}
tt.tech_ = options.tech;
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_' + Guid.newGUID();
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 = Fn.bind(tt, function () {
this['activeCues'];
if (changed) {
this['trigger']('cuechange');
changed = false;
}
});
if (mode !== 'disabled') {
tt.tech_.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.tech_.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.tech_.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) {
tt.src = options.src;
loadTrack(options.src, tt);
} else {
tt.loaded_ = true;
}
if (browser.IS_IE8) {
return tt;
}
};
TextTrack.prototype = Object.create(_eventTarget2['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.tech_.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(srcContent, track) {
if (typeof _globalWindow2['default']['WebVTT'] !== 'function') {
//try again a bit later
return _globalWindow2['default'].setTimeout(function () {
parseCues(srcContent, track);
}, 25);
}
var parser = new _globalWindow2['default']['WebVTT']['Parser'](_globalWindow2['default'], _globalWindow2['default']['vttjs'], _globalWindow2['default']['WebVTT']['StringDecoder']());
parser['oncue'] = function (cue) {
track.addCue(cue);
};
parser['onparsingerror'] = function (error) {
_utilsLogJs2['default'].error(error);
};
parser['parse'](srcContent);
parser['flush']();
};
var loadTrack = function loadTrack(src, track) {
_xhr2['default']({ uri: src }, Fn.bind(this, function (err, response, responseBody) {
if (err) {
return _utilsLogJs2['default'].error(err, response);
}
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-target":90,"../utils/browser.js":115,"../utils/fn.js":120,"../utils/guid.js":122,"../utils/log.js":123,"./text-track-cue-list":108,"./text-track-enums":110,"global/document":1,"global/window":2,"xhr":50}],115:[function(_dereq_,module,exports){
/**
* @file browser.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var USER_AGENT = _globalWindow2['default'].navigator.userAgent;
var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT);
var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null;
/*
* Device is an iPhone
*
* @type {Boolean}
* @constant
* @private
*/
var IS_IPHONE = /iPhone/i.test(USER_AGENT);
exports.IS_IPHONE = IS_IPHONE;
var IS_IPAD = /iPad/i.test(USER_AGENT);
exports.IS_IPAD = IS_IPAD;
var IS_IPOD = /iPod/i.test(USER_AGENT);
exports.IS_IPOD = IS_IPOD;
var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD;
exports.IS_IOS = IS_IOS;
var IOS_VERSION = (function () {
var match = USER_AGENT.match(/OS (\d+)_/i);
if (match && match[1]) {
return match[1];
}
})();
exports.IOS_VERSION = IOS_VERSION;
var IS_ANDROID = /Android/i.test(USER_AGENT);
exports.IS_ANDROID = IS_ANDROID;
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;
}
})();
exports.ANDROID_VERSION = ANDROID_VERSION;
// 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;
exports.IS_OLD_ANDROID = IS_OLD_ANDROID;
var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537;
exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID;
var IS_FIREFOX = /Firefox/i.test(USER_AGENT);
exports.IS_FIREFOX = IS_FIREFOX;
var IS_CHROME = /Chrome/i.test(USER_AGENT);
exports.IS_CHROME = IS_CHROME;
var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT);
exports.IS_IE8 = IS_IE8;
var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch);
exports.TOUCH_ENABLED = TOUCH_ENABLED;
var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style);
exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED;
},{"global/document":1,"global/window":2}],116:[function(_dereq_,module,exports){
/**
* @file buffer.js
*/
'use strict';
exports.__esModule = true;
exports.bufferedPercent = bufferedPercent;
var _timeRangesJs = _dereq_('./time-ranges.js');
/**
* Compute how much your video has been buffered
*
* @param {Object} Buffered object
* @param {Number} Total duration
* @return {Number} Percent buffered of the total duration
* @private
* @function bufferedPercent
*/
function bufferedPercent(buffered, duration) {
var bufferedDuration = 0,
start,
end;
if (!duration) {
return 0;
}
if (!buffered || !buffered.length) {
buffered = _timeRangesJs.createTimeRange(0, 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;
}
},{"./time-ranges.js":126}],117:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
/**
* Object containing the default behaviors for available handler methods.
*
* @private
* @type {Object}
*/
var defaultBehaviors = {
get: function get(obj, key) {
return obj[key];
},
set: function set(obj, key, value) {
obj[key] = value;
return true;
}
};
/**
* Expose private objects publicly using a Proxy to log deprecation warnings.
*
* Browsers that do not support Proxy objects will simply return the `target`
* object, so it can be directly exposed.
*
* @param {Object} target The target object.
* @param {Object} messages Messages to display from a Proxy. Only operations
* with an associated message will be proxied.
* @param {String} [messages.get]
* @param {String} [messages.set]
* @return {Object} A Proxy if supported or the `target` argument.
*/
exports['default'] = function (target) {
var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
if (typeof Proxy === 'function') {
var _ret = (function () {
var handler = {};
// Build a handler object based on those keys that have both messages
// and default behaviors.
Object.keys(messages).forEach(function (key) {
if (defaultBehaviors.hasOwnProperty(key)) {
handler[key] = function () {
_logJs2['default'].warn(messages[key]);
return defaultBehaviors[key].apply(this, arguments);
};
}
});
return {
v: new Proxy(target, handler)
};
})();
if (typeof _ret === 'object') return _ret.v;
}
return target;
};
module.exports = exports['default'];
},{"./log.js":123}],118:[function(_dereq_,module,exports){
/**
* @file dom.js
*/
'use strict';
exports.__esModule = true;
exports.getEl = getEl;
exports.createEl = createEl;
exports.insertElFirst = insertElFirst;
exports.getElData = getElData;
exports.hasElData = hasElData;
exports.removeElData = removeElData;
exports.hasElClass = hasElClass;
exports.addElClass = addElClass;
exports.removeElClass = removeElClass;
exports.setElAttributes = setElAttributes;
exports.getElAttributes = getElAttributes;
exports.blockTextSelection = blockTextSelection;
exports.unblockTextSelection = unblockTextSelection;
exports.findElPosition = findElPosition;
exports.getPointerPosition = getPointerPosition;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _guidJs = _dereq_('./guid.js');
var Guid = _interopRequireWildcard(_guidJs);
var _logJs = _dereq_('./log.js');
var _logJs2 = _interopRequireDefault(_logJs);
var _tsml = _dereq_('tsml');
var _tsml2 = _interopRequireDefault(_tsml);
/**
* 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
* @function getEl
*/
function getEl(id) {
if (id.indexOf('#') === 0) {
id = id.slice(1);
}
return _globalDocument2['default'].getElementById(id);
}
/**
* 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}
* @function createEl
*/
function createEl() {
var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0];
var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var el = _globalDocument2['default'].createElement(tagName);
Object.getOwnPropertyNames(properties).forEach(function (propName) {
var val = properties[propName];
// See #2176
// We originally were accepting both properties and attributes in the
// same object, but that doesn't work so well.
if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') {
_logJs2['default'].warn(_tsml2['default']('Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ' + propName + ' to ' + val + '.'));
el.setAttribute(propName, val);
} else {
el[propName] = val;
}
});
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var val = attributes[attrName];
el.setAttribute(attrName, attributes[attrName]);
});
return el;
}
/**
* Insert an element as the first child node of another
*
* @param {Element} child Element to insert
* @param {Element} parent Element to insert child into
* @private
* @function insertElFirst
*/
function insertElFirst(child, parent) {
if (parent.firstChild) {
parent.insertBefore(child, parent.firstChild);
} else {
parent.appendChild(child);
}
}
/**
* 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 elData = {};
/*
* Unique attribute name to store an element's guid in
*
* @type {String}
* @constant
* @private
*/
var elIdAttr = '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}
* @function getElData
*/
function getElData(el) {
var id = el[elIdAttr];
if (!id) {
id = el[elIdAttr] = Guid.newGUID();
}
if (!elData[id]) {
elData[id] = {};
}
return elData[id];
}
/**
* Returns whether or not an element has cached data
*
* @param {Element} el A dom element
* @return {Boolean}
* @private
* @function hasElData
*/
function hasElData(el) {
var id = el[elIdAttr];
if (!id) {
return false;
}
return !!Object.getOwnPropertyNames(elData[id]).length;
}
/**
* Delete data for the element from the cache and the guid attr from getElementById
*
* @param {Element} el Remove data for an element
* @private
* @function removeElData
*/
function removeElData(el) {
var id = el[elIdAttr];
if (!id) {
return;
}
// Remove all stored data
delete elData[id];
// Remove the elIdAttr property from the DOM node
try {
delete el[elIdAttr];
} catch (e) {
if (el.removeAttribute) {
el.removeAttribute(elIdAttr);
} else {
// IE doesn't appear to support removeAttribute on the document element
el[elIdAttr] = null;
}
}
}
/**
* Check if an element has a CSS class
*
* @param {Element} element Element to check
* @param {String} classToCheck Classname to check
* @function hasElClass
*/
function hasElClass(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
* @function addElClass
*/
function addElClass(element, classToAdd) {
if (!hasElClass(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} classToRemove Classname to remove
* @function removeElClass
*/
function removeElClass(element, classToRemove) {
if (!hasElClass(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(' ');
}
/**
* Apply attributes to an HTML element.
*
* @param {Element} el Target element.
* @param {Object=} attributes Element attributes to be applied.
* @private
* @function setElAttributes
*/
function setElAttributes(el, attributes) {
Object.getOwnPropertyNames(attributes).forEach(function (attrName) {
var attrValue = attributes[attrName];
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
* @function getElAttributes
*/
function getElAttributes(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;
}
/**
* Attempt to block the ability to select text while dragging controls
*
* @return {Boolean}
* @method blockTextSelection
*/
function blockTextSelection() {
_globalDocument2['default'].body.focus();
_globalDocument2['default'].onselectstart = function () {
return false;
};
}
/**
* Turn off text selection blocking
*
* @return {Boolean}
* @method unblockTextSelection
*/
function unblockTextSelection() {
_globalDocument2['default'].onselectstart = function () {
return true;
};
}
/**
* Offset Left
* getBoundingClientRect technique from
* John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/
*
* @param {Element} el Element from which to get offset
* @return {Object=}
* @method findElPosition
*/
function findElPosition(el) {
var box = undefined;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0
};
}
var docEl = _globalDocument2['default'].documentElement;
var body = _globalDocument2['default'].body;
var clientLeft = docEl.clientLeft || body.clientLeft || 0;
var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft;
var left = box.left + scrollLeft - clientLeft;
var clientTop = docEl.clientTop || body.clientTop || 0;
var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop;
var top = box.top + scrollTop - clientTop;
// Android sometimes returns slightly off decimal values, so need to round
return {
left: Math.round(left),
top: Math.round(top)
};
}
/**
* Get pointer position in element
* Returns an object with x and y coordinates.
* The base on the coordinates are the bottom left of the element.
*
* @param {Element} el Element on which to get the pointer position on
* @param {Event} event Event object
* @return {Object=} position This object will have x and y coordinates corresponding to the mouse position
* @metho getPointerPosition
*/
function getPointerPosition(el, event) {
var position = {};
var box = findElPosition(el);
var boxW = el.offsetWidth;
var boxH = el.offsetHeight;
var boxY = box.top;
var boxX = box.left;
var pageY = event.pageY;
var pageX = event.pageX;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
pageY = event.changedTouches[0].pageY;
}
position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH));
position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
return position;
}
},{"./guid.js":122,"./log.js":123,"global/document":1,"global/window":2,"tsml":49}],119:[function(_dereq_,module,exports){
/**
* @file events.js
*
* 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.
*/
'use strict';
exports.__esModule = true;
exports.on = on;
exports.off = off;
exports.trigger = trigger;
exports.one = one;
exports.fixEvent = fixEvent;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
var _domJs = _dereq_('./dom.js');
var Dom = _interopRequireWildcard(_domJs);
var _guidJs = _dereq_('./guid.js');
var Guid = _interopRequireWildcard(_guidJs);
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* 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.
* @method on
*/
function on(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(on, elem, type, fn);
}
var data = Dom.getElData(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 = Guid.newGUID();
data.handlers[type].push(fn);
if (!data.dispatcher) {
data.disabled = false;
data.dispatcher = function (event, hash) {
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, hash);
}
}
}
};
}
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.
* @method off
*/
function off(elem, type, fn) {
// Don't want to add a cache object through getElData if not needed
if (!Dom.hasElData(elem)) return;
var data = Dom.getElData(elem);
// If no events exist, nothing to unbind
if (!data.handlers) {
return;
}
if (Array.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);
}
/**
* 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
* @param {Object} [hash] data hash to pass along with the event
* @return {Boolean=} Returned only if default was prevented
* @method trigger
*/
function trigger(elem, event, hash) {
// 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 hasElData first.
var elemData = Dom.hasElData(elem) ? Dom.getElData(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, hash);
}
// 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 === true) {
trigger.call(null, parent, event, hash);
// If at the top of the DOM, triggers the default action unless disabled.
} else if (!parent && !event.defaultPrevented) {
var targetData = Dom.getElData(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 Name/type of event
* @param {Function} fn Event handler function
* @method one
*/
function one(elem, type, fn) {
if (Array.isArray(type)) {
return _handleMultipleEvents(one, elem, type, fn);
}
var func = function func() {
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 || Guid.newGUID();
on(elem, type, func);
}
/**
* Fix a native event to have standard property values
*
* @param {Object} event Event object to fix
* @return {Object}
* @private
* @method 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 || _globalWindow2['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
// and webkitMovementX/Y
if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') {
// 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 || _globalDocument2['default'];
}
// Handle which other element the event is related to
if (!event.relatedTarget) {
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;
old.returnValue = false;
event.defaultPrevented = true;
};
event.defaultPrevented = false;
// Stop the event from bubbling
event.stopPropagation = function () {
if (old.stopPropagation) {
old.stopPropagation();
}
event.cancelBubble = true;
old.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 = _globalDocument2['default'].documentElement,
body = _globalDocument2['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;
}
/**
* 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
* @method _cleanUpEvents
*/
function _cleanUpEvents(elem, type) {
var data = Dom.getElData(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 (Object.getOwnPropertyNames(data.handlers).length <= 0) {
delete data.handlers;
delete data.dispatcher;
delete data.disabled;
}
// Finally remove the element data if there is no data left
if (Object.getOwnPropertyNames(data).length === 0) {
Dom.removeElData(elem);
}
}
/**
* 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
*/
function _handleMultipleEvents(fn, elem, types, callback) {
types.forEach(function (type) {
//Call the event method for each one of the types
fn(elem, type, callback);
});
}
},{"./dom.js":118,"./guid.js":122,"global/document":1,"global/window":2}],120:[function(_dereq_,module,exports){
/**
* @file fn.js
*/
'use strict';
exports.__esModule = true;
var _guidJs = _dereq_('./guid.js');
/**
* 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
* @method bind
*/
var bind = function bind(context, fn, uid) {
// Make sure the function has a unique ID
if (!fn.guid) {
fn.guid = _guidJs.newGUID();
}
// 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;
};
exports.bind = bind;
},{"./guid.js":122}],121:[function(_dereq_,module,exports){
/**
* @file format-time.js
*
* 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
* @function formatTime
*/
'use strict';
exports.__esModule = true;
function formatTime(seconds) {
var guide = arguments.length <= 1 || 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;
})();
}
exports['default'] = formatTime;
module.exports = exports['default'];
},{}],122:[function(_dereq_,module,exports){
/**
* @file guid.js
*
* Unique ID for an element or function
* @type {Number}
* @private
*/
"use strict";
exports.__esModule = true;
exports.newGUID = newGUID;
var _guid = 1;
/**
* Get the next unique ID
*
* @return {String}
* @function newGUID
*/
function newGUID() {
return _guid++;
}
},{}],123:[function(_dereq_,module,exports){
/**
* @file log.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalWindow = _dereq_('global/window');
var _globalWindow2 = _interopRequireDefault(_globalWindow);
/**
* 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);
};
/**
* 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 {Object} args The args to be passed to the log
* @private
* @method _logType
*/
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 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 = _globalWindow2['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(' '));
}
}
exports['default'] = log;
module.exports = exports['default'];
},{"global/window":2}],124:[function(_dereq_,module,exports){
/**
* @file merge-options.js
*/
'use strict';
exports.__esModule = true;
exports['default'] = mergeOptions;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
function isPlain(obj) {
return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object;
}
/**
* Merge customizer. video.js simply overwrites non-simple objects
* (like arrays) instead of attempting to overlay them.
* @see https://lodash.com/docs#merge
*/
var customizer = function customizer(destination, source) {
// If we're not working with a plain object, copy the value as is
// If source is an array, for instance, it will replace destination
if (!isPlain(source)) {
return source;
}
// If the new value is a plain object but the first object value is not
// we need to create a new object for the first object to merge with.
// This makes it consistent with how merge() works by default
// and also protects from later changes the to first object affecting
// the second object's values.
if (!isPlain(destination)) {
return mergeOptions(source);
}
};
/**
* Merge one or more options objects, recursively merging **only**
* plain object properties. Previously `deepMerge`.
*
* @param {...Object} source One or more objects to merge
* @returns {Object} a new object that is the union of all
* provided objects
* @function mergeOptions
*/
function mergeOptions() {
// contruct the call dynamically to handle the variable number of
// objects to merge
var args = Array.prototype.slice.call(arguments);
// unshift an empty object into the front of the call as the target
// of the merge
args.unshift({});
// customize conflict resolution to match our historical merge behavior
args.push(customizer);
_lodashCompatObjectMerge2['default'].apply(null, args);
// return the mutated result object
return args[0];
}
module.exports = exports['default'];
},{"lodash-compat/object/merge":40}],125:[function(_dereq_,module,exports){
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var createStyleElement = function createStyleElement(className) {
var style = _globalDocument2['default'].createElement('style');
style.className = className;
return style;
};
exports.createStyleElement = createStyleElement;
var setTextContent = function setTextContent(el, content) {
if (el.styleSheet) {
el.styleSheet.cssText = content;
} else {
el.textContent = content;
}
};
exports.setTextContent = setTextContent;
},{"global/document":1}],126:[function(_dereq_,module,exports){
/**
* @file time-ranges.js
*
* 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
* @method createTimeRange
*/
'use strict';
exports.__esModule = true;
exports.createTimeRange = createTimeRange;
function createTimeRange(_start, _end) {
if (_start === undefined && _end === undefined) {
return {
length: 0,
start: function start() {
throw new Error('This TimeRanges object is empty');
},
end: function end() {
throw new Error('This TimeRanges object is empty');
}
};
}
return {
length: 1,
start: function start() {
return _start;
},
end: function end() {
return _end;
}
};
}
},{}],127:[function(_dereq_,module,exports){
/**
* @file to-title-case.js
*
* Uppercase the first letter of a string
*
* @param {String} string String to be uppercased
* @return {String}
* @private
* @method toTitleCase
*/
"use strict";
exports.__esModule = true;
function toTitleCase(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
exports["default"] = toTitleCase;
module.exports = exports["default"];
},{}],128:[function(_dereq_,module,exports){
/**
* @file url.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
/**
* Resolve and parse the elements of a URL
*
* @param {String} url The url to parse
* @return {Object} An object of url details
* @method parseUrl
*/
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 = _globalDocument2['default'].createElement('a');
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 = _globalDocument2['default'].createElement('div');
div.innerHTML = '<a href="' + url + '"></a>';
a = div.firstChild;
// prevent the div from affecting layout
div.setAttribute('style', 'display:none; position:absolute;');
_globalDocument2['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) {
_globalDocument2['default'].body.removeChild(div);
}
return details;
};
exports.parseUrl = parseUrl;
/**
* 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
* @method getAbsoluteURL
*/
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.
var div = _globalDocument2['default'].createElement('div');
div.innerHTML = '<a href="' + url + '">x</a>';
url = div.firstChild.href;
}
return url;
};
exports.getAbsoluteURL = getAbsoluteURL;
/**
* 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.
* @method getFileExtension
*/
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.getFileExtension = getFileExtension;
},{"global/document":1}],129:[function(_dereq_,module,exports){
/**
* @file video.js
*/
'use strict';
exports.__esModule = true;
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _globalDocument = _dereq_('global/document');
var _globalDocument2 = _interopRequireDefault(_globalDocument);
var _setup = _dereq_('./setup');
var setup = _interopRequireWildcard(_setup);
var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js');
var stylesheet = _interopRequireWildcard(_utilsStylesheetJs);
var _component = _dereq_('./component');
var _component2 = _interopRequireDefault(_component);
var _eventTarget = _dereq_('./event-target');
var _eventTarget2 = _interopRequireDefault(_eventTarget);
var _utilsEventsJs = _dereq_('./utils/events.js');
var Events = _interopRequireWildcard(_utilsEventsJs);
var _player = _dereq_('./player');
var _player2 = _interopRequireDefault(_player);
var _pluginsJs = _dereq_('./plugins.js');
var _pluginsJs2 = _interopRequireDefault(_pluginsJs);
var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js');
var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs);
var _utilsFnJs = _dereq_('./utils/fn.js');
var Fn = _interopRequireWildcard(_utilsFnJs);
var _objectAssign = _dereq_('object.assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js');
var _utilsFormatTimeJs = _dereq_('./utils/format-time.js');
var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs);
var _utilsLogJs = _dereq_('./utils/log.js');
var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs);
var _utilsDomJs = _dereq_('./utils/dom.js');
var Dom = _interopRequireWildcard(_utilsDomJs);
var _utilsBrowserJs = _dereq_('./utils/browser.js');
var browser = _interopRequireWildcard(_utilsBrowserJs);
var _utilsUrlJs = _dereq_('./utils/url.js');
var Url = _interopRequireWildcard(_utilsUrlJs);
var _extendsJs = _dereq_('./extends.js');
var _extendsJs2 = _interopRequireDefault(_extendsJs);
var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge');
var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge);
var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js');
var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs);
var _xhr = _dereq_('xhr');
var _xhr2 = _interopRequireDefault(_xhr);
// Include the built-in techs
var _techHtml5Js = _dereq_('./tech/html5.js');
var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js);
var _techFlashJs = _dereq_('./tech/flash.js');
var _techFlashJs2 = _interopRequireDefault(_techFlashJs);
// HTML5 Element Shim for IE8
if (typeof HTMLVideoElement === 'undefined') {
_globalDocument2['default'].createElement('video');
_globalDocument2['default'].createElement('audio');
_globalDocument2['default'].createElement('track');
}
/**
* Doubles as the main function for users to create a player instance and also
* the main library object.
* The `videojs` function can be used to initialize or retrieve a player.
* ```js
* var myPlayer = videojs('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
* @mixes videojs
* @method videojs
*/
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 (videojs.getPlayers()[id]) {
// If options or ready funtion are passed, warn
if (options) {
_utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.');
}
if (ready) {
videojs.getPlayers()[id].ready(ready);
}
return videojs.getPlayers()[id];
// Otherwise get element for ID
} else {
tag = Dom.getEl(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);
};
// Add default styles
var style = _globalDocument2['default'].querySelector('.vjs-styles-defaults');
if (!style) {
style = stylesheet.createStyleElement('vjs-styles-defaults');
var head = _globalDocument2['default'].querySelector('head');
head.insertBefore(style, head.firstChild);
stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n ');
}
// 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, videojs);
/*
* Current software version (semver)
*
* @type {String}
*/
videojs.VERSION = '5.0.0-rc.92';
/**
* The global options object. These are the settings that take effect
* if no overrides are specified when the player is created.
*
* ```js
* videojs.options.autoplay = true
* // -> all players will autoplay by default
* ```
*
* @type {Object}
*/
videojs.options = _player2['default'].prototype.options_;
/**
* Get an object with the currently created players, keyed by player ID
*
* @return {Object} The created players
* @mixes videojs
* @method getPlayers
*/
videojs.getPlayers = function () {
return _player2['default'].players;
};
/**
* For backward compatibility, expose players object.
*
* @deprecated
* @memberOf videojs
* @property {Object|Proxy} players
*/
videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, {
get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead',
set: 'Modification of videojs.players is deprecated'
});
/**
* Get a component class object by name
* ```js
* var VjsButton = videojs.getComponent('Button');
* // Create a new instance of the component
* var myButton = new VjsButton(myPlayer);
* ```
*
* @return {Component} Component identified by name
* @mixes videojs
* @method getComponent
*/
videojs.getComponent = _component2['default'].getComponent;
/**
* Register a component so it can referred to by name
* Used when adding to other
* components, either through addChild
* `component.addChild('myComponent')`
* or through default children options
* `{ children: ['myComponent'] }`.
* ```js
* // Get a component to subclass
* var VjsButton = videojs.getComponent('Button');
* // Subclass the component (see 'extends' doc for more info)
* var MySpecialButton = videojs.extends(VjsButton, {});
* // Register the new component
* VjsButton.registerComponent('MySepcialButton', MySepcialButton);
* // (optionally) add the new component as a default player child
* myPlayer.addChild('MySepcialButton');
* ```
* NOTE: You could also just initialize the component before adding.
* `component.addChild(new MyComponent());`
*
* @param {String} The class name of the component
* @param {Component} The component class
* @return {Component} The newly registered component
* @mixes videojs
* @method registerComponent
*/
videojs.registerComponent = _component2['default'].registerComponent;
/**
* A suite of browser and device tests
*
* @type {Object}
* @private
*/
videojs.browser = browser;
/**
* Whether or not the browser supports touch events. Included for backward
* compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED`
* instead going forward.
*
* @deprecated
* @type {Boolean}
*/
videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED;
/**
* Subclass an existing class
* Mimics ES6 subclassing with the `extends` keyword
* ```js
* // Create a basic javascript 'class'
* function MyClass(name){
* // Set a property at initialization
* this.myName = name;
* }
* // Create an instance method
* MyClass.prototype.sayMyName = function(){
* alert(this.myName);
* };
* // Subclass the exisitng class and change the name
* // when initializing
* var MySubClass = videojs.extends(MyClass, {
* constructor: function(name) {
* // Call the super class constructor for the subclass
* MyClass.call(this, name)
* }
* });
* // Create an instance of the new sub class
* var myInstance = new MySubClass('John');
* myInstance.sayMyName(); // -> should alert "John"
* ```
*
* @param {Function} The Class to subclass
* @param {Object} An object including instace methods for the new class
* Optionally including a `constructor` function
* @return {Function} The newly created subclass
* @mixes videojs
* @method extends
*/
videojs['extends'] = _extendsJs2['default'];
/**
* Merge two options objects recursively
* Performs a deep merge like lodash.merge but **only merges plain objects**
* (not arrays, elements, anything else)
* Other values will be copied directly from the second object.
* ```js
* var defaultOptions = {
* foo: true,
* bar: {
* a: true,
* b: [1,2,3]
* }
* };
* var newOptions = {
* foo: false,
* bar: {
* b: [4,5,6]
* }
* };
* var result = videojs.mergeOptions(defaultOptions, newOptions);
* // result.foo = false;
* // result.bar.a = true;
* // result.bar.b = [4,5,6];
* ```
*
* @param {Object} The options object whose values will be overriden
* @param {Object} The options object with values to override the first
* @param {Object} Any number of additional options objects
*
* @return {Object} a new object with the merged values
* @mixes videojs
* @method mergeOptions
*/
videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default'];
/**
* Change the context (this) of a function
*
* videojs.bind(newContext, function(){
* this === newContext
* });
*
* NOTE: as of v5.0 we require an ES5 shim, so you should use the native
* `function(){}.bind(newContext);` instead of this.
*
* @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}
*/
videojs.bind = Fn.bind;
/**
* Create a Video.js player plugin
* Plugins are only initialized when options for the plugin are included
* in the player options, or the plugin function on the player instance is
* called.
* **See the plugin guide in the docs for a more detailed example**
* ```js
* // Make a plugin that alerts when the player plays
* videojs.plugin('myPlugin', function(myPluginOptions) {
* myPluginOptions = myPluginOptions || {};
*
* var player = this;
* var alertText = myPluginOptions.text || 'Player is playing!'
*
* player.on('play', function(){
* alert(alertText);
* });
* });
* // USAGE EXAMPLES
* // EXAMPLE 1: New player with plugin options, call plugin immediately
* var player1 = videojs('idOne', {
* myPlugin: {
* text: 'Custom text!'
* }
* });
* // Click play
* // --> Should alert 'Custom text!'
* // EXAMPLE 3: New player, initialize plugin later
* var player3 = videojs('idThree');
* // Click play
* // --> NO ALERT
* // Click pause
* // Initialize plugin using the plugin function on the player instance
* player3.myPlugin({
* text: 'Plugin added later!'
* });
* // Click play
* // --> Should alert 'Plugin added later!'
* ```
*
* @param {String} The plugin name
* @param {Function} The plugin function that will be called with options
* @mixes videojs
* @method plugin
*/
videojs.plugin = _pluginsJs2['default'];
/**
* Adding languages so that they're available to all players.
* ```js
* 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 language dictionary object
* @mixes videojs
* @method addLanguage
*/
videojs.addLanguage = function (code, data) {
var _merge;
code = ('' + code).toLowerCase();
return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code];
};
/**
* Log debug messages.
*
* @param {...Object} messages One or more messages to log
*/
videojs.log = _utilsLogJs2['default'];
/**
* Creates an emulated TimeRange object.
*
* @param {Number} start Start time in seconds
* @param {Number} end End time in seconds
* @return {Object} Fake TimeRange object
* @method createTimeRange
*/
videojs.createTimeRange = _utilsTimeRangesJs.createTimeRange;
/**
* 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
* @method formatTime
*/
videojs.formatTime = _utilsFormatTimeJs2['default'];
/**
* Resolve and parse the elements of a URL
*
* @param {String} url The url to parse
* @return {Object} An object of url details
* @method parseUrl
*/
videojs.parseUrl = Url.parseUrl;
/**
* Event target class.
*
* @type {Function}
*/
videojs.EventTarget = _eventTarget2['default'];
/**
* 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.
* @method on
*/
videojs.on = Events.on;
/**
* Trigger a listener only once for an event
*
* @param {Element|Object} elem Element or object to
* @param {String|Array} type Name/type of event
* @param {Function} fn Event handler function
* @method one
*/
videojs.one = Events.one;
/**
* 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.
* @method off
*/
videojs.off = Events.off;
/**
* 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
* @param {Object} [hash] data hash to pass along with the event
* @return {Boolean=} Returned only if default was prevented
* @method trigger
*/
videojs.trigger = Events.trigger;
/**
* A cross-browser XMLHttpRequest wrapper. Here's a simple example:
*
* videojs.xhr({
* body: someJSONString,
* uri: "/foo",
* headers: {
* "Content-Type": "application/json"
* }
* }, function (err, resp, body) {
* // check resp.statusCode
* });
*
* Check out the [full
* documentation](https://github.com/Raynos/xhr/blob/v2.1.0/README.md)
* for more options.
*
* @param {Object} options settings for the request.
* @return {XMLHttpRequest|XDomainRequest} the request object.
* @see https://github.com/Raynos/xhr
*/
videojs.xhr = _xhr2['default'];
// REMOVING: We probably should add this to the migration plugin
// // Expose but deprecate the window[componentName] method for accessing components
// Object.getOwnPropertyNames(Component.components).forEach(function(name){
// let component = Component.components[name];
//
// // A deprecation warning as the constuctor
// module.exports[name] = function(player, options, ready){
// 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
// assign(module.exports[name], component);
// });
/*
* 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'];
},{"../../src/js/utils/merge-options.js":124,"./component":58,"./event-target":90,"./extends.js":91,"./player":98,"./plugins.js":99,"./setup":101,"./tech/flash.js":104,"./tech/html5.js":105,"./utils/browser.js":115,"./utils/create-deprecation-proxy.js":117,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/format-time.js":121,"./utils/log.js":123,"./utils/stylesheet.js":125,"./utils/time-ranges.js":126,"./utils/url.js":128,"global/document":1,"lodash-compat/object/merge":40,"object.assign":43,"xhr":50}]},{},[129])(129)
});
//# sourceMappingURL=video.js.map
|
node_modules/react-icons/md/picture-in-picture.js
|
bengimbel/Solstice-React-Contacts-Project
|
import React from 'react'
import Icon from 'react-icon-base'
const MdPictureInPicture = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m35 31.7v-23.4h-30v23.4h30z m0-26.7q1.3 0 2.3 1t1.1 2.4v23.2q0 1.4-1.1 2.4t-2.3 1h-30q-1.3 0-2.3-1t-1.1-2.4v-23.2q0-1.4 1.1-2.4t2.3-1h30z m-3.4 6.6v10h-13.2v-10h13.2z"/></g>
</Icon>
)
export default MdPictureInPicture
|
blueocean-material-icons/src/js/components/svg-icons/social/school.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialSchool = (props) => (
<SvgIcon {...props}>
<path d="M5 13.18v4L12 21l7-3.82v-4L12 17l-7-3.82zM12 3L1 9l11 6 9-4.91V17h2V9L12 3z"/>
</SvgIcon>
);
SocialSchool.displayName = 'SocialSchool';
SocialSchool.muiName = 'SvgIcon';
export default SocialSchool;
|
packages/my-joy-instances/src/components/create-instance/__tests__/images.spec.js
|
geek/joyent-portal
|
import React from 'react';
import renderer from 'react-test-renderer';
import 'jest-styled-components';
import Images from '../image';
import Theme from '@mocks/theme';
it('renders <Images /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Images expanded /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images expanded />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Images Images="test" /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images Images="[]" />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Images pristine={false} /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images pristine={false} />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Images images=[{name: stuff, imageName: stuff}] /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images images={[{ name: 'stuff', imageName: 'stuff' }]} />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Images loading /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images loading />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
it('renders <Images isVmSelected /> without throwing', () => {
expect(
renderer
.create(
<Theme>
<Images isVmSelected />
</Theme>
)
.toJSON()
).toMatchSnapshot();
});
|
ajax/libs/react-virtualized/7.0.0-rc.1/react-virtualized.min.js
|
dc-js/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.ReactVirtualized=t(require("react"),require("react-dom")):e.ReactVirtualized=t(e.React,e.ReactDOM)}(this,function(e,t){return function(e){function t(o){if(n[o])return n[o].exports;var r=n[o]={exports:{},id:o,loaded:!1};return e[o].call(r.exports,r,r.exports,t),r.loaded=!0,r.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var o=n(1);Object.defineProperty(t,"ArrowKeyStepper",{enumerable:!0,get:function(){return o.ArrowKeyStepper}});var r=n(7);Object.defineProperty(t,"AutoSizer",{enumerable:!0,get:function(){return r.AutoSizer}});var i=n(10);Object.defineProperty(t,"CellMeasurer",{enumerable:!0,get:function(){return i.CellMeasurer}});var a=n(160);Object.defineProperty(t,"Collection",{enumerable:!0,get:function(){return a.Collection}});var s=n(173);Object.defineProperty(t,"ColumnSizer",{enumerable:!0,get:function(){return s.ColumnSizer}});var l=n(182);Object.defineProperty(t,"FlexTable",{enumerable:!0,get:function(){return l.FlexTable}}),Object.defineProperty(t,"FlexColumn",{enumerable:!0,get:function(){return l.FlexColumn}}),Object.defineProperty(t,"SortDirection",{enumerable:!0,get:function(){return l.SortDirection}}),Object.defineProperty(t,"SortIndicator",{enumerable:!0,get:function(){return l.SortIndicator}});var u=n(175);Object.defineProperty(t,"Grid",{enumerable:!0,get:function(){return u.Grid}});var c=n(190);Object.defineProperty(t,"InfiniteLoader",{enumerable:!0,get:function(){return c.InfiniteLoader}});var d=n(192);Object.defineProperty(t,"ScrollSync",{enumerable:!0,get:function(){return d.ScrollSync}});var p=n(194);Object.defineProperty(t,"VirtualScroll",{enumerable:!0,get:function(){return p.VirtualScroll}})},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ArrowKeyStepper=t["default"]=void 0;var r=n(2),i=o(r);t["default"]=i["default"],t.ArrowKeyStepper=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}(),l=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),u=n(3),c=(o(u),n(4)),d=o(c),p=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={scrollToColumn:0,scrollToRow:0},o._columnStartIndex=0,o._columnStopIndex=0,o._rowStartIndex=0,o._rowStopIndex=0,o._onKeyDown=o._onKeyDown.bind(o),o._onSectionRendered=o._onSectionRendered.bind(o),o}return a(t,e),l(t,[{key:"render",value:function(){var e=this.props,t=e.className,n=e.children,o=this.state,r=o.scrollToColumn,i=o.scrollToRow;return s("div",{className:t,onKeyDown:this._onKeyDown},void 0,n({onSectionRendered:this._onSectionRendered,scrollToColumn:r,scrollToRow:i}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,d["default"])(this,e,t)}},{key:"_onKeyDown",value:function(e){var t=this.props,n=t.columnCount,o=t.rowCount;switch(e.key){case"ArrowDown":e.preventDefault(),this.setState({scrollToRow:Math.min(this._rowStopIndex+1,o-1)});break;case"ArrowLeft":e.preventDefault(),this.setState({scrollToColumn:Math.max(this._columnStartIndex-1,0)});break;case"ArrowRight":e.preventDefault(),this.setState({scrollToColumn:Math.min(this._columnStopIndex+1,n-1)});break;case"ArrowUp":e.preventDefault(),this.setState({scrollToRow:Math.max(this._rowStartIndex-1,0)})}}},{key:"_onSectionRendered",value:function(e){var t=e.columnStartIndex,n=e.columnStopIndex,o=e.rowStartIndex,r=e.rowStopIndex;this._columnStartIndex=t,this._columnStopIndex=n,this._rowStartIndex=o,this._rowStopIndex=r}}]),t}(u.Component);p.propTypes={children:u.PropTypes.func.isRequired,className:u.PropTypes.string,columnCount:u.PropTypes.number.isRequired,rowCount:u.PropTypes.number.isRequired},t["default"]=p},function(t,n){t.exports=e},function(e,t,n){e.exports=n(5)},function(e,t,n){"use strict";function o(e,t,n){return!r(e.props,t)||!r(e.state,n)}var r=n(6);e.exports=o},function(e,t){"use strict";function n(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var i=o.bind(t),a=0;a<n.length;a++)if(!i(n[a])||e[n[a]]!==t[n[a]])return!1;return!0}var o=Object.prototype.hasOwnProperty;e.exports=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.AutoSizer=t["default"]=void 0;var r=n(8),i=o(r);t["default"]=i["default"],t.AutoSizer=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(3),u=o(l),c=n(4),d=o(c),p=function(e){function t(e){r(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={height:0,width:0},n._onResize=n._onResize.bind(n),n._onScroll=n._onScroll.bind(n),n._setRef=n._setRef.bind(n),n}return a(t,e),s(t,[{key:"componentDidMount",value:function(){this._detectElementResize=n(9),this._detectElementResize.addResizeListener(this._parentNode,this._onResize),this._onResize()}},{key:"componentWillUnmount",value:function(){this._detectElementResize&&this._detectElementResize.removeResizeListener(this._parentNode,this._onResize)}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.disableHeight,o=e.disableWidth,r=this.state,i=r.height,a=r.width,s={overflow:"visible"};return n||(s.height=0),o||(s.width=0),u["default"].createElement("div",{ref:this._setRef,onScroll:this._onScroll,style:s},t({height:i,width:a}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,d["default"])(this,e,t)}},{key:"_onResize",value:function(){var e=this.props.onResize,t=this._parentNode.getBoundingClientRect(),n=t.height||0,o=t.width||0,r=getComputedStyle(this._parentNode),i=parseInt(r.paddingLeft,10)||0,a=parseInt(r.paddingRight,10)||0,s=parseInt(r.paddingTop,10)||0,l=parseInt(r.paddingBottom,10)||0;this.setState({height:n-s-l,width:o-i-a}),e({height:n,width:o})}},{key:"_onScroll",value:function(e){e.stopPropagation()}},{key:"_setRef",value:function(e){this._parentNode=e&&e.parentNode}}]),t}(l.Component);p.propTypes={children:l.PropTypes.func.isRequired,disableHeight:l.PropTypes.bool,disableWidth:l.PropTypes.bool,onResize:l.PropTypes.func.isRequired},p.defaultProps={onResize:function(){}},t["default"]=p},function(e,t){"use strict";var n;n="undefined"!=typeof window?window:"undefined"!=typeof self?self:void 0;var o="undefined"!=typeof document&&document.attachEvent,r=!1;if(!o){var i=function(){var e=n.requestAnimationFrame||n.mozRequestAnimationFrame||n.webkitRequestAnimationFrame||function(e){return n.setTimeout(e,20)};return function(t){return e(t)}}(),a=function(){var e=n.cancelAnimationFrame||n.mozCancelAnimationFrame||n.webkitCancelAnimationFrame||n.clearTimeout;return function(t){return e(t)}}(),s=function(e){var t=e.__resizeTriggers__,n=t.firstElementChild,o=t.lastElementChild,r=n.firstElementChild;o.scrollLeft=o.scrollWidth,o.scrollTop=o.scrollHeight,r.style.width=n.offsetWidth+1+"px",r.style.height=n.offsetHeight+1+"px",n.scrollLeft=n.scrollWidth,n.scrollTop=n.scrollHeight},l=function(e){return e.offsetWidth!=e.__resizeLast__.width||e.offsetHeight!=e.__resizeLast__.height},u=function(e){var t=this;s(this),this.__resizeRAF__&&a(this.__resizeRAF__),this.__resizeRAF__=i(function(){l(t)&&(t.__resizeLast__.width=t.offsetWidth,t.__resizeLast__.height=t.offsetHeight,t.__resizeListeners__.forEach(function(n){n.call(t,e)}))})},c=!1,d="animation",p="",f="animationstart",h="Webkit Moz O ms".split(" "),v="webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "),m="",y=document.createElement("fakeelement");if(void 0!==y.style.animationName&&(c=!0),c===!1)for(var g=0;g<h.length;g++)if(void 0!==y.style[h[g]+"AnimationName"]){m=h[g],d=m+"Animation",p="-"+m.toLowerCase()+"-",f=v[g],c=!0;break}var _="resizeanim",b="@"+p+"keyframes "+_+" { from { opacity: 0; } to { opacity: 0; } } ",E=p+"animation: 1ms "+_+"; "}var C=function(){if(!r){var e=(b?b:"")+".resize-triggers { "+(E?E:"")+'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }',t=document.head||document.getElementsByTagName("head")[0],n=document.createElement("style");n.type="text/css",n.styleSheet?n.styleSheet.cssText=e:n.appendChild(document.createTextNode(e)),t.appendChild(n),r=!0}},N=function(e,t){o?e.attachEvent("onresize",t):(e.__resizeTriggers__||("static"==getComputedStyle(e).position&&(e.style.position="relative"),C(),e.__resizeLast__={},e.__resizeListeners__=[],(e.__resizeTriggers__=document.createElement("div")).className="resize-triggers",e.__resizeTriggers__.innerHTML='<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>',e.appendChild(e.__resizeTriggers__),s(e),e.addEventListener("scroll",u,!0),f&&e.__resizeTriggers__.addEventListener(f,function(t){t.animationName==_&&s(e)})),e.__resizeListeners__.push(t))},w=function(e,t){o?e.detachEvent("onresize",t):(e.__resizeListeners__.splice(e.__resizeListeners__.indexOf(t),1),e.__resizeListeners__.length||(e.removeEventListener("scroll",u),e.__resizeTriggers__=!e.removeChild(e.__resizeTriggers__)))};e.exports={addResizeListener:N,removeResizeListener:w}},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.CellMeasurer=t["default"]=void 0;var r=n(11),i=o(r);t["default"]=i["default"],t.CellMeasurer=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(3),u=o(l),c=n(12),d=o(c),p=n(13),f=o(p),h=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._cachedColumnWidths={},o._cachedRowHeights={},o.getColumnWidth=o.getColumnWidth.bind(o),o.getRowHeight=o.getRowHeight.bind(o),o.resetMeasurements=o.resetMeasurements.bind(o),o}return a(t,e),s(t,[{key:"getColumnWidth",value:function(e){var t=e.index;if(this._cachedColumnWidths[t])return this._cachedColumnWidths[t];for(var n=this.props.rowCount,o=0,r=0;n>r;r++){var i=this._measureCell({clientWidth:!0,columnIndex:t,rowIndex:r}),a=i.width;o=Math.max(o,a)}return this._cachedColumnWidths[t]=o,o}},{key:"getRowHeight",value:function(e){var t=e.index;if(this._cachedRowHeights[t])return this._cachedRowHeights[t];for(var n=this.props.columnCount,o=0,r=0;n>r;r++){var i=this._measureCell({clientHeight:!0,columnIndex:r,rowIndex:t}),a=i.height;o=Math.max(o,a)}return this._cachedRowHeights[t]=o,o}},{key:"resetMeasurements",value:function(){this._cachedColumnWidths={},this._cachedRowHeights={}}},{key:"componentDidMount",value:function(){this._renderAndMount()}},{key:"componentWillReceiveProps",value:function(e){this._updateDivDimensions(e)}},{key:"componentWillUnmount",value:function(){this._unmountContainer()}},{key:"render",value:function(){var e=this.props.children;return e({getColumnWidth:this.getColumnWidth,getRowHeight:this.getRowHeight,resetMeasurements:this.resetMeasurements})}},{key:"_getContainerNode",value:function(e){var t=e.container;if(t)return d["default"].findDOMNode("function"==typeof t?t():t);var n=d["default"].findDOMNode(this);return n.ownerDocument.body}},{key:"_measureCell",value:function(e){var t=e.clientHeight,n=void 0===t?!1:t,o=e.clientWidth,r=void 0===o?!0:o,i=e.columnIndex,a=e.rowIndex,s=this.props.cellRenderer,l=s({columnIndex:i,rowIndex:a});return this._div.innerHTML=f["default"].renderToString(l),{height:n&&this._div.clientHeight,width:r&&this._div.clientWidth}}},{key:"_renderAndMount",value:function(){this._div||(this._div=document.createElement("div"),this._div.style.display="inline-block",this._div.style.position="absolute",this._div.style.visibility="hidden",this._div.style.zIndex=-1,this._updateDivDimensions(this.props),this._containerNode=this._getContainerNode(this.props),this._containerNode.appendChild(this._div))}},{key:"_unmountContainer",value:function(){this._div&&(this._containerNode.removeChild(this._div),this._div=null),this._containerNode=null}},{key:"_updateDivDimensions",value:function(e){var t=e.height,n=e.width;t&&t!==this._divHeight&&(this._divHeight=t,this._div.style.height=t+"px"),n&&n!==this._divWidth&&(this._divWidth=n,this._div.style.width=n+"px")}}]),t}(l.Component);h.propTypes={cellRenderer:l.PropTypes.func.isRequired,children:l.PropTypes.func.isRequired,columnCount:l.PropTypes.number.isRequired,container:u["default"].PropTypes.oneOfType([u["default"].PropTypes.func,u["default"].PropTypes.node]),height:l.PropTypes.number,rowCount:l.PropTypes.number.isRequired,width:l.PropTypes.number},t["default"]=h},function(e,n){e.exports=t},function(e,t,n){"use strict";e.exports=n(14)},function(e,t,n){"use strict";var o=n(15),r=n(156),i=n(159);o.inject();var a={renderToString:r.renderToString,renderToStaticMarkup:r.renderToStaticMarkup,version:i};e.exports=a},function(e,t,n){(function(t){"use strict";function o(){if(!S&&(S=!0,y.EventEmitter.injectReactEventListener(m),y.EventPluginHub.injectEventPluginOrder(s),y.EventPluginHub.injectInstanceHandle(g),y.EventPluginHub.injectMount(_),y.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:N,EnterLeaveEventPlugin:l,ChangeEventPlugin:i,SelectEventPlugin:E,BeforeInputEventPlugin:r}),y.NativeComponent.injectGenericComponentClass(h),y.NativeComponent.injectTextComponentClass(v),y.Class.injectMixin(d),y.DOMProperty.injectDOMPropertyConfig(c),y.DOMProperty.injectDOMPropertyConfig(w),y.EmptyComponent.injectEmptyComponent("noscript"),y.Updates.injectReconcileTransaction(b),y.Updates.injectBatchingStrategy(f),y.RootIndex.injectCreateReactRootIndex(u.canUseDOM?a.createReactRootIndex:C.createReactRootIndex),y.Component.injectEnvironment(p),"production"!==t.env.NODE_ENV)){var e=u.canUseDOM&&window.location.href||"";if(/[?&]react_perf\b/.test(e)){var o=n(152);o.start()}}}var r=n(17),i=n(39),a=n(50),s=n(51),l=n(52),u=n(30),c=n(86),d=n(87),p=n(89),f=n(102),h=n(103),v=n(127),m=n(128),y=n(131),g=n(66),_=n(57),b=n(135),E=n(140),C=n(141),N=n(142),w=n(151),S=!1;e.exports={inject:o}}).call(t,n(16))},function(e,t){function n(){u=!1,a.length?l=a.concat(l):c=-1,l.length&&o()}function o(){if(!u){var e=setTimeout(n);u=!0;for(var t=l.length;t;){for(a=l,l=[];++c<t;)a&&a[c].run();c=-1,t=l.length}a=null,u=!1,clearTimeout(e)}}function r(e,t){this.fun=e,this.array=t}function i(){}var a,s=e.exports={},l=[],u=!1,c=-1;s.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)t[n-1]=arguments[n];l.push(new r(e,t)),1!==l.length||u||setTimeout(o,0)},r.prototype.run=function(){this.fun.apply(null,this.array)},s.title="browser",s.browser=!0,s.env={},s.argv=[],s.version="",s.versions={},s.on=i,s.addListener=i,s.once=i,s.off=i,s.removeListener=i,s.removeAllListeners=i,s.emit=i,s.binding=function(e){throw new Error("process.binding is not supported")},s.cwd=function(){return"/"},s.chdir=function(e){throw new Error("process.chdir is not supported")},s.umask=function(){return 0}},function(e,t,n){"use strict";function o(){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 i(e){switch(e){case O.topCompositionStart:return T.compositionStart;case O.topCompositionEnd:return T.compositionEnd;case O.topCompositionUpdate:return T.compositionUpdate}}function a(e,t){return e===O.topKeyDown&&t.keyCode===E}function s(e,t){switch(e){case O.topKeyUp:return-1!==b.indexOf(t.keyCode);case O.topKeyDown:return t.keyCode!==E;case O.topKeyPress:case O.topMouseDown:case O.topBlur:return!0;default:return!1}}function l(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function u(e,t,n,o,r){var u,c;if(C?u=i(e):R?s(e,o)&&(u=T.compositionEnd):a(e,o)&&(u=T.compositionStart),!u)return null;S&&(R||u!==T.compositionStart?u===T.compositionEnd&&R&&(c=R.getData()):R=m.getPooled(t));var d=y.getPooled(u,n,o,r);if(c)d.data=c;else{var p=l(o);null!==p&&(d.data=p)}return h.accumulateTwoPhaseDispatches(d),d}function c(e,t){switch(e){case O.topCompositionEnd:return l(t);case O.topKeyPress:var n=t.which;return n!==x?null:(P=!0,D);case O.topTextInput:var o=t.data;return o===D&&P?null:o;default:return null}}function d(e,t){if(R){if(e===O.topCompositionEnd||s(e,t)){var n=R.getData();return m.release(R),R=null,n}return null}switch(e){case O.topPaste:return null;case O.topKeyPress:return t.which&&!r(t)?String.fromCharCode(t.which):null;case O.topCompositionEnd:return S?null:t.data;default:return null}}function p(e,t,n,o,r){var i;if(i=w?c(e,o):d(e,o),!i)return null;var a=g.getPooled(T.beforeInput,n,o,r);return a.data=i,h.accumulateTwoPhaseDispatches(a),a}var f=n(18),h=n(21),v=n(30),m=n(31),y=n(35),g=n(37),_=n(38),b=[9,13,27,32],E=229,C=v.canUseDOM&&"CompositionEvent"in window,N=null;v.canUseDOM&&"documentMode"in document&&(N=document.documentMode);var w=v.canUseDOM&&"TextEvent"in window&&!N&&!o(),S=v.canUseDOM&&(!C||N&&N>8&&11>=N),x=32,D=String.fromCharCode(x),O=f.topLevelTypes,T={beforeInput:{phasedRegistrationNames:{bubbled:_({onBeforeInput:null}),captured:_({onBeforeInputCapture:null})},dependencies:[O.topCompositionEnd,O.topKeyPress,O.topTextInput,O.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:_({onCompositionEnd:null}),captured:_({onCompositionEndCapture:null})},dependencies:[O.topBlur,O.topCompositionEnd,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:_({onCompositionStart:null}),captured:_({onCompositionStartCapture:null})},dependencies:[O.topBlur,O.topCompositionStart,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:_({onCompositionUpdate:null}),captured:_({onCompositionUpdateCapture:null})},dependencies:[O.topBlur,O.topCompositionUpdate,O.topKeyDown,O.topKeyPress,O.topKeyUp,O.topMouseDown]}},P=!1,R=null,M={eventTypes:T,extractEvents:function(e,t,n,o,r){return[u(e,t,n,o,r),p(e,t,n,o,r)]}};e.exports=M},function(e,t,n){"use strict";var o=n(19),r=o({bubbled:null,captured:null}),i=o({topAbort:null,topBlur:null,topCanPlay:null,topCanPlayThrough: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,topDurationChange:null,topEmptied:null,topEncrypted:null,topEnded:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topLoadedData:null,topLoadedMetadata:null,topLoadStart:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topPause:null,topPlay:null,topPlaying:null,topProgress:null,topRateChange:null,topReset:null,topScroll:null,topSeeked:null,topSeeking:null,topSelectionChange:null,topStalled:null,topSubmit:null,topSuspend:null,topTextInput:null,topTimeUpdate:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topVolumeChange:null,topWaiting:null,topWheel:null}),a={topLevelTypes:i,PropagationPhases:r};e.exports=a},function(e,t,n){(function(t){"use strict";var o=n(20),r=function(e){var n,r={};e instanceof Object&&!Array.isArray(e)?void 0:"production"!==t.env.NODE_ENV?o(!1,"keyMirror(...): Argument must be an object."):o(!1);for(n in e)e.hasOwnProperty(n)&&(r[n]=n);return r};e.exports=r}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function n(e,n,o,r,i,a,s,l){if("production"!==t.env.NODE_ENV&&void 0===n)throw new Error("invariant requires an error message argument");if(!e){var u;if(void 0===n)u=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[o,r,i,a,s,l],d=0;u=new Error(n.replace(/%s/g,function(){return c[d++]})),u.name="Invariant Violation"}throw u.framesToPop=1,u}}e.exports=n}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,t,n){var o=t.dispatchConfig.phasedRegistrationNames[n];return _(e,o)}function r(e,n,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?v(e,"Dispatching id must not be null"):void 0);var i=n?g.bubbled:g.captured,a=o(e,r,i);a&&(r._dispatchListeners=m(r._dispatchListeners,a),r._dispatchIDs=m(r._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,r,e)}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,r,e)}function s(e,t,n){if(n&&n.dispatchConfig.registrationName){var o=n.dispatchConfig.registrationName,r=_(e,o);r&&(n._dispatchListeners=m(n._dispatchListeners,r),n._dispatchIDs=m(n._dispatchIDs,e))}}function l(e){e&&e.dispatchConfig.registrationName&&s(e.dispatchMarker,null,e)}function u(e){y(e,i)}function c(e){y(e,a)}function d(e,t,n,o){h.injection.getInstanceHandle().traverseEnterLeave(n,o,s,e,t)}function p(e){y(e,l)}var f=n(18),h=n(22),v=n(26),m=n(28),y=n(29),g=f.PropagationPhases,_=h.getListener,b={accumulateTwoPhaseDispatches:u,accumulateTwoPhaseDispatchesSkipTarget:c,accumulateDirectDispatches:p,accumulateEnterLeaveDispatches:d};e.exports=b}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(){var e=m&&m.traverseTwoPhase&&m.traverseEnterLeave;"production"!==t.env.NODE_ENV?c(e,"InstanceHandle not injected before use!"):void 0}var r=n(23),i=n(24),a=n(25),s=n(28),l=n(29),u=n(20),c=n(26),d={},p=null,f=function(e,t){e&&(i.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e))},h=function(e){return f(e,!0)},v=function(e){return f(e,!1)},m=null,y={injection:{injectMount:i.injection.injectMount,injectInstanceHandle:function(e){m=e,"production"!==t.env.NODE_ENV&&o()},getInstanceHandle:function(){return"production"!==t.env.NODE_ENV&&o(),m},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,n,o){"function"!=typeof o?"production"!==t.env.NODE_ENV?u(!1,"Expected %s listener to be a function, instead got type %s",n,typeof o):u(!1):void 0;var i=d[n]||(d[n]={});i[e]=o;var a=r.registrationNameModules[n];a&&a.didPutListener&&a.didPutListener(e,n,o)},getListener:function(e,t){var n=d[t];return n&&n[e]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=d[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in d)if(d[t][e]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete d[t][e]}},extractEvents:function(e,t,n,o,i){for(var a,l=r.plugins,u=0;u<l.length;u++){var c=l[u];if(c){var d=c.extractEvents(e,t,n,o,i);d&&(a=s(a,d))}}return a},enqueueEvents:function(e){e&&(p=s(p,e))},processEventQueue:function(e){var n=p;p=null,e?l(n,h):l(n,v),p?"production"!==t.env.NODE_ENV?u(!1,"processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented."):u(!1):void 0,a.rethrowCaughtError()},__purge:function(){d={}},__getListenerBank:function(){return d}};e.exports=y}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(){if(s)for(var e in l){var n=l[e],o=s.indexOf(e);if(o>-1?void 0:"production"!==t.env.NODE_ENV?a(!1,"EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.",e):a(!1),!u.plugins[o]){n.extractEvents?void 0:"production"!==t.env.NODE_ENV?a(!1,"EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.",e):a(!1),u.plugins[o]=n;var i=n.eventTypes;for(var c in i)r(i[c],n,c)?void 0:"production"!==t.env.NODE_ENV?a(!1,"EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.",c,e):a(!1)}}}function r(e,n,o){u.eventNameDispatchConfigs.hasOwnProperty(o)?"production"!==t.env.NODE_ENV?a(!1,"EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.",o):a(!1):void 0,u.eventNameDispatchConfigs[o]=e;var r=e.phasedRegistrationNames;if(r){for(var s in r)if(r.hasOwnProperty(s)){var l=r[s];i(l,n,o)}return!0}return e.registrationName?(i(e.registrationName,n,o),!0):!1}function i(e,n,o){u.registrationNameModules[e]?"production"!==t.env.NODE_ENV?a(!1,"EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.",e):a(!1):void 0,u.registrationNameModules[e]=n,u.registrationNameDependencies[e]=n.eventTypes[o].dependencies}var a=n(20),s=null,l={},u={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){s?"production"!==t.env.NODE_ENV?a(!1,"EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React."):a(!1):void 0,s=Array.prototype.slice.call(e),o()},injectEventPluginsByName:function(e){var n=!1;for(var r in e)if(e.hasOwnProperty(r)){var i=e[r];l.hasOwnProperty(r)&&l[r]===i||(l[r]?"production"!==t.env.NODE_ENV?a(!1,"EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.",r):a(!1):void 0,l[r]=i,n=!0)}n&&o()},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 o=u.registrationNameModules[t.phasedRegistrationNames[n]];if(o)return o}return null},_resetEventPlugins:function(){s=null;for(var e in l)l.hasOwnProperty(e)&&delete l[e];u.plugins.length=0;var t=u.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var o=u.registrationNameModules;for(var r in o)o.hasOwnProperty(r)&&delete o[r]}};e.exports=u}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){return e===g.topMouseUp||e===g.topTouchEnd||e===g.topTouchCancel}function r(e){return e===g.topMouseMove||e===g.topTouchMove}function i(e){return e===g.topMouseDown||e===g.topTouchStart}function a(e,t,n,o){var r=e.type||"unknown-event";e.currentTarget=y.Mount.getNode(o),t?h.invokeGuardedCallbackWithCatch(r,n,e,o):h.invokeGuardedCallback(r,n,e,o),e.currentTarget=null}function s(e,n){var o=e._dispatchListeners,r=e._dispatchIDs;if("production"!==t.env.NODE_ENV&&p(e),Array.isArray(o))for(var i=0;i<o.length&&!e.isPropagationStopped();i++)a(e,n,o[i],r[i]);else o&&a(e,n,o,r);e._dispatchListeners=null,e._dispatchIDs=null}function l(e){var n=e._dispatchListeners,o=e._dispatchIDs;if("production"!==t.env.NODE_ENV&&p(e),Array.isArray(n)){for(var r=0;r<n.length&&!e.isPropagationStopped();r++)if(n[r](e,o[r]))return o[r]}else if(n&&n(e,o))return o;return null}function u(e){var t=l(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function c(e){"production"!==t.env.NODE_ENV&&p(e);var n=e._dispatchListeners,o=e._dispatchIDs;Array.isArray(n)?"production"!==t.env.NODE_ENV?v(!1,"executeDirectDispatch(...): Invalid `event`."):v(!1):void 0;var r=n?n(e,o):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function d(e){return!!e._dispatchListeners}var p,f=n(18),h=n(25),v=n(20),m=n(26),y={Mount:null,injectMount:function(e){y.Mount=e,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?m(e&&e.getNode&&e.getID,"EventPluginUtils.injection.injectMount(...): Injected Mount module is missing getNode or getID."):void 0)}},g=f.topLevelTypes;"production"!==t.env.NODE_ENV&&(p=function(e){var n=e._dispatchListeners,o=e._dispatchIDs,r=Array.isArray(n),i=Array.isArray(o),a=i?o.length:o?1:0,s=r?n.length:n?1:0;"production"!==t.env.NODE_ENV?m(i===r&&a===s,"EventPluginUtils: Invalid `event`."):void 0});var _={isEndish:o,isMoveish:r,isStartish:i,executeDirectDispatch:c,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:u,hasDispatches:d,getNode:function(e){return y.Mount.getNode(e)},getID:function(e){return y.Mount.getID(e)},injection:y};e.exports=_}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function n(e,t,n,r){try{return t(n,r)}catch(i){return void(null===o&&(o=i))}}var o=null,r={invokeGuardedCallback:n,invokeGuardedCallbackWithCatch:n,rethrowCaughtError:function(){if(o){var e=o;throw o=null,e}}};if("production"!==t.env.NODE_ENV&&"undefined"!=typeof window&&"function"==typeof window.dispatchEvent&&"undefined"!=typeof document&&"function"==typeof document.createEvent){var i=document.createElement("react");r.invokeGuardedCallback=function(e,t,n,o){var r=t.bind(null,n,o),a="react-"+e;
i.addEventListener(a,r,!1);var s=document.createEvent("Event");s.initEvent(a,!1,!1),i.dispatchEvent(s),i.removeEventListener(a,r,!1)}}e.exports=r}).call(t,n(16))},function(e,t,n){(function(t){"use strict";var o=n(27),r=o;"production"!==t.env.NODE_ENV&&(r=function(e,t){for(var n=arguments.length,o=Array(n>2?n-2:0),r=2;n>r;r++)o[r-2]=arguments[r];if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(0!==t.indexOf("Failed Composite propType: ")&&!e){var i=0,a="Warning: "+t.replace(/%s/g,function(){return o[i++]});"undefined"!=typeof console&&console.error(a);try{throw new Error(a)}catch(s){}}}),e.exports=r}).call(t,n(16))},function(e,t){"use strict";function n(e){return function(){return e}}function o(){}o.thatReturns=n,o.thatReturnsFalse=n(!1),o.thatReturnsTrue=n(!0),o.thatReturnsNull=n(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,n){(function(t){"use strict";function o(e,n){if(null==n?"production"!==t.env.NODE_ENV?r(!1,"accumulateInto(...): Accumulated items must not be null or undefined."):r(!1):void 0,null==e)return n;var o=Array.isArray(e),i=Array.isArray(n);return o&&i?(e.push.apply(e,n),e):o?(e.push(n),e):i?[e].concat(n):[e,n]}var r=n(20);e.exports=o}).call(t,n(16))},function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};e.exports=n},function(e,t){"use strict";var n=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:n,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:n&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:n&&!!window.screen,isInWorker:!n};e.exports=o},function(e,t,n){"use strict";function o(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var r=n(32),i=n(33),a=n(34);i(o.prototype,{destructor:function(){this._root=null,this._startText=null,this._fallbackText=null},getText:function(){return"value"in this._root?this._root.value:this._root[a()]},getData:function(){if(this._fallbackText)return this._fallbackText;var e,t,n=this._startText,o=n.length,r=this.getText(),i=r.length;for(e=0;o>e&&n[e]===r[e];e++);var a=o-e;for(t=1;a>=t&&n[o-t]===r[i-t];t++);var s=t>1?1-t:void 0;return this._fallbackText=r.slice(e,s),this._fallbackText}}),r.addPoolingTo(o),e.exports=o},function(e,t,n){(function(t){"use strict";var o=n(20),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)},i=function(e,t){var n=this;if(n.instancePool.length){var o=n.instancePool.pop();return n.call(o,e,t),o}return new n(e,t)},a=function(e,t,n){var o=this;if(o.instancePool.length){var r=o.instancePool.pop();return o.call(r,e,t,n),r}return new o(e,t,n)},s=function(e,t,n,o){var r=this;if(r.instancePool.length){var i=r.instancePool.pop();return r.call(i,e,t,n,o),i}return new r(e,t,n,o)},l=function(e,t,n,o,r){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,o,r),a}return new i(e,t,n,o,r)},u=function(e){var n=this;e instanceof n?void 0:"production"!==t.env.NODE_ENV?o(!1,"Trying to release an instance into a pool of a different type."):o(!1),e.destructor(),n.instancePool.length<n.poolSize&&n.instancePool.push(e)},c=10,d=r,p=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||d,n.poolSize||(n.poolSize=c),n.release=u,n},f={addPoolingTo:p,oneArgumentPooler:r,twoArgumentPooler:i,threeArgumentPooler:a,fourArgumentPooler:s,fiveArgumentPooler:l};e.exports=f}).call(t,n(16))},function(e,t){"use strict";function n(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),o=Object.prototype.hasOwnProperty,r=1;r<arguments.length;r++){var i=arguments[r];if(null!=i){var a=Object(i);for(var s in a)o.call(a,s)&&(n[s]=a[s])}}return n}e.exports=n},function(e,t,n){"use strict";function o(){return!i&&r.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var r=n(30),i=null;e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(36),i={data:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){(function(t){"use strict";function o(e,t,n,o){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var i in r)if(r.hasOwnProperty(i)){var s=r[i];s?this[i]=s(n):"target"===i?this.target=o:this[i]=n[i]}var l=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;l?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var r=n(32),i=n(33),a=n(27),s=n(26),l={type:null,target:null,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(o.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?s(e,"This synthetic event is reused for performance reasons. If you're seeing this, you're calling `preventDefault` on a released/nullified synthetic event. This is a no-op. See https://fb.me/react-event-pooling for more information."):void 0),e&&(e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue)},stopPropagation:function(){var e=this.nativeEvent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?s(e,"This synthetic event is reused for performance reasons. If you're seeing this, you're calling `stopPropagation` on a released/nullified synthetic event. This is a no-op. See https://fb.me/react-event-pooling for more information."):void 0),e&&(e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=a.thatReturnsTrue)},persist:function(){this.isPersistent=a.thatReturnsTrue},isPersistent:a.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}}),o.Interface=l,o.augmentClass=function(e,t){var n=this,o=Object.create(n.prototype);i(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.fourArgumentPooler)},r.addPoolingTo(o,r.fourArgumentPooler),e.exports=o}).call(t,n(16))},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(36),i={data:null};r.augmentClass(o,i),e.exports=o},function(e,t){"use strict";var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=n},function(e,t,n){"use strict";function o(e){var t=e.nodeName&&e.nodeName.toLowerCase();return"select"===t||"input"===t&&"file"===e.type}function r(e){var t=N.getPooled(T.change,R,e,w(e));b.accumulateTwoPhaseDispatches(t),C.batchedUpdates(i,t)}function i(e){_.enqueueEvents(e),_.processEventQueue(!1)}function a(e,t){P=e,R=t,P.attachEvent("onchange",r)}function s(){P&&(P.detachEvent("onchange",r),P=null,R=null)}function l(e,t,n){return e===O.topChange?n:void 0}function u(e,t,n){e===O.topFocus?(s(),a(t,n)):e===O.topBlur&&s()}function c(e,t){P=e,R=t,M=e.value,I=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(P,"value",V),P.attachEvent("onpropertychange",p)}function d(){P&&(delete P.value,P.detachEvent("onpropertychange",p),P=null,R=null,M=null,I=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==M&&(M=t,r(e))}}function f(e,t,n){return e===O.topInput?n:void 0}function h(e,t,n){e===O.topFocus?(d(),c(t,n)):e===O.topBlur&&d()}function v(e,t,n){return e!==O.topSelectionChange&&e!==O.topKeyUp&&e!==O.topKeyDown||!P||P.value===M?void 0:(M=P.value,R)}function m(e){return e.nodeName&&"input"===e.nodeName.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)}function y(e,t,n){return e===O.topClick?n:void 0}var g=n(18),_=n(22),b=n(21),E=n(30),C=n(40),N=n(36),w=n(47),S=n(48),x=n(49),D=n(38),O=g.topLevelTypes,T={change:{phasedRegistrationNames:{bubbled:D({onChange:null}),captured:D({onChangeCapture:null})},dependencies:[O.topBlur,O.topChange,O.topClick,O.topFocus,O.topInput,O.topKeyDown,O.topKeyUp,O.topSelectionChange]}},P=null,R=null,M=null,I=null,k=!1;E.canUseDOM&&(k=S("change")&&(!("documentMode"in document)||document.documentMode>8));var A=!1;E.canUseDOM&&(A=S("input")&&(!("documentMode"in document)||document.documentMode>9));var V={get:function(){return I.get.call(this)},set:function(e){M=""+e,I.set.call(this,e)}},L={eventTypes:T,extractEvents:function(e,t,n,r,i){var a,s;if(o(t)?k?a=l:s=u:x(t)?A?a=f:(a=v,s=h):m(t)&&(a=y),a){var c=a(e,t,n);if(c){var d=N.getPooled(T.change,c,r,i);return d.type="change",b.accumulateTwoPhaseDispatches(d),d}}s&&s(e,t,n)}};e.exports=L},function(e,t,n){(function(t){"use strict";function o(){x.ReactReconcileTransaction&&b?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must inject a reconcile transaction class and batching strategy"):m(!1)}function r(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=x.ReactReconcileTransaction.getPooled(!1)}function i(e,t,n,r,i,a){o(),b.batchedUpdates(e,t,n,r,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function s(e){var n=e.dirtyComponentsLength;n!==y.length?"production"!==t.env.NODE_ENV?m(!1,"Expected flush transaction's stored dirty-components length (%s) to match dirty-components array length (%s).",n,y.length):m(!1):void 0,y.sort(a);for(var o=0;n>o;o++){var r=y[o],i=r._pendingCallbacks;if(r._pendingCallbacks=null,f.performUpdateIfNecessary(r,e.reconcileTransaction),i)for(var s=0;s<i.length;s++)e.callbackQueue.enqueue(i[s],r.getPublicInstance())}}function l(e){return o(),b.isBatchingUpdates?void y.push(e):void b.batchedUpdates(l,e)}function u(e,n){b.isBatchingUpdates?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates.asap: Can't enqueue an asap callback in a context whereupdates are not being batched."):m(!1),g.enqueue(e,n),_=!0}var c=n(41),d=n(32),p=n(42),f=n(43),h=n(46),v=n(33),m=n(20),y=[],g=c.getPooled(),_=!1,b=null,E={initialize:function(){this.dirtyComponentsLength=y.length},close:function(){this.dirtyComponentsLength!==y.length?(y.splice(0,this.dirtyComponentsLength),w()):y.length=0}},C={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},N=[E,C];v(r.prototype,h.Mixin,{getTransactionWrappers:function(){return N},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,x.ReactReconcileTransaction.release(this.reconcileTransaction),this.reconcileTransaction=null},perform:function(e,t,n){return h.Mixin.perform.call(this,this.reconcileTransaction.perform,this.reconcileTransaction,e,t,n)}}),d.addPoolingTo(r);var w=function(){for(;y.length||_;){if(y.length){var e=r.getPooled();e.perform(s,null,e),r.release(e)}if(_){_=!1;var t=g;g=c.getPooled(),t.notifyAll(),c.release(t)}}};w=p.measure("ReactUpdates","flushBatchedUpdates",w);var S={injectReconcileTransaction:function(e){e?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide a reconcile transaction class"):m(!1),x.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){e?void 0:"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide a batching strategy"):m(!1),"function"!=typeof e.batchedUpdates?"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide a batchedUpdates() function"):m(!1):void 0,"boolean"!=typeof e.isBatchingUpdates?"production"!==t.env.NODE_ENV?m(!1,"ReactUpdates: must provide an isBatchingUpdates boolean attribute"):m(!1):void 0,b=e}},x={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:l,flushBatchedUpdates:w,injection:S,asap:u};e.exports=x}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(){this._callbacks=null,this._contexts=null}var r=n(32),i=n(33),a=n(20);i(o.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,n=this._contexts;if(e){e.length!==n.length?"production"!==t.env.NODE_ENV?a(!1,"Mismatched list of contexts in callback queue"):a(!1):void 0,this._callbacks=null,this._contexts=null;for(var o=0;o<e.length;o++)e[o].call(n[o]);e.length=0,n.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),r.addPoolingTo(o),e.exports=o}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function n(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:n,measureMethods:function(e,n,r){if("production"!==t.env.NODE_ENV)for(var i in r)r.hasOwnProperty(i)&&(e[i]=o.measure(n,r[i],e[i]))},measure:function(e,n,r){if("production"!==t.env.NODE_ENV){var i=null,a=function(){return o.enableMeasure?(i||(i=o.storedMeasure(e,n,r)),i.apply(this,arguments)):r.apply(this,arguments)};return a.displayName=e+"_"+n,a}return r},injection:{injectMeasure:function(e){o.storedMeasure=e}}};e.exports=o}).call(t,n(16))},function(e,t,n){"use strict";function o(){r.attachRefs(this,this._currentElement)}var r=n(44),i={mountComponent:function(e,t,n,r){var i=e.mountComponent(t,n,r);return e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(o,e),i},unmountComponent:function(e){r.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||i!==e._context){var s=r.shouldUpdateRefs(a,t);s&&r.detachRefs(e,a),e.receiveComponent(t,n,i),s&&e._currentElement&&null!=e._currentElement.ref&&n.getReactMountReady().enqueue(o,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}};e.exports=i},function(e,t,n){"use strict";function o(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function r(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=n(45),a={};a.attachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&o(n,e,t._owner)}},a.shouldUpdateRefs=function(e,t){var n=null===e||e===!1,o=null===t||t===!1;return n||o||t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){if(null!==t&&t!==!1){var n=t.ref;null!=n&&r(n,e,t._owner)}},e.exports=a},function(e,t,n){(function(t){"use strict";var o=n(20),r={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,n,i){r.isValidOwner(i)?void 0:"production"!==t.env.NODE_ENV?o(!1,"addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner)."):o(!1),i.attachRef(n,e)},removeComponentAsRefFrom:function(e,n,i){r.isValidOwner(i)?void 0:"production"!==t.env.NODE_ENV?o(!1,"removeComponentAsRefFrom(...): Only a ReactOwner can have refs. You might be removing a ref to a component that was not created inside a component's `render` method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner)."):o(!1),i.getPublicInstance().refs[n]===e.getPublicInstance()&&i.detachRef(n)}};e.exports=r}).call(t,n(16))},function(e,t,n){(function(t){"use strict";var o=n(20),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,n,r,i,a,s,l,u){this.isInTransaction()?"production"!==t.env.NODE_ENV?o(!1,"Transaction.perform(...): Cannot initialize a transaction when there is already an outstanding transaction."):o(!1):void 0;var c,d;try{this._isInTransaction=!0,c=!0,this.initializeAll(0),d=e.call(n,r,i,a,s,l,u),c=!1}finally{try{if(c)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return d},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=o.initialize?o.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(r){}}}},closeAll:function(e){this.isInTransaction()?void 0:"production"!==t.env.NODE_ENV?o(!1,"Transaction.closeAll(): Cannot close transaction when none are open."):o(!1);for(var n=this.transactionWrappers,r=e;r<n.length;r++){var a,s=n[r],l=this.wrapperInitData[r];try{a=!0,l!==i.OBSERVED_ERROR&&s.close&&s.close.call(this,l),a=!1}finally{if(a)try{this.closeAll(r+1)}catch(u){}}}this.wrapperInitData.length=0}},i={Mixin:r,OBSERVED_ERROR:{}};e.exports=i}).call(t,n(16))},function(e,t){"use strict";function n(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}e.exports=n},function(e,t,n){"use strict";function o(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,o=n in document;if(!o){var a=document.createElement("div");a.setAttribute(n,"return;"),o="function"==typeof a[n]}return!o&&r&&"wheel"===e&&(o=document.implementation.hasFeature("Events.wheel","3.0")),o}var r,i=n(30);i.canUseDOM&&(r=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),e.exports=o},function(e,t){"use strict";function n(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&o[e.type]||"textarea"===t)}var o={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};e.exports=n},function(e,t){"use strict";var n=0,o={createReactRootIndex:function(){return n++}};e.exports=o},function(e,t,n){"use strict";var o=n(38),r=[o({ResponderEventPlugin:null}),o({SimpleEventPlugin:null}),o({TapEventPlugin:null}),o({EnterLeaveEventPlugin:null}),o({ChangeEventPlugin:null}),o({SelectEventPlugin:null}),o({BeforeInputEventPlugin:null})];e.exports=r},function(e,t,n){"use strict";var o=n(18),r=n(21),i=n(53),a=n(57),s=n(38),l=o.topLevelTypes,u=a.getFirstReactDOM,c={mouseEnter:{registrationName:s({onMouseEnter:null}),dependencies:[l.topMouseOut,l.topMouseOver]},mouseLeave:{registrationName:s({onMouseLeave:null}),dependencies:[l.topMouseOut,l.topMouseOver]}},d=[null,null],p={eventTypes:c,extractEvents:function(e,t,n,o,s){if(e===l.topMouseOver&&(o.relatedTarget||o.fromElement))return null;if(e!==l.topMouseOut&&e!==l.topMouseOver)return null;var p;if(t.window===t)p=t;else{var f=t.ownerDocument;p=f?f.defaultView||f.parentWindow:window}var h,v,m="",y="";if(e===l.topMouseOut?(h=t,m=n,v=u(o.relatedTarget||o.toElement),v?y=a.getID(v):v=p,v=v||p):(h=p,v=t,y=n),h===v)return null;var g=i.getPooled(c.mouseLeave,m,o,s);g.type="mouseleave",g.target=h,g.relatedTarget=v;var _=i.getPooled(c.mouseEnter,y,o,s);return _.type="mouseenter",_.target=v,_.relatedTarget=h,r.accumulateEnterLeaveDispatches(g,_,m,y),d[0]=g,d[1]=_,d}};e.exports=p},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(54),i=n(55),a=n(56),s={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:a,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+i.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+i.currentScrollTop}};r.augmentClass(o,s),e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(36),i=n(47),a={view:function(e){if(e.view)return e.view;var t=i(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(o,a),e.exports=o},function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){n.currentScrollLeft=e.x,n.currentScrollTop=e.y}};e.exports=n},function(e,t){"use strict";function n(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var o=r[e];return o?!!n[o]:!1}function o(e){return n}var r={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};e.exports=o},function(e,t,n){(function(t){"use strict";function o(e,t){for(var n=Math.min(e.length,t.length),o=0;n>o;o++)if(e.charAt(o)!==t.charAt(o))return o;return e.length===t.length?-1:n}function r(e){return e?e.nodeType===q?e.documentElement:e.firstChild:null}function i(e){var t=r(e);return t&&ee.getID(t)}function a(e){var n=s(e);if(n)if(H.hasOwnProperty(n)){var o=H[n];o!==e&&(d(o,n)?"production"!==t.env.NODE_ENV?L(!1,"ReactMount: Two valid but unequal nodes with the same `%s`: %s",W,n):L(!1):void 0,H[n]=e)}else H[n]=e;return n}function s(e){return e&&e.getAttribute&&e.getAttribute(W)||""}function l(e,t){var n=s(e);n!==t&&delete H[n],e.setAttribute(W,t),H[t]=e}function u(e){return H.hasOwnProperty(e)&&d(H[e],e)||(H[e]=ee.findReactNodeByID(e)),H[e]}function c(e){var t=D.get(e)._rootNodeID;return S.isNullComponentID(t)?null:(H.hasOwnProperty(t)&&d(H[t],t)||(H[t]=ee.findReactNodeByID(t)),H[t])}function d(e,n){if(e){s(e)!==n?"production"!==t.env.NODE_ENV?L(!1,"ReactMount: Unexpected modification of `%s`",W):L(!1):void 0;var o=ee.findReactContainerForID(n);if(o&&A(o,e))return!0}return!1}function p(e){delete H[e]}function f(e){var t=H[e];return t&&d(t,e)?void(J=t):!1}function h(e){J=null,x.traverseAncestors(e,f);var t=J;return J=null,t}function v(e,n,o,r,i,a){if(N.useCreateElement&&(a=I({},a),o.nodeType===q?a[G]=o:a[G]=o.ownerDocument),"production"!==t.env.NODE_ENV){a===k&&(a={});var s=o.nodeName.toLowerCase();a[z.ancestorInfoContextKey]=z.updatedAncestorInfo(null,s,null)}var l=P.mountComponent(e,n,r,a);e._renderedComponent._topLevelWrapper=e,ee._mountImageIntoNode(l,o,i,r)}function m(e,t,n,o,r){var i=M.ReactReconcileTransaction.getPooled(o);i.perform(v,null,e,t,n,i,o,r),M.ReactReconcileTransaction.release(i)}function y(e,t){for(P.unmountComponent(e),t.nodeType===q&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}function g(e){var t=i(e);return t?t!==x.getReactRootIDFromNodeID(t):!1}function _(e){for(;e&&e.parentNode!==e;e=e.parentNode)if(1===e.nodeType){var t=s(e);if(t){var n,o=x.getReactRootIDFromNodeID(t),r=e;do if(n=s(r),r=r.parentNode,null==r)return null;while(n!==o);if(r===$[o])return e}}return null}var b=n(58),E=n(59),C=n(61),N=n(62),w=n(63),S=n(65),x=n(66),D=n(68),O=n(69),T=n(42),P=n(43),R=n(71),M=n(40),I=n(33),k=n(72),A=n(73),V=n(76),L=n(20),j=n(84),U=n(81),z=n(85),F=n(26),W=b.ID_ATTRIBUTE_NAME,H={},B=1,q=9,K=11,G="__ReactMount_ownerDocument$"+Math.random().toString(36).slice(2),Y={},$={};if("production"!==t.env.NODE_ENV)var Q={};var X=[],J=null,Z=function(){};Z.prototype.isReactComponent={},"production"!==t.env.NODE_ENV&&(Z.displayName="TopLevelWrapper"),Z.prototype.render=function(){return this.props};var ee={TopLevelWrapper:Z,_instancesByReactRootID:Y,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,n,o,a){return ee.scrollMonitor(o,function(){R.enqueueElementInternal(e,n),a&&R.enqueueCallbackInternal(e,a)}),"production"!==t.env.NODE_ENV&&(Q[i(o)]=r(o)),e},_registerComponent:function(e,n){!n||n.nodeType!==B&&n.nodeType!==q&&n.nodeType!==K?"production"!==t.env.NODE_ENV?L(!1,"_registerComponent(...): Target container is not a DOM element."):L(!1):void 0,E.ensureScrollValueMonitoring();var o=ee.registerContainer(n);return Y[o]=e,o},_renderNewRootComponent:function(e,n,o,i){"production"!==t.env.NODE_ENV?F(null==C.current,"_renderNewRootComponent(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate. Check the render method of %s.",C.current&&C.current.getName()||"ReactCompositeComponent"):void 0;var a=V(e,null),s=ee._registerComponent(a,n);return M.batchedUpdates(m,a,s,n,o,i),"production"!==t.env.NODE_ENV&&(Q[s]=r(n)),a},renderSubtreeIntoContainer:function(e,n,o,r){return null==e||null==e._reactInternalInstance?"production"!==t.env.NODE_ENV?L(!1,"parentComponent must be a valid React Component"):L(!1):void 0,ee._renderSubtreeIntoContainer(e,n,o,r)},_renderSubtreeIntoContainer:function(e,n,o,a){w.isValidElement(n)?void 0:"production"!==t.env.NODE_ENV?L(!1,"ReactDOM.render(): Invalid component element.%s","string"==typeof n?" Instead of passing an element string, make sure to instantiate it by passing it to React.createElement.":"function"==typeof n?" Instead of passing a component class, make sure to instantiate it by passing it to React.createElement.":null!=n&&void 0!==n.props?" This may be caused by unintentionally loading two independent copies of React.":""):L(!1),"production"!==t.env.NODE_ENV?F(!o||!o.tagName||"BODY"!==o.tagName.toUpperCase(),"render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reconciliation issues. Try rendering into a container element created for your app."):void 0;var l=new w(Z,null,null,null,null,null,n),u=Y[i(o)];if(u){var c=u._currentElement,d=c.props;if(U(d,n)){var p=u._renderedComponent.getPublicInstance(),f=a&&function(){a.call(p)};return ee._updateRootComponent(u,l,o,f),p}ee.unmountComponentAtNode(o)}var h=r(o),v=h&&!!s(h),m=g(o);if("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?F(!m,"render(...): Replacing React-rendered children with a new root component. If you intended to update the children of this node, you should instead have the existing children update their state and render the new components instead of calling ReactDOM.render."):void 0,!v||h.nextSibling))for(var y=h;y;){if(s(y)){"production"!==t.env.NODE_ENV?F(!1,"render(): Target node has markup rendered by React, but there are unrelated nodes as well. This is most commonly caused by white-space inserted around server-rendered markup."):void 0;break}y=y.nextSibling}var _=v&&!u&&!m,b=ee._renderNewRootComponent(l,o,_,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):k)._renderedComponent.getPublicInstance();return a&&a.call(b),b},render:function(e,t,n){return ee._renderSubtreeIntoContainer(null,e,t,n)},registerContainer:function(e){var t=i(e);return t&&(t=x.getReactRootIDFromNodeID(t)),t||(t=x.createReactRootID()),$[t]=e,t},unmountComponentAtNode:function(e){"production"!==t.env.NODE_ENV?F(null==C.current,"unmountComponentAtNode(): Render methods should be a pure function of props and state; triggering nested component updates from render is not allowed. If necessary, trigger nested updates in componentDidUpdate. Check the render method of %s.",C.current&&C.current.getName()||"ReactCompositeComponent"):void 0,!e||e.nodeType!==B&&e.nodeType!==q&&e.nodeType!==K?"production"!==t.env.NODE_ENV?L(!1,"unmountComponentAtNode(...): Target container is not a DOM element."):L(!1):void 0;var n=i(e),o=Y[n];if(!o){var r=g(e),a=s(e),l=a&&a===x.getReactRootIDFromNodeID(a);return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?F(!r,"unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. %s",l?"You may have accidentally passed in a React root node instead of its container.":"Instead, have the parent component update its state and rerender in order to remove this component."):void 0),!1}return M.batchedUpdates(y,o,e),delete Y[n],delete $[n],"production"!==t.env.NODE_ENV&&delete Q[n],!0},findReactContainerForID:function(e){var n=x.getReactRootIDFromNodeID(e),o=$[n];if("production"!==t.env.NODE_ENV){var r=Q[n];if(r&&r.parentNode!==o){"production"!==t.env.NODE_ENV?F(s(r)===n,"ReactMount: Root element ID differed from reactRootID."):void 0;var i=o.firstChild;i&&n===s(i)?Q[n]=i:"production"!==t.env.NODE_ENV?F(!1,"ReactMount: Root element has been removed from its original container. New container: %s",r.parentNode):void 0}}return o},findReactNodeByID:function(e){var t=ee.findReactContainerForID(e);return ee.findComponentRoot(t,e)},getFirstReactDOM:function(e){return _(e)},findComponentRoot:function(e,n){var o=X,r=0,i=h(n)||e;for("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?F(null!=i,"React can't find the root component node for data-reactid value `%s`. If you're seeing this message, it probably means that you've loaded two copies of React on the page. At this time, only a single copy of React can be loaded at a time.",n):void 0),o[0]=i.firstChild,o.length=1;r<o.length;){for(var a,s=o[r++];s;){var l=ee.getID(s);l?n===l?a=s:x.isAncestorIDOf(l,n)&&(o.length=r=0,o.push(s.firstChild)):o.push(s.firstChild),s=s.nextSibling}if(a)return o.length=0,a}o.length=0,"production"!==t.env.NODE_ENV?L(!1,"findComponentRoot(..., %s): Unable to find element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",n,ee.getID(e)):L(!1)},_mountImageIntoNode:function(e,n,i,a){if(!n||n.nodeType!==B&&n.nodeType!==q&&n.nodeType!==K?"production"!==t.env.NODE_ENV?L(!1,"mountComponentIntoNode(...): Target container is not valid."):L(!1):void 0,i){var s=r(n);if(O.canReuseMarkup(e,s))return;var l=s.getAttribute(O.CHECKSUM_ATTR_NAME);s.removeAttribute(O.CHECKSUM_ATTR_NAME);var u=s.outerHTML;s.setAttribute(O.CHECKSUM_ATTR_NAME,l);var c=e;if("production"!==t.env.NODE_ENV){var d;n.nodeType===B?(d=document.createElement("div"),d.innerHTML=e,c=d.innerHTML):(d=document.createElement("iframe"),document.body.appendChild(d),d.contentDocument.write(e),c=d.contentDocument.documentElement.outerHTML,document.body.removeChild(d))}var p=o(c,u),f=" (client) "+c.substring(p-20,p+20)+"\n (server) "+u.substring(p-20,p+20);n.nodeType===q?"production"!==t.env.NODE_ENV?L(!1,"You're trying to render a component to the document using server rendering but the checksum was invalid. This usually means you rendered a different component type or props on the client from the one on the server, or your render() methods are impure. React cannot handle this case due to cross-browser quirks by rendering at the document root. You should look for environment dependent code in your components and ensure the props are the same client and server side:\n%s",f):L(!1):void 0,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?F(!1,"React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:\n%s",f):void 0)}if(n.nodeType===q?"production"!==t.env.NODE_ENV?L(!1,"You're trying to render a component to the document but you didn't use server rendering. We can't do this without using server rendering due to cross-browser quirks. See ReactDOMServer.renderToString() for server rendering."):L(!1):void 0,a.useCreateElement){for(;n.lastChild;)n.removeChild(n.lastChild);n.appendChild(e)}else j(n,e)},ownerDocumentContextKey:G,getReactRootID:i,getID:a,setID:l,getNode:u,getNodeFromInstance:c,isValid:d,purgeID:p};T.measureMethods(ee,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),e.exports=ee}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,t){return(e&t)===t}var r=n(20),i={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 n=i,a=e.Properties||{},l=e.DOMAttributeNamespaces||{},u=e.DOMAttributeNames||{},c=e.DOMPropertyNames||{},d=e.DOMMutationMethods||{};e.isCustomAttribute&&s._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var p in a){s.properties.hasOwnProperty(p)?"production"!==t.env.NODE_ENV?r(!1,"injectDOMPropertyConfig(...): You're trying to inject DOM property '%s' which has already been injected. You may be accidentally injecting the same DOM property config twice, or you may be injecting two configs that have conflicting property names.",p):r(!1):void 0;var f=p.toLowerCase(),h=a[p],v={attributeName:f,attributeNamespace:null,propertyName:p,mutationMethod:null,mustUseAttribute:o(h,n.MUST_USE_ATTRIBUTE),mustUseProperty:o(h,n.MUST_USE_PROPERTY),hasSideEffects:o(h,n.HAS_SIDE_EFFECTS),hasBooleanValue:o(h,n.HAS_BOOLEAN_VALUE),hasNumericValue:o(h,n.HAS_NUMERIC_VALUE),hasPositiveNumericValue:o(h,n.HAS_POSITIVE_NUMERIC_VALUE),hasOverloadedBooleanValue:o(h,n.HAS_OVERLOADED_BOOLEAN_VALUE)};if(v.mustUseAttribute&&v.mustUseProperty?"production"!==t.env.NODE_ENV?r(!1,"DOMProperty: Cannot require using both attribute and property: %s",p):r(!1):void 0,!v.mustUseProperty&&v.hasSideEffects?"production"!==t.env.NODE_ENV?r(!1,"DOMProperty: Properties that have side effects must use property: %s",p):r(!1):void 0,v.hasBooleanValue+v.hasNumericValue+v.hasOverloadedBooleanValue<=1?void 0:"production"!==t.env.NODE_ENV?r(!1,"DOMProperty: Value can be one of boolean, overloaded boolean, or numeric value, but not a combination: %s",p):r(!1),"production"!==t.env.NODE_ENV&&(s.getPossibleStandardName[f]=p),u.hasOwnProperty(p)){var m=u[p];v.attributeName=m,"production"!==t.env.NODE_ENV&&(s.getPossibleStandardName[m]=p)}l.hasOwnProperty(p)&&(v.attributeNamespace=l[p]),c.hasOwnProperty(p)&&(v.propertyName=c[p]),d.hasOwnProperty(p)&&(v.mutationMethod=d[p]),s.properties[p]=v}}},a={},s={ID_ATTRIBUTE_NAME:"data-reactid",properties:{},getPossibleStandardName:"production"!==t.env.NODE_ENV?{}:null,_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<s._isCustomAttributeFunctions.length;t++){var n=s._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,o=a[e];return o||(a[e]=o={}),t in o||(n=document.createElement(e),o[t]=n[t]),o[t]},injection:i};e.exports=s}).call(t,n(16))},function(e,t,n){"use strict";function o(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=h++,p[e[m]]={}),p[e[m]]}var r=n(18),i=n(22),a=n(23),s=n(60),l=n(42),u=n(55),c=n(33),d=n(48),p={},f=!1,h=0,v={topAbort:"abort",topBlur:"blur",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",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",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topScroll:"scroll",topSeeked:"seeked",topSeeking:"seeking",topSelectionChange:"selectionchange",topStalled:"stalled",topSuspend:"suspend",topTextInput:"textInput",topTimeUpdate:"timeupdate",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topVolumeChange:"volumechange",topWaiting:"waiting",topWheel:"wheel"},m="_reactListenersID"+String(Math.random()).slice(2),y=c({},s,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(y.handleTopLevel),y.ReactEventListener=e}},setEnabled:function(e){y.ReactEventListener&&y.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!y.ReactEventListener||!y.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=o(n),s=a.registrationNameDependencies[e],l=r.topLevelTypes,u=0;u<s.length;u++){var c=s[u];i.hasOwnProperty(c)&&i[c]||(c===l.topWheel?d("wheel")?y.ReactEventListener.trapBubbledEvent(l.topWheel,"wheel",n):d("mousewheel")?y.ReactEventListener.trapBubbledEvent(l.topWheel,"mousewheel",n):y.ReactEventListener.trapBubbledEvent(l.topWheel,"DOMMouseScroll",n):c===l.topScroll?d("scroll",!0)?y.ReactEventListener.trapCapturedEvent(l.topScroll,"scroll",n):y.ReactEventListener.trapBubbledEvent(l.topScroll,"scroll",y.ReactEventListener.WINDOW_HANDLE):c===l.topFocus||c===l.topBlur?(d("focus",!0)?(y.ReactEventListener.trapCapturedEvent(l.topFocus,"focus",n),y.ReactEventListener.trapCapturedEvent(l.topBlur,"blur",n)):d("focusin")&&(y.ReactEventListener.trapBubbledEvent(l.topFocus,"focusin",n),y.ReactEventListener.trapBubbledEvent(l.topBlur,"focusout",n)),i[l.topBlur]=!0,i[l.topFocus]=!0):v.hasOwnProperty(c)&&y.ReactEventListener.trapBubbledEvent(c,v[c],n),i[c]=!0)}},trapBubbledEvent:function(e,t,n){return y.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return y.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!f){var e=u.refreshScrollValues;y.ReactEventListener.monitorScrollValue(e),f=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});l.measureMethods(y,"ReactBrowserEventEmitter",{putListener:"putListener",deleteListener:"deleteListener"}),e.exports=y},function(e,t,n){"use strict";function o(e){r.enqueueEvents(e),r.processEventQueue(!1)}var r=n(22),i={handleTopLevel:function(e,t,n,i,a){var s=r.extractEvents(e,t,n,i,a);o(s)}};e.exports=i},function(e,t){"use strict";var n={current:null};e.exports=n},function(e,t){"use strict";var n={useCreateElement:!1};e.exports=n},function(e,t,n){(function(t){"use strict";var o=n(61),r=n(33),i=n(64),a="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103,s={key:!0,ref:!0,__self:!0,__source:!0},l=function(e,n,o,r,s,l,u){var c={$$typeof:a,type:e,key:n,ref:o,props:u,_owner:l};return"production"!==t.env.NODE_ENV&&(c._store={},i?(Object.defineProperty(c._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:!1}),Object.defineProperty(c,"_self",{configurable:!1,enumerable:!1,writable:!1,value:r}),Object.defineProperty(c,"_source",{configurable:!1,enumerable:!1,writable:!1,value:s})):(c._store.validated=!1,c._self=r,c._source=s),Object.freeze(c.props),Object.freeze(c)),c};l.createElement=function(e,t,n){var r,i={},a=null,u=null,c=null,d=null;if(null!=t){u=void 0===t.ref?null:t.ref,a=void 0===t.key?null:""+t.key,c=void 0===t.__self?null:t.__self,d=void 0===t.__source?null:t.__source;for(r in t)t.hasOwnProperty(r)&&!s.hasOwnProperty(r)&&(i[r]=t[r])}var p=arguments.length-2;if(1===p)i.children=n;else if(p>1){for(var f=Array(p),h=0;p>h;h++)f[h]=arguments[h+2];i.children=f}if(e&&e.defaultProps){var v=e.defaultProps;for(r in v)"undefined"==typeof i[r]&&(i[r]=v[r])}return l(e,a,u,c,d,o.current,i)},l.createFactory=function(e){var t=l.createElement.bind(null,e);return t.type=e,t},l.cloneAndReplaceKey=function(e,t){var n=l(e.type,t,e.ref,e._self,e._source,e._owner,e.props);return n},l.cloneAndReplaceProps=function(e,n){var o=l(e.type,e.key,e.ref,e._self,e._source,e._owner,n);return"production"!==t.env.NODE_ENV&&(o._store.validated=e._store.validated),o},l.cloneElement=function(e,t,n){var i,a=r({},e.props),u=e.key,c=e.ref,d=e._self,p=e._source,f=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,f=o.current),void 0!==t.key&&(u=""+t.key);for(i in t)t.hasOwnProperty(i)&&!s.hasOwnProperty(i)&&(a[i]=t[i])}var h=arguments.length-2;if(1===h)a.children=n;else if(h>1){for(var v=Array(h),m=0;h>m;m++)v[m]=arguments[m+2];a.children=v}return l(e.type,u,c,d,p,f,a)},l.isValidElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===a},e.exports=l}).call(t,n(16))},function(e,t,n){(function(t){"use strict";var n=!1;if("production"!==t.env.NODE_ENV)try{Object.defineProperty({},"x",{get:function(){}}),n=!0}catch(o){}e.exports=n}).call(t,n(16))},function(e,t){"use strict";function n(e){return!!i[e]}function o(e){i[e]=!0}function r(e){delete i[e]}var i={},a={isNullComponentID:n,registerNullComponentID:o,deregisterNullComponentID:r};e.exports=a},function(e,t,n){(function(t){"use strict";function o(e){return f+e.toString(36)}function r(e,t){return e.charAt(t)===f||t===e.length}function i(e){return""===e||e.charAt(0)===f&&e.charAt(e.length-1)!==f}function a(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function s(e){return e?e.substr(0,e.lastIndexOf(f)):""}function l(e,n){if(i(e)&&i(n)?void 0:"production"!==t.env.NODE_ENV?p(!1,"getNextDescendantID(%s, %s): Received an invalid React DOM ID.",e,n):p(!1),a(e,n)?void 0:"production"!==t.env.NODE_ENV?p(!1,"getNextDescendantID(...): React has made an invalid assumption about the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.",e,n):p(!1),e===n)return e;var o,s=e.length+h;for(o=s;o<n.length&&!r(n,o);o++);return n.substr(0,o)}function u(e,n){var o=Math.min(e.length,n.length);if(0===o)return"";for(var a=0,s=0;o>=s;s++)if(r(e,s)&&r(n,s))a=s;else if(e.charAt(s)!==n.charAt(s))break;var l=e.substr(0,a);return i(l)?void 0:"production"!==t.env.NODE_ENV?p(!1,"getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s",e,n,l):p(!1),l}function c(e,n,o,r,i,u){e=e||"",n=n||"",e===n?"production"!==t.env.NODE_ENV?p(!1,"traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.",e):p(!1):void 0;var c=a(n,e);c||a(e,n)?void 0:"production"!==t.env.NODE_ENV?p(!1,"traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do not have a parent path.",e,n):p(!1);for(var d=0,f=c?s:l,h=e;;h=f(h,n)){var m;if(i&&h===e||u&&h===n||(m=o(h,c,r)),m===!1||h===n)break;d++<v?void 0:"production"!==t.env.NODE_ENV?p(!1,"traverseParentPath(%s, %s, ...): Detected an infinite loop while traversing the React DOM ID tree. This may be due to malformed IDs: %s",e,n,h):p(!1)}}var d=n(67),p=n(20),f=".",h=f.length,v=1e4,m={createReactRootID:function(){return o(d.createReactRootIndex())},createReactID:function(e,t){return e+t},getReactRootIDFromNodeID:function(e){if(e&&e.charAt(0)===f&&e.length>1){var t=e.indexOf(f,1);return t>-1?e.substr(0,t):e}return null},traverseEnterLeave:function(e,t,n,o,r){var i=u(e,t);i!==e&&c(e,i,n,o,!1,!0),i!==t&&c(i,t,n,r,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(c("",e,t,n,!0,!1),c(e,"",t,n,!1,!0))},traverseTwoPhaseSkipTarget:function(e,t,n){e&&(c("",e,t,n,!0,!0),c(e,"",t,n,!0,!0))},traverseAncestors:function(e,t,n){c("",e,t,n,!0,!1)},getFirstCommonAncestorID:u,_getNextDescendantID:l,isAncestorIDOf:a,SEPARATOR:f};e.exports=m}).call(t,n(16))},function(e,t){"use strict";var n={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:n};e.exports=o},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}};e.exports=n},function(e,t,n){"use strict";var o=n(70),r=/\/?>/,i={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=o(e);return e.replace(r," "+i.CHECKSUM_ATTR_NAME+'="'+t+'"$&')},canReuseMarkup:function(e,t){var n=t.getAttribute(i.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var r=o(e);return r===n}};e.exports=i},function(e,t){"use strict";function n(e){for(var t=1,n=0,r=0,i=e.length,a=-4&i;a>r;){for(;r<Math.min(r+4096,a);r+=4)n+=(t+=e.charCodeAt(r))+(t+=e.charCodeAt(r+1))+(t+=e.charCodeAt(r+2))+(t+=e.charCodeAt(r+3));t%=o,n%=o}for(;i>r;r++)n+=t+=e.charCodeAt(r);return t%=o,n%=o,t|n<<16}var o=65521;e.exports=n},function(e,t,n){(function(t){"use strict";function o(e){l.enqueueUpdate(e)}function r(e,n){var o=s.get(e);return o?("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?d(null==i.current,"%s(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.",n):void 0),o):("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?d(!n,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.",n,n,e.constructor.displayName):void 0),null)}var i=n(61),a=n(63),s=n(68),l=n(40),u=n(33),c=n(20),d=n(26),p={isMounted:function(e){if("production"!==t.env.NODE_ENV){var n=i.current;null!==n&&("production"!==t.env.NODE_ENV?d(n._warnedAboutRefsInRender,"%s is accessing isMounted inside its render() function. render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",n.getName()||"A component"):void 0,n._warnedAboutRefsInRender=!0)}var o=s.get(e);return o?!!o._renderedComponent:!1},enqueueCallback:function(e,n){"function"!=typeof n?"production"!==t.env.NODE_ENV?c(!1,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):c(!1):void 0;var i=r(e);return i?(i._pendingCallbacks?i._pendingCallbacks.push(n):i._pendingCallbacks=[n],void o(i)):null},enqueueCallbackInternal:function(e,n){"function"!=typeof n?"production"!==t.env.NODE_ENV?c(!1,"enqueueCallback(...): You called `setProps`, `replaceProps`, `setState`, `replaceState`, or `forceUpdate` with a callback that isn't callable."):c(!1):void 0,e._pendingCallbacks?e._pendingCallbacks.push(n):e._pendingCallbacks=[n],o(e)},enqueueForceUpdate:function(e){var t=r(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,o(t))},enqueueReplaceState:function(e,t){var n=r(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,o(n))},enqueueSetState:function(e,t){var n=r(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),o(n)}},enqueueSetProps:function(e,t){var n=r(e,"setProps");n&&p.enqueueSetPropsInternal(n,t)},enqueueSetPropsInternal:function(e,n){var r=e._topLevelWrapper;r?void 0:"production"!==t.env.NODE_ENV?c(!1,"setProps(...): You called `setProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):c(!1);var i=r._pendingElement||r._currentElement,s=i.props,l=u({},s.props,n);r._pendingElement=a.cloneAndReplaceProps(i,a.cloneAndReplaceProps(s,l)),o(r)},enqueueReplaceProps:function(e,t){var n=r(e,"replaceProps");n&&p.enqueueReplacePropsInternal(n,t)},enqueueReplacePropsInternal:function(e,n){var r=e._topLevelWrapper;r?void 0:"production"!==t.env.NODE_ENV?c(!1,"replaceProps(...): You called `replaceProps` on a component with a parent. This is an anti-pattern since props will get reactively updated when rendered. Instead, change the owner's `render` method to pass the correct value as props to the component where it is created."):c(!1);var i=r._pendingElement||r._currentElement,s=i.props;r._pendingElement=a.cloneAndReplaceProps(i,a.cloneAndReplaceProps(s,n)),o(r)},enqueueElementInternal:function(e,t){e._pendingElement=t,o(e)}};e.exports=p}).call(t,n(16))},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&Object.freeze(n),e.exports=n}).call(t,n(16))},function(e,t,n){"use strict";function o(e,t){var n=!0;e:for(;n;){var o=e,i=t;if(n=!1,o&&i){if(o===i)return!0;if(r(o))return!1;if(r(i)){e=o,t=i.parentNode,n=!0;continue e}return o.contains?o.contains(i):o.compareDocumentPosition?!!(16&o.compareDocumentPosition(i)):!1}return!1}}var r=n(74);e.exports=o},function(e,t,n){"use strict";function o(e){return r(e)&&3==e.nodeType}var r=n(75);e.exports=o},function(e,t){"use strict";function n(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}e.exports=n},function(e,t,n){(function(t){"use strict";function o(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function i(e){var n;if(null===e||e===!1)n=new s(i);else if("object"==typeof e){var a=e;!a||"function"!=typeof a.type&&"string"!=typeof a.type?"production"!==t.env.NODE_ENV?c(!1,"Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s",null==a.type?a.type:typeof a.type,o(a._owner)):c(!1):void 0,n="string"==typeof a.type?l.createInternalComponent(a):r(a.type)?new a.type(a):new p}else"string"==typeof e||"number"==typeof e?n=l.createInstanceForText(e):"production"!==t.env.NODE_ENV?c(!1,"Encountered invalid React node of type %s",typeof e):c(!1);return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?d("function"==typeof n.construct&&"function"==typeof n.mountComponent&&"function"==typeof n.receiveComponent&&"function"==typeof n.unmountComponent,"Only React Components can be mounted."):void 0),n.construct(e),n._mountIndex=0,n._mountImage=null,"production"!==t.env.NODE_ENV&&(n._isOwnerNecessary=!1,n._warnedAboutRefsInRender=!1),"production"!==t.env.NODE_ENV&&Object.preventExtensions&&Object.preventExtensions(n),n}var a=n(77),s=n(82),l=n(83),u=n(33),c=n(20),d=n(26),p=function(){};u(p.prototype,a.Mixin,{_instantiateReactComponent:i}),e.exports=i}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}function r(e){}var i=n(78),a=n(61),s=n(63),l=n(68),u=n(42),c=n(79),d=n(80),p=n(43),f=n(71),h=n(33),v=n(72),m=n(20),y=n(81),g=n(26);r.prototype.render=function(){var e=l.get(this)._currentElement.type;return e(this.props,this.context,this.updater)};var _=1,b={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._topLevelWrapper=null,this._pendingCallbacks=null},mountComponent:function(e,n,o){this._context=o,this._mountOrder=_++,this._rootNodeID=e;var i,u,c=this._processProps(this._currentElement.props),d=this._processContext(o),h=this._currentElement.type,y="prototype"in h;if(y)if("production"!==t.env.NODE_ENV){a.current=this;try{i=new h(c,d,f)}finally{a.current=null}}else i=new h(c,d,f);y&&null!==i&&i!==!1&&!s.isValidElement(i)||(u=i,i=new r(h)),"production"!==t.env.NODE_ENV&&(null==i.render?"production"!==t.env.NODE_ENV?g(!1,"%s(...): No `render` method found on the returned component instance: you may have forgotten to define `render`, returned null/false from a stateless component, or tried to render an element whose type is a function that isn't a React component.",h.displayName||h.name||"Component"):void 0:"production"!==t.env.NODE_ENV?g(h.prototype&&h.prototype.isReactComponent||!y||!(i instanceof h),"%s(...): React component classes must extend React.Component.",h.displayName||h.name||"Component"):void 0),i.props=c,i.context=d,i.refs=v,i.updater=f,this._instance=i,l.set(i,this),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?g(!i.getInitialState||i.getInitialState.isReactClassApproved,"getInitialState was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Did you mean to define a state property instead?",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g(!i.getDefaultProps||i.getDefaultProps.isReactClassApproved,"getDefaultProps was defined on %s, a plain JavaScript class. This is only supported for classes created using React.createClass. Use a static property to define defaultProps instead.",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g(!i.propTypes,"propTypes was defined as an instance property on %s. Use a static property to define propTypes instead.",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g(!i.contextTypes,"contextTypes was defined as an instance property on %s. Use a static property to define contextTypes instead.",this.getName()||"a component"):void 0,"production"!==t.env.NODE_ENV?g("function"!=typeof i.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",this.getName()||"A component"):void 0,"production"!==t.env.NODE_ENV?g("function"!=typeof i.componentDidUnmount,"%s has a method called componentDidUnmount(). But there is no such lifecycle method. Did you mean componentWillUnmount()?",this.getName()||"A component"):void 0,"production"!==t.env.NODE_ENV?g("function"!=typeof i.componentWillRecieveProps,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",this.getName()||"A component"):void 0);var b=i.state;void 0===b&&(i.state=b=null),"object"!=typeof b||Array.isArray(b)?"production"!==t.env.NODE_ENV?m(!1,"%s.state: must be set to an object or null",this.getName()||"ReactCompositeComponent"):m(!1):void 0,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,i.componentWillMount&&(i.componentWillMount(),this._pendingStateQueue&&(i.state=this._processPendingState(i.props,i.context))),void 0===u&&(u=this._renderValidatedComponent()),this._renderedComponent=this._instantiateReactComponent(u);var E=p.mountComponent(this._renderedComponent,e,n,this._processChildContext(o));return i.componentDidMount&&n.getReactMountReady().enqueue(i.componentDidMount,i),E},unmountComponent:function(){var e=this._instance;e.componentWillUnmount&&e.componentWillUnmount(),p.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._instance=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,this._topLevelWrapper=null,l.remove(e)},_maskContext:function(e){var t=null,n=this._currentElement.type,o=n.contextTypes;if(!o)return v;t={};for(var r in o)t[r]=e[r];return t},_processContext:function(e){var n=this._maskContext(e);if("production"!==t.env.NODE_ENV){var o=this._currentElement.type;o.contextTypes&&this._checkPropTypes(o.contextTypes,n,c.context)}return n},_processChildContext:function(e){var n=this._currentElement.type,o=this._instance,r=o.getChildContext&&o.getChildContext();if(r){"object"!=typeof n.childContextTypes?"production"!==t.env.NODE_ENV?m(!1,"%s.getChildContext(): childContextTypes must be defined in order to use getChildContext().",this.getName()||"ReactCompositeComponent"):m(!1):void 0,"production"!==t.env.NODE_ENV&&this._checkPropTypes(n.childContextTypes,r,c.childContext);for(var i in r)i in n.childContextTypes?void 0:"production"!==t.env.NODE_ENV?m(!1,'%s.getChildContext(): key "%s" is not defined in childContextTypes.',this.getName()||"ReactCompositeComponent",i):m(!1);return h({},e,r)}return e},_processProps:function(e){if("production"!==t.env.NODE_ENV){var n=this._currentElement.type;n.propTypes&&this._checkPropTypes(n.propTypes,e,c.prop)}return e},_checkPropTypes:function(e,n,r){var i=this.getName();for(var a in e)if(e.hasOwnProperty(a)){var s;try{"function"!=typeof e[a]?"production"!==t.env.NODE_ENV?m(!1,"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",i||"React class",d[r],a):m(!1):void 0,s=e[a](n,a,i,r)}catch(l){s=l}if(s instanceof Error){var u=o(this);r===c.prop?"production"!==t.env.NODE_ENV?g(!1,"Failed Composite propType: %s%s",s.message,u):void 0:"production"!==t.env.NODE_ENV?g(!1,"Failed Context Types: %s%s",s.message,u):void 0}}},receiveComponent:function(e,t,n){var o=this._currentElement,r=this._context;this._pendingElement=null,this.updateComponent(t,o,e,r,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&p.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)},updateComponent:function(e,n,o,r,i){var a,s=this._instance,l=this._context===i?s.context:this._processContext(i);n===o?a=o.props:(a=this._processProps(o.props),s.componentWillReceiveProps&&s.componentWillReceiveProps(a,l));var u=this._processPendingState(a,l),c=this._pendingForceUpdate||!s.shouldComponentUpdate||s.shouldComponentUpdate(a,u,l);"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?g("undefined"!=typeof c,"%s.shouldComponentUpdate(): Returned undefined instead of a boolean value. Make sure to return true or false.",this.getName()||"ReactCompositeComponent"):void 0),c?(this._pendingForceUpdate=!1,this._performComponentUpdate(o,a,u,l,e,i)):(this._currentElement=o,this._context=i,s.props=a,s.state=u,s.context=l)},_processPendingState:function(e,t){var n=this._instance,o=this._pendingStateQueue,r=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!o)return n.state;if(r&&1===o.length)return o[0];for(var i=h({},r?o[0]:n.state),a=r?1:0;a<o.length;a++){var s=o[a];h(i,"function"==typeof s?s.call(n,i,e,t):s)}return i},_performComponentUpdate:function(e,t,n,o,r,i){var a,s,l,u=this._instance,c=Boolean(u.componentDidUpdate);c&&(a=u.props,s=u.state,l=u.context),u.componentWillUpdate&&u.componentWillUpdate(t,n,o),this._currentElement=e,this._context=i,u.props=t,u.state=n,u.context=o,this._updateRenderedComponent(r,i),c&&r.getReactMountReady().enqueue(u.componentDidUpdate.bind(u,a,s,l),u)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,o=n._currentElement,r=this._renderValidatedComponent();if(y(o,r))p.receiveComponent(n,r,e,this._processChildContext(t));else{var i=this._rootNodeID,a=n._rootNodeID;p.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(r);var s=p.mountComponent(this._renderedComponent,i,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(a,s)}},_replaceNodeWithMarkupByID:function(e,t){i.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,n=e.render();return"production"!==t.env.NODE_ENV&&"undefined"==typeof n&&e.render._isMockFunction&&(n=null),n},_renderValidatedComponent:function(){var e;a.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{a.current=null}return null===e||e===!1||s.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?m(!1,"%s.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.",this.getName()||"ReactCompositeComponent"):m(!1),e},attachRef:function(e,n){var o=this.getPublicInstance();null==o?"production"!==t.env.NODE_ENV?m(!1,"Stateless function components cannot have refs."):m(!1):void 0;var r=n.getPublicInstance();if("production"!==t.env.NODE_ENV){var i=n&&n.getName?n.getName():"a component";"production"!==t.env.NODE_ENV?g(null!=r,'Stateless function components cannot be given refs (See ref "%s" in %s created by %s). Attempts to access this ref will fail.',e,i,this.getName()):void 0}var a=o.refs===v?o.refs={}:o.refs;a[e]=r},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(){var e=this._instance;return e instanceof r?null:e},_instantiateReactComponent:null};u.measureMethods(b,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var E={Mixin:b};e.exports=E}).call(t,n(16))},function(e,t,n){(function(t){"use strict";var o=n(20),r=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){r?"production"!==t.env.NODE_ENV?o(!1,"ReactCompositeComponent: injectEnvironment() can only be called once."):o(!1):void 0,i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,r=!0}}};e.exports=i}).call(t,n(16))},function(e,t,n){"use strict";var o=n(19),r=o({prop:null,context:null,childContext:null});e.exports=r},function(e,t,n){(function(t){"use strict";var n={};"production"!==t.env.NODE_ENV&&(n={prop:"prop",context:"context",childContext:"child context"}),e.exports=n}).call(t,n(16))},function(e,t){"use strict";function n(e,t){var n=null===e||e===!1,o=null===t||t===!1;if(n||o)return n===o;var r=typeof e,i=typeof t;return"string"===r||"number"===r?"string"===i||"number"===i:"object"===i&&e.type===t.type&&e.key===t.key}e.exports=n},function(e,t,n){"use strict";var o,r=n(63),i=n(65),a=n(43),s=n(33),l={injectEmptyComponent:function(e){o=r.createElement(e)}},u=function(e){this._currentElement=null,this._rootNodeID=null,this._renderedComponent=e(o)};s(u.prototype,{construct:function(e){},mountComponent:function(e,t,n){return i.registerNullComponentID(e),this._rootNodeID=e,a.mountComponent(this._renderedComponent,e,t,n)},receiveComponent:function(){},unmountComponent:function(e,t,n){a.unmountComponent(this._renderedComponent),i.deregisterNullComponentID(this._rootNodeID),this._rootNodeID=null,this._renderedComponent=null}}),u.injection=l,e.exports=u},function(e,t,n){(function(t){"use strict";function o(e){if("function"==typeof e.type)return e.type;var t=e.type,n=d[t];return null==n&&(d[t]=n=u(t)),n}function r(e){return c?void 0:"production"!==t.env.NODE_ENV?l(!1,"There is no registered component for the tag %s",e.type):l(!1),new c(e.type,e.props)}function i(e){return new p(e)}function a(e){return e instanceof p}var s=n(33),l=n(20),u=null,c=null,d={},p=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){p=e},injectComponentClasses:function(e){s(d,e)}},h={getComponentClassForElement:o,createInternalComponent:r,createInstanceForText:i,isTextComponent:a,injection:f};e.exports=h}).call(t,n(16))},function(e,t,n){"use strict";var o=n(30),r=/^[ \r\n\t\f]/,i=/<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/,a=function(e,t){e.innerHTML=t};if("undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction&&(a=function(e,t){MSApp.execUnsafeLocalFunction(function(){e.innerHTML=t})}),o.canUseDOM){var s=document.createElement("div");s.innerHTML=" ",""===s.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),r.test(t)||"<"===t[0]&&i.test(t)){e.innerHTML=String.fromCharCode(65279)+t;var n=e.firstChild;1===n.data.length?e.removeChild(n):n.deleteData(0,1)}else e.innerHTML=t})}e.exports=a},function(e,t,n){(function(t){"use strict";var o=n(33),r=n(27),i=n(26),a=r;if("production"!==t.env.NODE_ENV){var s=["address","applet","area","article","aside","base","basefont","bgsound","blockquote","body","br","button","caption","center","col","colgroup","dd","details","dir","div","dl","dt","embed","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","iframe","img","input","isindex","li","link","listing","main","marquee","menu","menuitem","meta","nav","noembed","noframes","noscript","object","ol","p","param","plaintext","pre","script","section","select","source","style","summary","table","tbody","td","template","textarea","tfoot","th","thead","title","tr","track","ul","wbr","xmp"],l=["applet","caption","html","table","td","th","marquee","object","template","foreignObject","desc","title"],u=l.concat(["button"]),c=["dd","dt","li","option","optgroup","p","rp","rt"],d={
parentTag:null,formTag:null,aTagInScope:null,buttonTagInScope:null,nobrTagInScope:null,pTagInButtonScope:null,listItemTagAutoclosing:null,dlItemTagAutoclosing:null},p=function(e,t,n){var r=o({},e||d),i={tag:t,instance:n};return-1!==l.indexOf(t)&&(r.aTagInScope=null,r.buttonTagInScope=null,r.nobrTagInScope=null),-1!==u.indexOf(t)&&(r.pTagInButtonScope=null),-1!==s.indexOf(t)&&"address"!==t&&"div"!==t&&"p"!==t&&(r.listItemTagAutoclosing=null,r.dlItemTagAutoclosing=null),r.parentTag=i,"form"===t&&(r.formTag=i),"a"===t&&(r.aTagInScope=i),"button"===t&&(r.buttonTagInScope=i),"nobr"===t&&(r.nobrTagInScope=i),"p"===t&&(r.pTagInButtonScope=i),"li"===t&&(r.listItemTagAutoclosing=i),"dd"!==t&&"dt"!==t||(r.dlItemTagAutoclosing=i),r},f=function(e,t){switch(t){case"select":return"option"===e||"optgroup"===e||"#text"===e;case"optgroup":return"option"===e||"#text"===e;case"option":return"#text"===e;case"tr":return"th"===e||"td"===e||"style"===e||"script"===e||"template"===e;case"tbody":case"thead":case"tfoot":return"tr"===e||"style"===e||"script"===e||"template"===e;case"colgroup":return"col"===e||"template"===e;case"table":return"caption"===e||"colgroup"===e||"tbody"===e||"tfoot"===e||"thead"===e||"style"===e||"script"===e||"template"===e;case"head":return"base"===e||"basefont"===e||"bgsound"===e||"link"===e||"meta"===e||"title"===e||"noscript"===e||"noframes"===e||"style"===e||"script"===e||"template"===e;case"html":return"head"===e||"body"===e}switch(e){case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return"h1"!==t&&"h2"!==t&&"h3"!==t&&"h4"!==t&&"h5"!==t&&"h6"!==t;case"rp":case"rt":return-1===c.indexOf(t);case"caption":case"col":case"colgroup":case"frame":case"head":case"tbody":case"td":case"tfoot":case"th":case"thead":case"tr":return null==t}return!0},h=function(e,t){switch(e){case"address":case"article":case"aside":case"blockquote":case"center":case"details":case"dialog":case"dir":case"div":case"dl":case"fieldset":case"figcaption":case"figure":case"footer":case"header":case"hgroup":case"main":case"menu":case"nav":case"ol":case"p":case"section":case"summary":case"ul":case"pre":case"listing":case"table":case"hr":case"xmp":case"h1":case"h2":case"h3":case"h4":case"h5":case"h6":return t.pTagInButtonScope;case"form":return t.formTag||t.pTagInButtonScope;case"li":return t.listItemTagAutoclosing;case"dd":case"dt":return t.dlItemTagAutoclosing;case"button":return t.buttonTagInScope;case"a":return t.aTagInScope;case"nobr":return t.nobrTagInScope}return null},v=function(e){if(!e)return[];var t=[];do t.push(e);while(e=e._currentElement._owner);return t.reverse(),t},m={};a=function(e,n,o){o=o||d;var r=o.parentTag,a=r&&r.tag,s=f(e,a)?null:r,l=s?null:h(e,o),u=s||l;if(u){var c,p=u.tag,y=u.instance,g=n&&n._currentElement._owner,_=y&&y._currentElement._owner,b=v(g),E=v(_),C=Math.min(b.length,E.length),N=-1;for(c=0;C>c&&b[c]===E[c];c++)N=c;var w="(unknown)",S=b.slice(N+1).map(function(e){return e.getName()||w}),x=E.slice(N+1).map(function(e){return e.getName()||w}),D=[].concat(-1!==N?b[N].getName()||w:[],x,p,l?["..."]:[],S,e).join(" > "),O=!!s+"|"+e+"|"+p+"|"+D;if(m[O])return;if(m[O]=!0,s){var T="";"table"===p&&"tr"===e&&(T+=" Add a <tbody> to your code to match the DOM tree generated by the browser."),"production"!==t.env.NODE_ENV?i(!1,"validateDOMNesting(...): <%s> cannot appear as a child of <%s>. See %s.%s",e,p,D,T):void 0}else"production"!==t.env.NODE_ENV?i(!1,"validateDOMNesting(...): <%s> cannot appear as a descendant of <%s>. See %s.",e,p,D):void 0}},a.ancestorInfoContextKey="__validateDOMNesting_ancestorInfo$"+Math.random().toString(36).slice(2),a.updatedAncestorInfo=p,a.isTagValidInContext=function(e,t){t=t||d;var n=t.parentTag,o=n&&n.tag;return f(e,o)&&!h(e,t)}}e.exports=a}).call(t,n(16))},function(e,t,n){"use strict";var o,r=n(58),i=n(30),a=r.injection.MUST_USE_ATTRIBUTE,s=r.injection.MUST_USE_PROPERTY,l=r.injection.HAS_BOOLEAN_VALUE,u=r.injection.HAS_SIDE_EFFECTS,c=r.injection.HAS_NUMERIC_VALUE,d=r.injection.HAS_POSITIVE_NUMERIC_VALUE,p=r.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var f=document.implementation;o=f&&f.hasFeature&&f.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")}var h={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accept:null,acceptCharset:null,accessKey:null,action:null,allowFullScreen:a|l,allowTransparency:a,alt:null,async:l,autoComplete:null,autoPlay:l,capture:a|l,cellPadding:null,cellSpacing:null,charSet:a,challenge:a,checked:s|l,classID:a,className:o?a:s,cols:a|d,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:s|l,coords:null,crossOrigin:null,data:null,dateTime:a,"default":l,defer:l,dir:null,disabled:a|l,download:p,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:l,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|l,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:s,inputMode:a,integrity:null,is:a,keyParams:a,keyType:a,kind:null,label:null,lang:null,list:a,loop:s|l,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,minLength:a,multiple:s|l,muted:s|l,name:null,nonce:a,noValidate:l,open:l,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:s|l,rel:null,required:l,reversed:l,role:a,rows:a|d,rowSpan:null,sandbox:null,scope:null,scoped:l,scrolling:null,seamless:a|l,selected:s|l,shape:null,size:a|d,sizes:a,span:d,spellCheck:null,src:null,srcDoc:s,srcLang:null,srcSet:a,start:c,step:null,style:null,summary:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:s|u,width:a,wmode:a,wrap:null,about:a,datatype:a,inlist:a,prefix:a,property:a,resource:a,"typeof":a,vocab:a,autoCapitalize:a,autoCorrect:a,autoSave:null,color:null,itemProp:a,itemScope:a|l,itemType:a,itemID:a,itemRef:a,results:null,security:a,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoComplete:"autocomplete",autoFocus:"autofocus",autoPlay:"autoplay",autoSave:"autosave",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};e.exports=h},function(e,t,n){(function(t){"use strict";var o=n(68),r=n(88),i=n(26),a="_getDOMNodeDidWarn",s={getDOMNode:function(){return"production"!==t.env.NODE_ENV?i(this.constructor[a],"%s.getDOMNode(...) is deprecated. Please use ReactDOM.findDOMNode(instance) instead.",o.get(this).getName()||this.tagName||"Unknown"):void 0,this.constructor[a]=!0,r(this)}};e.exports=s}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){if("production"!==t.env.NODE_ENV){var n=r.current;null!==n&&("production"!==t.env.NODE_ENV?l(n._warnedAboutRefsInRender,"%s is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead.",n.getName()||"A component"):void 0,n._warnedAboutRefsInRender=!0)}return null==e?null:1===e.nodeType?e:i.has(e)?a.getNodeFromInstance(e):(null!=e.render&&"function"==typeof e.render?"production"!==t.env.NODE_ENV?s(!1,"findDOMNode was called on an unmounted component."):s(!1):void 0,void("production"!==t.env.NODE_ENV?s(!1,"Element appears to be neither ReactComponent nor DOMNode (keys: %s)",Object.keys(e)):s(!1)))}var r=n(61),i=n(68),a=n(57),s=n(20),l=n(26);e.exports=o}).call(t,n(16))},function(e,t,n){"use strict";var o=n(90),r=n(57),i={processChildrenUpdates:o.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:o.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){r.purgeID(e)}};e.exports=i},function(e,t,n){(function(t){"use strict";var o=n(91),r=n(100),i=n(57),a=n(42),s=n(20),l={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},u={updatePropertyByID:function(e,n,o){var a=i.getNode(e);l.hasOwnProperty(n)?"production"!==t.env.NODE_ENV?s(!1,"updatePropertyByID(...): %s",l[n]):s(!1):void 0,null!=o?r.setValueForProperty(a,n,o):r.deleteValueForProperty(a,n)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=i.getNode(e);o.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=i.getNode(e[n].parentID);o.processUpdates(e,t)}};a.measureMethods(u,"ReactDOMIDOperations",{dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),e.exports=u}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,t,n){var o=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,o)}var r=n(92),i=n(97),a=n(42),s=n(84),l=n(98),u=n(20),c={dangerouslyReplaceNodeWithMarkup:r.dangerouslyReplaceNodeWithMarkup,updateTextContent:l,processUpdates:function(e,n){for(var a,c=null,d=null,p=0;p<e.length;p++)if(a=e[p],a.type===i.MOVE_EXISTING||a.type===i.REMOVE_NODE){var f=a.fromIndex,h=a.parentNode.childNodes[f],v=a.parentID;h?void 0:"production"!==t.env.NODE_ENV?u(!1,"processUpdates(): Unable to find child %s of element. This probably means the DOM was unexpectedly mutated (e.g., by the browser), usually due to forgetting a <tbody> when using tables, nesting tags like <form>, <p>, or <a>, or using non-SVG elements in an <svg> parent. Try inspecting the child nodes of the element with React ID `%s`.",f,v):u(!1),c=c||{},c[v]=c[v]||[],c[v][f]=h,d=d||[],d.push(h)}var m;if(m=n.length&&"string"==typeof n[0]?r.dangerouslyRenderMarkup(n):n,d)for(var y=0;y<d.length;y++)d[y].parentNode.removeChild(d[y]);for(var g=0;g<e.length;g++)switch(a=e[g],a.type){case i.INSERT_MARKUP:o(a.parentNode,m[a.markupIndex],a.toIndex);break;case i.MOVE_EXISTING:o(a.parentNode,c[a.parentID][a.fromIndex],a.toIndex);break;case i.SET_MARKUP:s(a.parentNode,a.content);break;case i.TEXT_CONTENT:l(a.parentNode,a.content);break;case i.REMOVE_NODE:}}};a.measureMethods(c,"DOMChildrenOperations",{updateTextContent:"updateTextContent"}),e.exports=c}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){return e.substring(1,e.indexOf(" "))}var r=n(30),i=n(93),a=n(27),s=n(96),l=n(20),u=/^(<[^ \/>]+)/,c="data-danger-index",d={dangerouslyRenderMarkup:function(e){r.canUseDOM?void 0:"production"!==t.env.NODE_ENV?l(!1,"dangerouslyRenderMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString for server rendering."):l(!1);for(var n,d={},p=0;p<e.length;p++)e[p]?void 0:"production"!==t.env.NODE_ENV?l(!1,"dangerouslyRenderMarkup(...): Missing markup."):l(!1),n=o(e[p]),n=s(n)?n:"*",d[n]=d[n]||[],d[n][p]=e[p];var f=[],h=0;for(n in d)if(d.hasOwnProperty(n)){var v,m=d[n];for(v in m)if(m.hasOwnProperty(v)){var y=m[v];m[v]=y.replace(u,"$1 "+c+'="'+v+'" ')}for(var g=i(m.join(""),a),_=0;_<g.length;++_){var b=g[_];b.hasAttribute&&b.hasAttribute(c)?(v=+b.getAttribute(c),b.removeAttribute(c),f.hasOwnProperty(v)?"production"!==t.env.NODE_ENV?l(!1,"Danger: Assigning to an already-occupied result index."):l(!1):void 0,f[v]=b,h+=1):"production"!==t.env.NODE_ENV&&console.error("Danger: Discarding unexpected node:",b)}}return h!==f.length?"production"!==t.env.NODE_ENV?l(!1,"Danger: Did not assign to every index of resultList."):l(!1):void 0,f.length!==e.length?"production"!==t.env.NODE_ENV?l(!1,"Danger: Expected markup to render %s nodes, but rendered %s.",e.length,f.length):l(!1):void 0,f},dangerouslyReplaceNodeWithMarkup:function(e,n){r.canUseDOM?void 0:"production"!==t.env.NODE_ENV?l(!1,"dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a worker thread. Make sure `window` and `document` are available globally before requiring React when unit testing or use ReactDOMServer.renderToString() for server rendering."):l(!1),n?void 0:"production"!==t.env.NODE_ENV?l(!1,"dangerouslyReplaceNodeWithMarkup(...): Missing markup."):l(!1),"html"===e.tagName.toLowerCase()?"production"!==t.env.NODE_ENV?l(!1,"dangerouslyReplaceNodeWithMarkup(...): Cannot replace markup of the <html> node. This is because browser quirks make this unreliable and/or slow. If you want to render to the root you must use server rendering. See ReactDOMServer.renderToString()."):l(!1):void 0;var o;o="string"==typeof n?i(n,a)[0]:n,e.parentNode.replaceChild(o,e)}};e.exports=d}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){var t=e.match(c);return t&&t[1].toLowerCase()}function r(e,n){var r=u;u?void 0:"production"!==t.env.NODE_ENV?l(!1,"createNodesFromMarkup dummy not initialized"):l(!1);var i=o(e),c=i&&s(i);if(c){r.innerHTML=c[1]+e+c[2];for(var d=c[0];d--;)r=r.lastChild}else r.innerHTML=e;var p=r.getElementsByTagName("script");p.length&&(n?void 0:"production"!==t.env.NODE_ENV?l(!1,"createNodesFromMarkup(...): Unexpected <script> element rendered."):l(!1),a(p).forEach(n));for(var f=a(r.childNodes);r.lastChild;)r.removeChild(r.lastChild);return f}var i=n(30),a=n(94),s=n(96),l=n(20),u=i.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;e.exports=r}).call(t,n(16))},function(e,t,n){"use strict";function o(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 o(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=n(95);e.exports=r},function(e,t,n){(function(t){"use strict";function o(e){var n=e.length;if(Array.isArray(e)||"object"!=typeof e&&"function"!=typeof e?"production"!==t.env.NODE_ENV?r(!1,"toArray: Array-like object expected"):r(!1):void 0,"number"!=typeof n?"production"!==t.env.NODE_ENV?r(!1,"toArray: Object needs a length property"):r(!1):void 0,0===n||n-1 in e?void 0:"production"!==t.env.NODE_ENV?r(!1,"toArray: Object should have keys for indices"):r(!1),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(o){}for(var i=Array(n),a=0;n>a;a++)i[a]=e[a];return i}var r=n(20);e.exports=o}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){return a?void 0:"production"!==t.env.NODE_ENV?i(!1,"Markup wrapping node not initialized"):i(!1),p.hasOwnProperty(e)||(e="*"),s.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",s[e]=!a.firstChild),s[e]?p[e]:null}var r=n(30),i=n(20),a=r.canUseDOM?document.createElement("div"):null,s={},l=[1,'<select multiple="true">',"</select>"],u=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],d=[1,'<svg xmlns="http://www.w3.org/2000/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:l,option:l,caption:u,colgroup:u,tbody:u,tfoot:u,thead:u,td:c,th:c},f=["circle","clipPath","defs","ellipse","g","image","line","linearGradient","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","text","tspan"];f.forEach(function(e){p[e]=d,s[e]=!0}),e.exports=o}).call(t,n(16))},function(e,t,n){"use strict";var o=n(19),r=o({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,SET_MARKUP:null,TEXT_CONTENT:null});e.exports=r},function(e,t,n){"use strict";var o=n(30),r=n(99),i=n(84),a=function(e,t){e.textContent=t};o.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,r(t))})),e.exports=a},function(e,t){"use strict";function n(e){return r[e]}function o(e){return(""+e).replace(i,n)}var r={"&":"&",">":">","<":"<",'"':""","'":"'"},i=/[&><"']/g;e.exports=o},function(e,t,n){(function(t){"use strict";function o(e){return d.hasOwnProperty(e)?!0:c.hasOwnProperty(e)?!1:u.test(e)?(d[e]=!0,!0):(c[e]=!0,"production"!==t.env.NODE_ENV?l(!1,"Invalid attribute name: `%s`",e):void 0,!1)}function r(e,t){return null==t||e.hasBooleanValue&&!t||e.hasNumericValue&&isNaN(t)||e.hasPositiveNumericValue&&1>t||e.hasOverloadedBooleanValue&&t===!1}var i=n(58),a=n(42),s=n(101),l=n(26),u=/^[a-zA-Z_][\w\.\-]*$/,c={},d={};if("production"!==t.env.NODE_ENV)var p={children:!0,dangerouslySetInnerHTML:!0,key:!0,ref:!0},f={},h=function(e){if(!(p.hasOwnProperty(e)&&p[e]||f.hasOwnProperty(e)&&f[e])){f[e]=!0;var n=e.toLowerCase(),o=i.isCustomAttribute(n)?n:i.getPossibleStandardName.hasOwnProperty(n)?i.getPossibleStandardName[n]:null;"production"!==t.env.NODE_ENV?l(null==o,"Unknown DOM property %s. Did you mean %s?",e,o):void 0}};var v={createMarkupForID:function(e){return i.ID_ATTRIBUTE_NAME+"="+s(e)},setAttributeForID:function(e,t){e.setAttribute(i.ID_ATTRIBUTE_NAME,t)},createMarkupForProperty:function(e,n){var o=i.properties.hasOwnProperty(e)?i.properties[e]:null;if(o){if(r(o,n))return"";var a=o.attributeName;return o.hasBooleanValue||o.hasOverloadedBooleanValue&&n===!0?a+'=""':a+"="+s(n)}return i.isCustomAttribute(e)?null==n?"":e+"="+s(n):("production"!==t.env.NODE_ENV&&h(e),null)},createMarkupForCustomAttribute:function(e,t){return o(e)&&null!=t?e+"="+s(t):""},setValueForProperty:function(e,n,o){var a=i.properties.hasOwnProperty(n)?i.properties[n]:null;if(a){var s=a.mutationMethod;if(s)s(e,o);else if(r(a,o))this.deleteValueForProperty(e,n);else if(a.mustUseAttribute){var l=a.attributeName,u=a.attributeNamespace;u?e.setAttributeNS(u,l,""+o):a.hasBooleanValue||a.hasOverloadedBooleanValue&&o===!0?e.setAttribute(l,""):e.setAttribute(l,""+o)}else{var c=a.propertyName;a.hasSideEffects&&""+e[c]==""+o||(e[c]=o)}}else i.isCustomAttribute(n)?v.setValueForAttribute(e,n,o):"production"!==t.env.NODE_ENV&&h(n)},setValueForAttribute:function(e,t,n){o(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,n){var o=i.properties.hasOwnProperty(n)?i.properties[n]:null;if(o){var r=o.mutationMethod;if(r)r(e,void 0);else if(o.mustUseAttribute)e.removeAttribute(o.attributeName);else{var a=o.propertyName,s=i.getDefaultValueForProperty(e.nodeName,a);o.hasSideEffects&&""+e[a]===s||(e[a]=s)}}else i.isCustomAttribute(n)?e.removeAttribute(n):"production"!==t.env.NODE_ENV&&h(n)}};a.measureMethods(v,"DOMPropertyOperations",{setValueForProperty:"setValueForProperty",setValueForAttribute:"setValueForAttribute",deleteValueForProperty:"deleteValueForProperty"}),e.exports=v}).call(t,n(16))},function(e,t,n){"use strict";function o(e){return'"'+r(e)+'"'}var r=n(99);e.exports=o},function(e,t,n){"use strict";function o(){this.reinitializeTransaction()}var r=n(40),i=n(46),a=n(33),s=n(27),l={initialize:s,close:function(){p.isBatchingUpdates=!1}},u={initialize:s,close:r.flushBatchedUpdates.bind(r)},c=[u,l];a(o.prototype,i.Mixin,{getTransactionWrappers:function(){return c}});var d=new o,p={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,o,r,i){var a=p.isBatchingUpdates;p.isBatchingUpdates=!0,a?e(t,n,o,r,i):d.perform(e,null,t,n,o,r,i)}};e.exports=p},function(e,t,n){(function(t){"use strict";function o(e){if(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" This DOM node was rendered by `"+n+"`."}}return""}function r(){if("production"!==t.env.NODE_ENV){var e=this._reactInternalComponent;"production"!==t.env.NODE_ENV?Y(!1,"ReactDOMComponent: Do not access .getDOMNode() of a DOM node; instead, use the node directly.%s",o(e)):void 0}return this}function i(){var e=this._reactInternalComponent;return"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?Y(!1,"ReactDOMComponent: Do not access .isMounted() of a DOM node.%s",o(e)):void 0),!!e}function a(){if("production"!==t.env.NODE_ENV){var e=this._reactInternalComponent;"production"!==t.env.NODE_ENV?Y(!1,"ReactDOMComponent: Do not access .setState(), .replaceState(), or .forceUpdate() of a DOM node. This is a no-op.%s",o(e)):void 0}}function s(e,n){var r=this._reactInternalComponent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?Y(!1,"ReactDOMComponent: Do not access .setProps() of a DOM node. Instead, call ReactDOM.render again at the top level.%s",o(r)):void 0),r&&(L.enqueueSetPropsInternal(r,e),n&&L.enqueueCallbackInternal(r,n))}function l(e,n){var r=this._reactInternalComponent;"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?Y(!1,"ReactDOMComponent: Do not access .replaceProps() of a DOM node. Instead, call ReactDOM.render again at the top level.%s",o(r)):void 0),r&&(L.enqueueReplacePropsInternal(r,e),n&&L.enqueueCallbackInternal(r,n))}function u(e){if("object"==typeof e){if(Array.isArray(e))return"["+e.map(u).join(", ")+"]";var t=[];for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var o=/^[a-z$_][\w$_]*$/i.test(n)?n:JSON.stringify(n);t.push(o+": "+u(e[n]))}return"{"+t.join(", ")+"}"}return"string"==typeof e?JSON.stringify(e):"function"==typeof e?"[function object]":String(e)}function c(e,n,o){if(null!=e&&null!=n&&!K(e,n)){var r,i=o._tag,a=o._currentElement._owner;a&&(r=a.getName());var s=r+"|"+i;oe.hasOwnProperty(s)||(oe[s]=!0,"production"!==t.env.NODE_ENV?Y(!1,"`%s` was passed a style object that has previously been mutated. Mutating `style` is deprecated. Consider cloning it beforehand. Check the `render` %s. Previous style: %s. Mutated style: %s.",i,a?"of `"+r+"`":"using <"+i+">",u(e),u(n)):void 0)}}function d(e,n){n&&("production"!==t.env.NODE_ENV&&se[e._tag]&&("production"!==t.env.NODE_ENV?Y(null==n.children&&null==n.dangerouslySetInnerHTML,"%s is a void element tag and must not have `children` or use `props.dangerouslySetInnerHTML`.%s",e._tag,e._currentElement._owner?" Check the render method of "+e._currentElement._owner.getName()+".":""):void 0),null!=n.dangerouslySetInnerHTML&&(null!=n.children?"production"!==t.env.NODE_ENV?F(!1,"Can only set one of `children` or `props.dangerouslySetInnerHTML`."):F(!1):void 0,"object"==typeof n.dangerouslySetInnerHTML&&te in n.dangerouslySetInnerHTML?void 0:"production"!==t.env.NODE_ENV?F(!1,"`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. Please visit https://fb.me/react-invariant-dangerously-set-inner-html for more information."):F(!1)),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?Y(null==n.innerHTML,"Directly setting property `innerHTML` is not permitted. For more information, lookup documentation on `dangerouslySetInnerHTML`."):void 0,"production"!==t.env.NODE_ENV?Y(!n.contentEditable||null==n.children,"A component is `contentEditable` and contains `children` managed by React. It is now your responsibility to guarantee that none of those nodes are unexpectedly modified or duplicated. This is probably not intentional."):void 0),null!=n.style&&"object"!=typeof n.style?"production"!==t.env.NODE_ENV?F(!1,"The `style` prop expects a mapping from style properties to values, not a string. For example, style={{marginRight: spacing + 'em'}} when using JSX.%s",o(e)):F(!1):void 0)}function p(e,n,o,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?Y("onScroll"!==n||W("scroll",!0),"This browser doesn't support the `onScroll` event"):void 0);var i=k.findReactContainerForID(e);if(i){var a=i.nodeType===ne?i.ownerDocument:i;Q(n,a)}r.getReactMountReady().enqueue(f,{id:e,registrationName:n,listener:o})}function f(){var e=this;D.putListener(e.id,e.registrationName,e.listener)}function h(){var e=this;e._rootNodeID?void 0:"production"!==t.env.NODE_ENV?F(!1,"Must be mounted to trap events"):F(!1);var n=k.getNode(e._rootNodeID);switch(n?void 0:"production"!==t.env.NODE_ENV?F(!1,"trapBubbledEvent(...): Requires node to be rendered."):F(!1),e._tag){case"iframe":e._wrapperState.listeners=[D.trapBubbledEvent(x.topLevelTypes.topLoad,"load",n)];break;case"video":case"audio":e._wrapperState.listeners=[];for(var o in re)re.hasOwnProperty(o)&&e._wrapperState.listeners.push(D.trapBubbledEvent(x.topLevelTypes[o],re[o],n));break;case"img":e._wrapperState.listeners=[D.trapBubbledEvent(x.topLevelTypes.topError,"error",n),D.trapBubbledEvent(x.topLevelTypes.topLoad,"load",n)];break;case"form":e._wrapperState.listeners=[D.trapBubbledEvent(x.topLevelTypes.topReset,"reset",n),D.trapBubbledEvent(x.topLevelTypes.topSubmit,"submit",n)]}}function v(){P.mountReadyWrapper(this)}function m(){M.postUpdateWrapper(this)}function y(e){ce.call(ue,e)||(le.test(e)?void 0:"production"!==t.env.NODE_ENV?F(!1,"Invalid tag: %s",e):F(!1),ue[e]=!0)}function g(e,t){e=j({},e);var n=e[G.ancestorInfoContextKey];return e[G.ancestorInfoContextKey]=G.updatedAncestorInfo(n,t._tag,t),e}function _(e,t){return e.indexOf("-")>=0||null!=t.is}function b(e){y(e),this._tag=e.toLowerCase(),this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null,this._wrapperState=null,this._topLevelWrapper=null,this._nodeWithLegacyProperties=null,"production"!==t.env.NODE_ENV&&(this._unprocessedContextDev=null,this._processedContextDev=null)}var E,C=n(104),N=n(106),w=n(58),S=n(100),x=n(18),D=n(59),O=n(89),T=n(114),P=n(115),R=n(119),M=n(122),I=n(123),k=n(57),A=n(124),V=n(42),L=n(71),j=n(33),U=n(64),z=n(99),F=n(20),W=n(48),H=n(38),B=n(84),q=n(98),K=n(6),G=n(85),Y=n(26),$=D.deleteListener,Q=D.listenTo,X=D.registrationNameModules,J={string:!0,number:!0},Z=H({children:null}),ee=H({style:null}),te=H({__html:null}),ne=1;"production"!==t.env.NODE_ENV&&(E={props:{enumerable:!1,get:function(){var e=this._reactInternalComponent;return"production"!==t.env.NODE_ENV?Y(!1,"ReactDOMComponent: Do not access .props of a DOM node; instead, recreate the props as `render` did originally or read the DOM properties/attributes directly from this node (e.g., this.refs.box.className).%s",o(e)):void 0,e._currentElement.props}}});var oe={},re={topAbort:"abort",topCanPlay:"canplay",topCanPlayThrough:"canplaythrough",topDurationChange:"durationchange",topEmptied:"emptied",topEncrypted:"encrypted",topEnded:"ended",topError:"error",topLoadedData:"loadeddata",topLoadedMetadata:"loadedmetadata",topLoadStart:"loadstart",topPause:"pause",topPlay:"play",topPlaying:"playing",topProgress:"progress",topRateChange:"ratechange",topSeeked:"seeked",topSeeking:"seeking",topStalled:"stalled",topSuspend:"suspend",topTimeUpdate:"timeupdate",topVolumeChange:"volumechange",topWaiting:"waiting"},ie={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},ae={listing:!0,pre:!0,textarea:!0},se=j({menuitem:!0},ie),le=/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/,ue={},ce={}.hasOwnProperty;b.displayName="ReactDOMComponent",b.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,n,o){this._rootNodeID=e;var r=this._currentElement.props;switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":this._wrapperState={listeners:null},n.getReactMountReady().enqueue(h,this);break;case"button":r=T.getNativeProps(this,r,o);break;case"input":P.mountWrapper(this,r,o),r=P.getNativeProps(this,r,o);break;case"option":R.mountWrapper(this,r,o),r=R.getNativeProps(this,r,o);break;case"select":M.mountWrapper(this,r,o),r=M.getNativeProps(this,r,o),o=M.processChildContext(this,r,o);break;case"textarea":I.mountWrapper(this,r,o),r=I.getNativeProps(this,r,o)}d(this,r),"production"!==t.env.NODE_ENV&&o[G.ancestorInfoContextKey]&&G(this._tag,this,o[G.ancestorInfoContextKey]),"production"!==t.env.NODE_ENV&&(this._unprocessedContextDev=o,this._processedContextDev=g(o,this),o=this._processedContextDev);var i;if(n.useCreateElement){var a=o[k.ownerDocumentContextKey],s=a.createElement(this._currentElement.type);S.setAttributeForID(s,this._rootNodeID),k.getID(s),this._updateDOMProperties({},r,n,s),this._createInitialChildren(n,r,o,s),i=s}else{var l=this._createOpenTagMarkupAndPutListeners(n,r),u=this._createContentMarkup(n,r,o);i=!u&&ie[this._tag]?l+"/>":l+">"+u+"</"+this._currentElement.type+">"}switch(this._tag){case"input":n.getReactMountReady().enqueue(v,this);case"button":case"select":case"textarea":r.autoFocus&&n.getReactMountReady().enqueue(C.focusDOMComponent,this)}return i},_createOpenTagMarkupAndPutListeners:function(e,n){var o="<"+this._currentElement.type;for(var r in n)if(n.hasOwnProperty(r)){var i=n[r];if(null!=i)if(X.hasOwnProperty(r))i&&p(this._rootNodeID,r,i,e);else{r===ee&&(i&&("production"!==t.env.NODE_ENV&&(this._previousStyle=i),i=this._previousStyleCopy=j({},n.style)),i=N.createMarkupForStyles(i));var a=null;null!=this._tag&&_(this._tag,n)?r!==Z&&(a=S.createMarkupForCustomAttribute(r,i)):a=S.createMarkupForProperty(r,i),a&&(o+=" "+a)}}if(e.renderToStaticMarkup)return o;var s=S.createMarkupForID(this._rootNodeID);return o+" "+s},_createContentMarkup:function(e,t,n){var o="",r=t.dangerouslySetInnerHTML;if(null!=r)null!=r.__html&&(o=r.__html);else{var i=J[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)o=z(i);else if(null!=a){var s=this.mountChildren(a,e,n);o=s.join("")}}return ae[this._tag]&&"\n"===o.charAt(0)?"\n"+o:o},_createInitialChildren:function(e,t,n,o){var r=t.dangerouslySetInnerHTML;if(null!=r)null!=r.__html&&B(o,r.__html);else{var i=J[typeof t.children]?t.children:null,a=null!=i?null:t.children;if(null!=i)q(o,i);else if(null!=a)for(var s=this.mountChildren(a,e,n),l=0;l<s.length;l++)o.appendChild(s[l])}},receiveComponent:function(e,t,n){var o=this._currentElement;this._currentElement=e,this.updateComponent(t,o,e,n)},updateComponent:function(e,n,o,r){var i=n.props,a=this._currentElement.props;switch(this._tag){case"button":i=T.getNativeProps(this,i),a=T.getNativeProps(this,a);break;case"input":P.updateWrapper(this),i=P.getNativeProps(this,i),a=P.getNativeProps(this,a);break;case"option":i=R.getNativeProps(this,i),a=R.getNativeProps(this,a);break;case"select":i=M.getNativeProps(this,i),a=M.getNativeProps(this,a);break;case"textarea":I.updateWrapper(this),i=I.getNativeProps(this,i),a=I.getNativeProps(this,a)}"production"!==t.env.NODE_ENV&&(this._unprocessedContextDev!==r&&(this._unprocessedContextDev=r,this._processedContextDev=g(r,this)),r=this._processedContextDev),d(this,a),this._updateDOMProperties(i,a,e,null),this._updateDOMChildren(i,a,e,r),!U&&this._nodeWithLegacyProperties&&(this._nodeWithLegacyProperties.props=a),"select"===this._tag&&e.getReactMountReady().enqueue(m,this)},_updateDOMProperties:function(e,n,o,r){var i,a,s;for(i in e)if(!n.hasOwnProperty(i)&&e.hasOwnProperty(i))if(i===ee){var l=this._previousStyleCopy;for(a in l)l.hasOwnProperty(a)&&(s=s||{},s[a]="");this._previousStyleCopy=null}else X.hasOwnProperty(i)?e[i]&&$(this._rootNodeID,i):(w.properties[i]||w.isCustomAttribute(i))&&(r||(r=k.getNode(this._rootNodeID)),S.deleteValueForProperty(r,i));for(i in n){var u=n[i],d=i===ee?this._previousStyleCopy:e[i];if(n.hasOwnProperty(i)&&u!==d)if(i===ee)if(u?("production"!==t.env.NODE_ENV&&(c(this._previousStyleCopy,this._previousStyle,this),this._previousStyle=u),u=this._previousStyleCopy=j({},u)):this._previousStyleCopy=null,d){for(a in d)!d.hasOwnProperty(a)||u&&u.hasOwnProperty(a)||(s=s||{},s[a]="");for(a in u)u.hasOwnProperty(a)&&d[a]!==u[a]&&(s=s||{},s[a]=u[a])}else s=u;else X.hasOwnProperty(i)?u?p(this._rootNodeID,i,u,o):d&&$(this._rootNodeID,i):_(this._tag,n)?(r||(r=k.getNode(this._rootNodeID)),i===Z&&(u=null),S.setValueForAttribute(r,i,u)):(w.properties[i]||w.isCustomAttribute(i))&&(r||(r=k.getNode(this._rootNodeID)),null!=u?S.setValueForProperty(r,i,u):S.deleteValueForProperty(r,i))}s&&(r||(r=k.getNode(this._rootNodeID)),N.setValueForStyles(r,s))},_updateDOMChildren:function(e,t,n,o){var r=J[typeof e.children]?e.children:null,i=J[typeof t.children]?t.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,s=t.dangerouslySetInnerHTML&&t.dangerouslySetInnerHTML.__html,l=null!=r?null:e.children,u=null!=i?null:t.children,c=null!=r||null!=a,d=null!=i||null!=s;null!=l&&null==u?this.updateChildren(null,n,o):c&&!d&&this.updateTextContent(""),null!=i?r!==i&&this.updateTextContent(""+i):null!=s?a!==s&&this.updateMarkup(""+s):null!=u&&this.updateChildren(u,n,o);
},unmountComponent:function(){switch(this._tag){case"iframe":case"img":case"form":case"video":case"audio":var e=this._wrapperState.listeners;if(e)for(var n=0;n<e.length;n++)e[n].remove();break;case"input":P.unmountWrapper(this);break;case"html":case"head":case"body":"production"!==t.env.NODE_ENV?F(!1,"<%s> tried to unmount. Because of cross-browser quirks it is impossible to unmount some top-level components (eg <html>, <head>, and <body>) reliably and efficiently. To fix this, have a single top-level component that never unmounts render these elements.",this._tag):F(!1)}if(this.unmountChildren(),D.deleteAllListeners(this._rootNodeID),O.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null,this._wrapperState=null,this._nodeWithLegacyProperties){var o=this._nodeWithLegacyProperties;o._reactInternalComponent=null,this._nodeWithLegacyProperties=null}},getPublicInstance:function(){if(!this._nodeWithLegacyProperties){var e=k.getNode(this._rootNodeID);e._reactInternalComponent=this,e.getDOMNode=r,e.isMounted=i,e.setState=a,e.replaceState=a,e.forceUpdate=a,e.setProps=s,e.replaceProps=l,"production"!==t.env.NODE_ENV&&U?Object.defineProperties(e,E):e.props=this._currentElement.props,this._nodeWithLegacyProperties=e}return this._nodeWithLegacyProperties}},V.measureMethods(b,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),j(b.prototype,b.Mixin,A.Mixin),e.exports=b}).call(t,n(16))},function(e,t,n){"use strict";var o=n(57),r=n(88),i=n(105),a={componentDidMount:function(){this.props.autoFocus&&i(r(this))}},s={Mixin:a,focusDOMComponent:function(){i(o.getNode(this._rootNodeID))}};e.exports=s},function(e,t){"use strict";function n(e){try{e.focus()}catch(t){}}e.exports=n},function(e,t,n){(function(t){"use strict";var o=n(107),r=n(30),i=n(42),a=n(108),s=n(110),l=n(111),u=n(113),c=n(26),d=u(function(e){return l(e)}),p=!1,f="cssFloat";if(r.canUseDOM){var h=document.createElement("div").style;try{h.font=""}catch(v){p=!0}void 0===document.documentElement.style.cssFloat&&(f="styleFloat")}if("production"!==t.env.NODE_ENV)var m=/^(?:webkit|moz|o)[A-Z]/,y=/;\s*$/,g={},_={},b=function(e){g.hasOwnProperty(e)&&g[e]||(g[e]=!0,"production"!==t.env.NODE_ENV?c(!1,"Unsupported style property %s. Did you mean %s?",e,a(e)):void 0)},E=function(e){g.hasOwnProperty(e)&&g[e]||(g[e]=!0,"production"!==t.env.NODE_ENV?c(!1,"Unsupported vendor-prefixed style property %s. Did you mean %s?",e,e.charAt(0).toUpperCase()+e.slice(1)):void 0)},C=function(e,n){_.hasOwnProperty(n)&&_[n]||(_[n]=!0,"production"!==t.env.NODE_ENV?c(!1,'Style property values shouldn\'t contain a semicolon. Try "%s: %s" instead.',e,n.replace(y,"")):void 0)},N=function(e,t){e.indexOf("-")>-1?b(e):m.test(e)?E(e):y.test(t)&&C(e,t)};var w={createMarkupForStyles:function(e){var n="";for(var o in e)if(e.hasOwnProperty(o)){var r=e[o];"production"!==t.env.NODE_ENV&&N(o,r),null!=r&&(n+=d(o)+":",n+=s(o,r)+";")}return n||null},setValueForStyles:function(e,n){var r=e.style;for(var i in n)if(n.hasOwnProperty(i)){"production"!==t.env.NODE_ENV&&N(i,n[i]);var a=s(i,n[i]);if("float"===i&&(i=f),a)r[i]=a;else{var l=p&&o.shorthandPropertyExpansions[i];if(l)for(var u in l)r[u]="";else r[i]=""}}}};i.measureMethods(w,"CSSPropertyOperations",{setValueForStyles:"setValueForStyles"}),e.exports=w}).call(t,n(16))},function(e,t){"use strict";function n(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={animationIterationCount:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,stopOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},r=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){r.forEach(function(t){o[n(t,e)]=o[e]})});var i={background:{backgroundAttachment:!0,backgroundColor:!0,backgroundImage:!0,backgroundPositionX:!0,backgroundPositionY:!0,backgroundRepeat:!0},backgroundPosition:{backgroundPositionX:!0,backgroundPositionY:!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},outline:{outlineWidth:!0,outlineStyle:!0,outlineColor:!0}},a={isUnitlessNumber:o,shorthandPropertyExpansions:i};e.exports=a},function(e,t,n){"use strict";function o(e){return r(e.replace(i,"ms-"))}var r=n(109),i=/^-ms-/;e.exports=o},function(e,t){"use strict";function n(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;e.exports=n},function(e,t,n){"use strict";function o(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var o=isNaN(t);return o||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var r=n(107),i=r.isUnitlessNumber;e.exports=o},function(e,t,n){"use strict";function o(e){return r(e).replace(i,"-ms-")}var r=n(112),i=/^ms-/;e.exports=o},function(e,t){"use strict";function n(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;e.exports=n},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]}}e.exports=n},function(e,t){"use strict";var n={onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0},o={getNativeProps:function(e,t,o){if(!t.disabled)return t;var r={};for(var i in t)t.hasOwnProperty(i)&&!n[i]&&(r[i]=t[i]);return r}};e.exports=o},function(e,t,n){(function(t){"use strict";function o(){this._rootNodeID&&p.updateWrapper(this)}function r(e){var n=this._currentElement.props,r=a.executeOnChange(n,e);l.asap(o,this);var i=n.name;if("radio"===n.type&&null!=i){for(var u=s.getNode(this._rootNodeID),p=u;p.parentNode;)p=p.parentNode;for(var f=p.querySelectorAll("input[name="+JSON.stringify(""+i)+'][type="radio"]'),h=0;h<f.length;h++){var v=f[h];if(v!==u&&v.form===u.form){var m=s.getID(v);m?void 0:"production"!==t.env.NODE_ENV?c(!1,"ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."):c(!1);var y=d[m];y?void 0:"production"!==t.env.NODE_ENV?c(!1,"ReactDOMInput: Unknown radio button ID %s.",m):c(!1),l.asap(o,y)}}}return r}var i=n(90),a=n(116),s=n(57),l=n(40),u=n(33),c=n(20),d={},p={getNativeProps:function(e,t,n){var o=a.getValue(t),r=a.getChecked(t),i=u({},t,{defaultChecked:void 0,defaultValue:void 0,value:null!=o?o:e._wrapperState.initialValue,checked:null!=r?r:e._wrapperState.initialChecked,onChange:e._wrapperState.onChange});return i},mountWrapper:function(e,n){"production"!==t.env.NODE_ENV&&a.checkPropTypes("input",n,e._currentElement._owner);var o=n.defaultValue;e._wrapperState={initialChecked:n.defaultChecked||!1,initialValue:null!=o?o:null,onChange:r.bind(e)}},mountReadyWrapper:function(e){d[e._rootNodeID]=e},unmountWrapper:function(e){delete d[e._rootNodeID]},updateWrapper:function(e){var t=e._currentElement.props,n=t.checked;null!=n&&i.updatePropertyByID(e._rootNodeID,"checked",n||!1);var o=a.getValue(t);null!=o&&i.updatePropertyByID(e._rootNodeID,"value",""+o)}};e.exports=p}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e){null!=e.checkedLink&&null!=e.valueLink?"production"!==t.env.NODE_ENV?u(!1,"Cannot provide a checkedLink and a valueLink. If you want to use checkedLink, you probably don't want to use valueLink and vice versa."):u(!1):void 0}function r(e){o(e),null!=e.value||null!=e.onChange?"production"!==t.env.NODE_ENV?u(!1,"Cannot provide a valueLink and a value or onChange event. If you want to use value or onChange, you probably don't want to use valueLink."):u(!1):void 0}function i(e){o(e),null!=e.checked||null!=e.onChange?"production"!==t.env.NODE_ENV?u(!1,"Cannot provide a checkedLink and a checked property or onChange event. If you want to use checked or onChange, you probably don't want to use checkedLink"):u(!1):void 0}function a(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}var s=n(117),l=n(79),u=n(20),c=n(26),d={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},p={value:function(e,t,n){return!e[t]||d[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,n){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},f={},h={checkPropTypes:function(e,n,o){for(var r in p){if(p.hasOwnProperty(r))var i=p[r](n,r,e,l.prop);if(i instanceof Error&&!(i.message in f)){f[i.message]=!0;var s=a(o);"production"!==t.env.NODE_ENV?c(!1,"Failed form propType: %s%s",i.message,s):void 0}}},getValue:function(e){return e.valueLink?(r(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},executeOnChange:function(e,t){return e.valueLink?(r(e),e.valueLink.requestChange(t.target.value)):e.checkedLink?(i(e),e.checkedLink.requestChange(t.target.checked)):e.onChange?e.onChange.call(void 0,t):void 0}};e.exports=h}).call(t,n(16))},function(e,t,n){"use strict";function o(e){function t(t,n,o,r,i,a){if(r=r||C,a=a||o,null==n[o]){var s=_[i];return t?new Error("Required "+s+" `"+a+"` was not specified in "+("`"+r+"`.")):null}return e(n,o,r,i,a)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function r(e){function t(t,n,o,r,i){var a=t[n],s=v(a);if(s!==e){var l=_[r],u=m(a);return new Error("Invalid "+l+" `"+i+"` of type "+("`"+u+"` supplied to `"+o+"`, expected ")+("`"+e+"`."))}return null}return o(t)}function i(){return o(b.thatReturns(null))}function a(e){function t(t,n,o,r,i){var a=t[n];if(!Array.isArray(a)){var s=_[r],l=v(a);return new Error("Invalid "+s+" `"+i+"` of type "+("`"+l+"` supplied to `"+o+"`, expected an array."))}for(var u=0;u<a.length;u++){var c=e(a,u,o,r,i+"["+u+"]");if(c instanceof Error)return c}return null}return o(t)}function s(){function e(e,t,n,o,r){if(!g.isValidElement(e[t])){var i=_[o];return new Error("Invalid "+i+" `"+r+"` supplied to "+("`"+n+"`, expected a single ReactElement."))}return null}return o(e)}function l(e){function t(t,n,o,r,i){if(!(t[n]instanceof e)){var a=_[r],s=e.name||C,l=y(t[n]);return new Error("Invalid "+a+" `"+i+"` of type "+("`"+l+"` supplied to `"+o+"`, expected ")+("instance of `"+s+"`."))}return null}return o(t)}function u(e){function t(t,n,o,r,i){for(var a=t[n],s=0;s<e.length;s++)if(a===e[s])return null;var l=_[r],u=JSON.stringify(e);return new Error("Invalid "+l+" `"+i+"` of value `"+a+"` "+("supplied to `"+o+"`, expected one of "+u+"."))}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOf, expected an instance of array.")})}function c(e){function t(t,n,o,r,i){var a=t[n],s=v(a);if("object"!==s){var l=_[r];return new Error("Invalid "+l+" `"+i+"` of type "+("`"+s+"` supplied to `"+o+"`, expected an object."))}for(var u in a)if(a.hasOwnProperty(u)){var c=e(a,u,o,r,i+"."+u);if(c instanceof Error)return c}return null}return o(t)}function d(e){function t(t,n,o,r,i){for(var a=0;a<e.length;a++){var s=e[a];if(null==s(t,n,o,r,i))return null}var l=_[r];return new Error("Invalid "+l+" `"+i+"` supplied to "+("`"+o+"`."))}return o(Array.isArray(e)?t:function(){return new Error("Invalid argument supplied to oneOfType, expected an instance of array.")})}function p(){function e(e,t,n,o,r){if(!h(e[t])){var i=_[o];return new Error("Invalid "+i+" `"+r+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return o(e)}function f(e){function t(t,n,o,r,i){var a=t[n],s=v(a);if("object"!==s){var l=_[r];return new Error("Invalid "+l+" `"+i+"` of type `"+s+"` "+("supplied to `"+o+"`, expected `object`."))}for(var u in e){var c=e[u];if(c){var d=c(a,u,o,r,i+"."+u);if(d)return d}}return null}return o(t)}function h(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(h);if(null===e||g.isValidElement(e))return!0;var t=E(e);if(!t)return!1;var n,o=t.call(e);if(t!==e.entries){for(;!(n=o.next()).done;)if(!h(n.value))return!1}else for(;!(n=o.next()).done;){var r=n.value;if(r&&!h(r[1]))return!1}return!0;default:return!1}}function v(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function m(e){var t=v(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function y(e){return e.constructor&&e.constructor.name?e.constructor.name:"<<anonymous>>"}var g=n(63),_=n(80),b=n(27),E=n(118),C="<<anonymous>>",N={array:r("array"),bool:r("boolean"),func:r("function"),number:r("number"),object:r("object"),string:r("string"),any:i(),arrayOf:a,element:s(),instanceOf:l,node:p(),objectOf:c,oneOf:u,oneOfType:d,shape:f};e.exports=N},function(e,t){"use strict";function n(e){var t=e&&(o&&e[o]||e[r]);return"function"==typeof t?t:void 0}var o="function"==typeof Symbol&&Symbol.iterator,r="@@iterator";e.exports=n},function(e,t,n){(function(t){"use strict";var o=n(120),r=n(122),i=n(33),a=n(26),s=r.valueContextKey,l={mountWrapper:function(e,n,o){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?a(null==n.selected,"Use the `defaultValue` or `value` props on <select> instead of setting `selected` on <option>."):void 0);var r=o[s],i=null;if(null!=r)if(i=!1,Array.isArray(r)){for(var l=0;l<r.length;l++)if(""+r[l]==""+n.value){i=!0;break}}else i=""+r==""+n.value;e._wrapperState={selected:i}},getNativeProps:function(e,n,r){var s=i({selected:void 0,children:void 0},n);null!=e._wrapperState.selected&&(s.selected=e._wrapperState.selected);var l="";return o.forEach(n.children,function(e){null!=e&&("string"==typeof e||"number"==typeof e?l+=e:"production"!==t.env.NODE_ENV?a(!1,"Only strings and numbers are supported as <option> children."):void 0)}),l&&(s.children=l),s}};e.exports=l}).call(t,n(16))},function(e,t,n){"use strict";function o(e){return(""+e).replace(b,"//")}function r(e,t){this.func=e,this.context=t,this.count=0}function i(e,t,n){var o=e.func,r=e.context;o.call(r,t,e.count++)}function a(e,t,n){if(null==e)return e;var o=r.getPooled(t,n);y(e,i,o),r.release(o)}function s(e,t,n,o){this.result=e,this.keyPrefix=t,this.func=n,this.context=o,this.count=0}function l(e,t,n){var r=e.result,i=e.keyPrefix,a=e.func,s=e.context,l=a.call(s,t,e.count++);Array.isArray(l)?u(l,r,n,m.thatReturnsArgument):null!=l&&(v.isValidElement(l)&&(l=v.cloneAndReplaceKey(l,i+(l!==t?o(l.key||"")+"/":"")+n)),r.push(l))}function u(e,t,n,r,i){var a="";null!=n&&(a=o(n)+"/");var u=s.getPooled(t,a,r,i);y(e,l,u),s.release(u)}function c(e,t,n){if(null==e)return e;var o=[];return u(e,o,null,t,n),o}function d(e,t,n){return null}function p(e,t){return y(e,d,null)}function f(e){var t=[];return u(e,t,null,m.thatReturnsArgument),t}var h=n(32),v=n(63),m=n(27),y=n(121),g=h.twoArgumentPooler,_=h.fourArgumentPooler,b=/\/(?!\/)/g;r.prototype.destructor=function(){this.func=null,this.context=null,this.count=0},h.addPoolingTo(r,g),s.prototype.destructor=function(){this.result=null,this.keyPrefix=null,this.func=null,this.context=null,this.count=0},h.addPoolingTo(s,_);var E={forEach:a,map:c,mapIntoWithKeyPrefixInternal:u,count:p,toArray:f};e.exports=E},function(e,t,n){(function(t){"use strict";function o(e){return y[e]}function r(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(g,o)}function a(e){return"$"+i(e)}function s(e,n,o,i){var l=typeof e;if("undefined"!==l&&"boolean"!==l||(e=null),null===e||"string"===l||"number"===l||c.isValidElement(e))return o(i,e,""===n?v+r(e,0):n),1;var d,y,g=0,b=""===n?v:n+m;if(Array.isArray(e))for(var E=0;E<e.length;E++)d=e[E],y=b+r(d,E),g+=s(d,y,o,i);else{var C=p(e);if(C){var N,w=C.call(e);if(C!==e.entries)for(var S=0;!(N=w.next()).done;)d=N.value,y=b+r(d,S++),g+=s(d,y,o,i);else for("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?h(_,"Using Maps as children is not yet fully supported. It is an experimental feature that might be removed. Convert it to a sequence / iterable of keyed ReactElements instead."):void 0,_=!0);!(N=w.next()).done;){var x=N.value;x&&(d=x[1],y=b+a(x[0])+m+r(d,0),g+=s(d,y,o,i))}}else if("object"===l){var D="";if("production"!==t.env.NODE_ENV&&(D=" If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons.",e._isReactElement&&(D=" It looks like you're using an element created by a different version of React. Make sure to use only one copy of React."),u.current)){var O=u.current.getName();O&&(D+=" Check the render method of `"+O+"`.")}var T=String(e);"production"!==t.env.NODE_ENV?f(!1,"Objects are not valid as a React child (found: %s).%s","[object Object]"===T?"object with keys {"+Object.keys(e).join(", ")+"}":T,D):f(!1)}}return g}function l(e,t,n){return null==e?0:s(e,"",t,n)}var u=n(61),c=n(63),d=n(66),p=n(118),f=n(20),h=n(26),v=d.SEPARATOR,m=":",y={"=":"=0",".":"=1",":":"=2"},g=/[=.:]/g,_=!1;e.exports=l}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(){if(this._rootNodeID&&this._wrapperState.pendingUpdate){this._wrapperState.pendingUpdate=!1;var e=this._currentElement.props,t=l.getValue(e);null!=t&&a(this,Boolean(e.multiple),t)}}function r(e){if(e){var t=e.getName();if(t)return" Check the render method of `"+t+"`."}return""}function i(e,n){var o=e._currentElement._owner;l.checkPropTypes("select",n,o);for(var i=0;i<h.length;i++){var a=h[i];null!=n[a]&&(n.multiple?"production"!==t.env.NODE_ENV?p(Array.isArray(n[a]),"The `%s` prop supplied to <select> must be an array if `multiple` is true.%s",a,r(o)):void 0:"production"!==t.env.NODE_ENV?p(!Array.isArray(n[a]),"The `%s` prop supplied to <select> must be a scalar value if `multiple` is false.%s",a,r(o)):void 0)}}function a(e,t,n){var o,r,i=u.getNode(e._rootNodeID).options;if(t){for(o={},r=0;r<n.length;r++)o[""+n[r]]=!0;for(r=0;r<i.length;r++){var a=o.hasOwnProperty(i[r].value);i[r].selected!==a&&(i[r].selected=a)}}else{for(o=""+n,r=0;r<i.length;r++)if(i[r].value===o)return void(i[r].selected=!0);i.length&&(i[0].selected=!0)}}function s(e){var t=this._currentElement.props,n=l.executeOnChange(t,e);return this._wrapperState.pendingUpdate=!0,c.asap(o,this),n}var l=n(116),u=n(57),c=n(40),d=n(33),p=n(26),f="__ReactDOMSelect_value$"+Math.random().toString(36).slice(2),h=["value","defaultValue"],v={valueContextKey:f,getNativeProps:function(e,t,n){return d({},t,{onChange:e._wrapperState.onChange,value:void 0})},mountWrapper:function(e,n){"production"!==t.env.NODE_ENV&&i(e,n);var o=l.getValue(n);e._wrapperState={pendingUpdate:!1,initialValue:null!=o?o:n.defaultValue,onChange:s.bind(e),wasMultiple:Boolean(n.multiple)}},processChildContext:function(e,t,n){var o=d({},n);return o[f]=e._wrapperState.initialValue,o},postUpdateWrapper:function(e){var t=e._currentElement.props;e._wrapperState.initialValue=void 0;var n=e._wrapperState.wasMultiple;e._wrapperState.wasMultiple=Boolean(t.multiple);var o=l.getValue(t);null!=o?(e._wrapperState.pendingUpdate=!1,a(e,Boolean(t.multiple),o)):n!==Boolean(t.multiple)&&(null!=t.defaultValue?a(e,Boolean(t.multiple),t.defaultValue):a(e,Boolean(t.multiple),t.multiple?[]:""))}};e.exports=v}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(){this._rootNodeID&&d.updateWrapper(this)}function r(e){var t=this._currentElement.props,n=i.executeOnChange(t,e);return s.asap(o,this),n}var i=n(116),a=n(90),s=n(40),l=n(33),u=n(20),c=n(26),d={getNativeProps:function(e,n,o){null!=n.dangerouslySetInnerHTML?"production"!==t.env.NODE_ENV?u(!1,"`dangerouslySetInnerHTML` does not make sense on <textarea>."):u(!1):void 0;var r=l({},n,{defaultValue:void 0,value:void 0,children:e._wrapperState.initialValue,onChange:e._wrapperState.onChange});return r},mountWrapper:function(e,n){"production"!==t.env.NODE_ENV&&i.checkPropTypes("textarea",n,e._currentElement._owner);var o=n.defaultValue,a=n.children;null!=a&&("production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?c(!1,"Use the `defaultValue` or `value` props instead of setting children on <textarea>."):void 0),null!=o?"production"!==t.env.NODE_ENV?u(!1,"If you supply `defaultValue` on a <textarea>, do not pass children."):u(!1):void 0,Array.isArray(a)&&(a.length<=1?void 0:"production"!==t.env.NODE_ENV?u(!1,"<textarea> can only have at most one child."):u(!1),a=a[0]),o=""+a),null==o&&(o="");var s=i.getValue(n);e._wrapperState={initialValue:""+(null!=s?s:o),onChange:r.bind(e)}},updateWrapper:function(e){var t=e._currentElement.props,n=i.getValue(t);null!=n&&a.updatePropertyByID(e._rootNodeID,"value",""+n)}};e.exports=d}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,t,n){y.push({parentID:e,parentNode:null,type:d.INSERT_MARKUP,markupIndex:g.push(t)-1,content:null,fromIndex:null,toIndex:n})}function r(e,t,n){y.push({parentID:e,parentNode:null,type:d.MOVE_EXISTING,markupIndex:null,content:null,fromIndex:t,toIndex:n})}function i(e,t){y.push({parentID:e,parentNode:null,type:d.REMOVE_NODE,markupIndex:null,content:null,fromIndex:t,toIndex:null})}function a(e,t){y.push({parentID:e,parentNode:null,type:d.SET_MARKUP,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function s(e,t){y.push({parentID:e,parentNode:null,type:d.TEXT_CONTENT,markupIndex:null,content:t,fromIndex:null,toIndex:null})}function l(){y.length&&(c.processChildrenUpdates(y,g),u())}function u(){y.length=0,g.length=0}var c=n(78),d=n(97),p=n(61),f=n(43),h=n(125),v=n(126),m=0,y=[],g=[],_={Mixin:{_reconcilerInstantiateChildren:function(e,n,o){if("production"!==t.env.NODE_ENV&&this._currentElement)try{return p.current=this._currentElement._owner,h.instantiateChildren(e,n,o)}finally{p.current=null}return h.instantiateChildren(e,n,o)},_reconcilerUpdateChildren:function(e,n,o,r){var i;if("production"!==t.env.NODE_ENV&&this._currentElement){try{p.current=this._currentElement._owner,i=v(n)}finally{p.current=null}return h.updateChildren(e,i,o,r)}return i=v(n),h.updateChildren(e,i,o,r)},mountChildren:function(e,t,n){var o=this._reconcilerInstantiateChildren(e,t,n);this._renderedChildren=o;var r=[],i=0;for(var a in o)if(o.hasOwnProperty(a)){var s=o[a],l=this._rootNodeID+a,u=f.mountComponent(s,l,t,n);s._mountIndex=i++,r.push(u)}return r},updateTextContent:function(e){m++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var o in n)n.hasOwnProperty(o)&&this._unmountChild(n[o]);this.setTextContent(e),t=!1}finally{m--,m||(t?u():l())}},updateMarkup:function(e){m++;var t=!0;try{var n=this._renderedChildren;h.unmountChildren(n);for(var o in n)n.hasOwnProperty(o)&&this._unmountChildByName(n[o],o);this.setMarkup(e),t=!1}finally{m--,m||(t?u():l())}},updateChildren:function(e,t,n){m++;var o=!0;try{this._updateChildren(e,t,n),o=!1}finally{m--,m||(o?u():l())}},_updateChildren:function(e,t,n){var o=this._renderedChildren,r=this._reconcilerUpdateChildren(o,e,t,n);if(this._renderedChildren=r,r||o){var i,a=0,s=0;for(i in r)if(r.hasOwnProperty(i)){var l=o&&o[i],u=r[i];l===u?(this.moveChild(l,s,a),a=Math.max(l._mountIndex,a),l._mountIndex=s):(l&&(a=Math.max(l._mountIndex,a),this._unmountChild(l)),this._mountChildByNameAtIndex(u,i,s,t,n)),s++}for(i in o)!o.hasOwnProperty(i)||r&&r.hasOwnProperty(i)||this._unmountChild(o[i])}},unmountChildren:function(){var e=this._renderedChildren;h.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&r(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){o(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){s(this._rootNodeID,e)},setMarkup:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,o,r){var i=this._rootNodeID+t,a=f.mountComponent(e,i,o,r);e._mountIndex=n,this.createChild(e,a)},_unmountChild:function(e){this.removeChild(e),e._mountIndex=null}}};e.exports=_}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,n,o){var r=void 0===e[o];"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(r,"flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",o):void 0),null!=n&&r&&(e[o]=i(n,null))}var r=n(43),i=n(76),a=n(81),s=n(121),l=n(26),u={instantiateChildren:function(e,t,n){if(null==e)return null;var r={};return s(e,o,r),r},updateChildren:function(e,t,n,o){if(!t&&!e)return null;var s;for(s in t)if(t.hasOwnProperty(s)){var l=e&&e[s],u=l&&l._currentElement,c=t[s];if(null!=l&&a(u,c))r.receiveComponent(l,c,n,o),t[s]=l;else{l&&r.unmountComponent(l,s);var d=i(c,null);t[s]=d}}for(s in e)!e.hasOwnProperty(s)||t&&t.hasOwnProperty(s)||r.unmountComponent(e[s]);return t},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];r.unmountComponent(n)}}};e.exports=u}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,n,o){var r=e,i=void 0===r[o];"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?a(i,"flattenChildren(...): Encountered two children with the same key, `%s`. Child keys must be unique; when two children share a key, only the first child will be used.",o):void 0),i&&null!=n&&(r[o]=n)}function r(e){if(null==e)return e;var t={};return i(e,o,t),t}var i=n(121),a=n(26);e.exports=r}).call(t,n(16))},function(e,t,n){(function(t){"use strict";var o=n(91),r=n(100),i=n(89),a=n(57),s=n(33),l=n(99),u=n(98),c=n(85),d=function(e){};s(d.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,n,o){if("production"!==t.env.NODE_ENV&&o[c.ancestorInfoContextKey]&&c("span",null,o[c.ancestorInfoContextKey]),this._rootNodeID=e,n.useCreateElement){var i=o[a.ownerDocumentContextKey],s=i.createElement("span");return r.setAttributeForID(s,e),a.getID(s),u(s,this._stringText),s}var d=l(this._stringText);return n.renderToStaticMarkup?d:"<span "+r.createMarkupForID(e)+">"+d+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;if(n!==this._stringText){this._stringText=n;var r=a.getNode(this._rootNodeID);o.updateTextContent(r,n)}}},unmountComponent:function(){i.unmountIDFromEnvironment(this._rootNodeID)}}),e.exports=d}).call(t,n(16))},function(e,t,n){"use strict";function o(e){var t=p.getID(e),n=d.getReactRootIDFromNodeID(t),o=p.findReactContainerForID(n),r=p.getFirstReactDOM(o);return r}function r(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){a(e)}function a(e){for(var t=p.getFirstReactDOM(v(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=o(n);for(var r=0;r<e.ancestors.length;r++){t=e.ancestors[r];var i=p.getID(t)||"";y._handleTopLevel(e.topLevelType,t,i,e.nativeEvent,v(e.nativeEvent))}}function s(e){var t=m(window);e(t)}var l=n(129),u=n(30),c=n(32),d=n(66),p=n(57),f=n(40),h=n(33),v=n(47),m=n(130);h(r.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),c.addPoolingTo(r,c.twoArgumentPooler);var y={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:u.canUseDOM?window:null,setHandleTopLevel:function(e){y._handleTopLevel=e},setEnabled:function(e){y._enabled=!!e},isEnabled:function(){return y._enabled},trapBubbledEvent:function(e,t,n){var o=n;return o?l.listen(o,t,y.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var o=n;return o?l.capture(o,t,y.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=s.bind(null,e);l.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(y._enabled){var n=r.getPooled(e,t);try{f.batchedUpdates(i,n)}finally{r.release(n)}}}};e.exports=y},function(e,t,n){(function(t){"use strict";var o=n(27),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,n,r){return e.addEventListener?(e.addEventListener(n,r,!0),{remove:function(){e.removeEventListener(n,r,!0)}}):("production"!==t.env.NODE_ENV&&console.error("Attempted to listen to events during the capture phase on a browser that does not support the capture phase. Your application will not receive some events."),{remove:o})},registerDefault:function(){}};e.exports=r}).call(t,n(16))},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}}e.exports=n},function(e,t,n){"use strict";var o=n(58),r=n(22),i=n(78),a=n(132),s=n(82),l=n(59),u=n(83),c=n(42),d=n(67),p=n(40),f={Component:i.injection,Class:a.injection,DOMProperty:o.injection,EmptyComponent:s.injection,EventPluginHub:r.injection,EventEmitter:l.injection,NativeComponent:u.injection,Perf:c.injection,RootIndex:d.injection,Updates:p.injection};e.exports=f},function(e,t,n){(function(t){"use strict";function o(){D||(D=!0,"production"!==t.env.NODE_ENV?N(!1,"setProps(...) and replaceProps(...) are deprecated. Instead, call render again at the top level."):void 0)}function r(e,n,o){for(var r in n)n.hasOwnProperty(r)&&("production"!==t.env.NODE_ENV?N("function"==typeof n[r],"%s: %s type `%s` is invalid; it must be a function, usually from React.PropTypes.",e.displayName||"ReactClass",m[o],r):void 0)}function i(e,n){var o=O.hasOwnProperty(n)?O[n]:null;P.hasOwnProperty(n)&&(o!==S.OVERRIDE_BASE?"production"!==t.env.NODE_ENV?b(!1,"ReactClassInterface: You are attempting to override `%s` from your class specification. Ensure that your method names do not overlap with React methods.",n):b(!1):void 0),e.hasOwnProperty(n)&&(o!==S.DEFINE_MANY&&o!==S.DEFINE_MANY_MERGED?"production"!==t.env.NODE_ENV?b(!1,"ReactClassInterface: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",n):b(!1):void 0)}function a(e,n){if(n){"function"==typeof n?"production"!==t.env.NODE_ENV?b(!1,"ReactClass: You're attempting to use a component class as a mixin. Instead, just use a regular object."):b(!1):void 0,h.isValidElement(n)?"production"!==t.env.NODE_ENV?b(!1,"ReactClass: You're attempting to use a component as a mixin. Instead, just use a regular object."):b(!1):void 0;var o=e.prototype;n.hasOwnProperty(w)&&T.mixins(e,n.mixins);for(var r in n)if(n.hasOwnProperty(r)&&r!==w){var a=n[r];if(i(o,r),T.hasOwnProperty(r))T[r](e,a);else{var s=O.hasOwnProperty(r),l=o.hasOwnProperty(r),d="function"==typeof a,p=d&&!s&&!l&&n.autobind!==!1;if(p)o.__reactAutoBindMap||(o.__reactAutoBindMap={}),o.__reactAutoBindMap[r]=a,o[r]=a;else if(l){var f=O[r];!s||f!==S.DEFINE_MANY_MERGED&&f!==S.DEFINE_MANY?"production"!==t.env.NODE_ENV?b(!1,"ReactClass: Unexpected spec policy %s for key %s when mixing in component specs.",f,r):b(!1):void 0,f===S.DEFINE_MANY_MERGED?o[r]=u(o[r],a):f===S.DEFINE_MANY&&(o[r]=c(o[r],a))}else o[r]=a,"production"!==t.env.NODE_ENV&&"function"==typeof a&&n.displayName&&(o[r].displayName=n.displayName+"_"+r)}}}}function s(e,n){if(n)for(var o in n){var r=n[o];if(n.hasOwnProperty(o)){var i=o in T;i?"production"!==t.env.NODE_ENV?b(!1,'ReactClass: You are attempting to define a reserved property, `%s`, that shouldn\'t be on the "statics" key. Define it as an instance property instead; it will still be accessible on the constructor.',o):b(!1):void 0;
var a=o in e;a?"production"!==t.env.NODE_ENV?b(!1,"ReactClass: You are attempting to define `%s` on your component more than once. This conflict may be due to a mixin.",o):b(!1):void 0,e[o]=r}}}function l(e,n){e&&n&&"object"==typeof e&&"object"==typeof n?void 0:"production"!==t.env.NODE_ENV?b(!1,"mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects."):b(!1);for(var o in n)n.hasOwnProperty(o)&&(void 0!==e[o]?"production"!==t.env.NODE_ENV?b(!1,"mergeIntoWithNoDuplicateKeys(): Tried to merge two objects with the same key: `%s`. This conflict may be due to a mixin; in particular, this may be caused by two getInitialState() or getDefaultProps() methods returning objects with clashing keys.",o):b(!1):void 0,e[o]=n[o]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),o=t.apply(this,arguments);if(null==n)return o;if(null==o)return n;var r={};return l(r,n),l(r,o),r}}function c(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function d(e,n){var o=n.bind(e);if("production"!==t.env.NODE_ENV){o.__reactBoundContext=e,o.__reactBoundMethod=n,o.__reactBoundArguments=null;var r=e.constructor.displayName,i=o.bind;o.bind=function(a){for(var s=arguments.length,l=Array(s>1?s-1:0),u=1;s>u;u++)l[u-1]=arguments[u];if(a!==e&&null!==a)"production"!==t.env.NODE_ENV?N(!1,"bind(): React component methods may only be bound to the component instance. See %s",r):void 0;else if(!l.length)return"production"!==t.env.NODE_ENV?N(!1,"bind(): You are binding a component method to the component. React does this for you automatically in a high-performance way, so you can safely remove this call. See %s",r):void 0,o;var c=i.apply(o,arguments);return c.__reactBoundContext=e,c.__reactBoundMethod=n,c.__reactBoundArguments=l,c}}return o}function p(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=d(e,n)}}var f=n(133),h=n(63),v=n(79),m=n(80),y=n(134),g=n(33),_=n(72),b=n(20),E=n(19),C=n(38),N=n(26),w=C({mixins:null}),S=E({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],D=!1,O={mixins:S.DEFINE_MANY,statics:S.DEFINE_MANY,propTypes:S.DEFINE_MANY,contextTypes:S.DEFINE_MANY,childContextTypes:S.DEFINE_MANY,getDefaultProps:S.DEFINE_MANY_MERGED,getInitialState:S.DEFINE_MANY_MERGED,getChildContext:S.DEFINE_MANY_MERGED,render:S.DEFINE_ONCE,componentWillMount:S.DEFINE_MANY,componentDidMount:S.DEFINE_MANY,componentWillReceiveProps:S.DEFINE_MANY,shouldComponentUpdate:S.DEFINE_ONCE,componentWillUpdate:S.DEFINE_MANY,componentDidUpdate:S.DEFINE_MANY,componentWillUnmount:S.DEFINE_MANY,updateComponent:S.OVERRIDE_BASE},T={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)a(e,t[n])},childContextTypes:function(e,n){"production"!==t.env.NODE_ENV&&r(e,n,v.childContext),e.childContextTypes=g({},e.childContextTypes,n)},contextTypes:function(e,n){"production"!==t.env.NODE_ENV&&r(e,n,v.context),e.contextTypes=g({},e.contextTypes,n)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,n){"production"!==t.env.NODE_ENV&&r(e,n,v.prop),e.propTypes=g({},e.propTypes,n)},statics:function(e,t){s(e,t)},autobind:function(){}},P={replaceState:function(e,t){this.updater.enqueueReplaceState(this,e),t&&this.updater.enqueueCallback(this,t)},isMounted:function(){return this.updater.isMounted(this)},setProps:function(e,n){"production"!==t.env.NODE_ENV&&o(),this.updater.enqueueSetProps(this,e),n&&this.updater.enqueueCallback(this,n)},replaceProps:function(e,n){"production"!==t.env.NODE_ENV&&o(),this.updater.enqueueReplaceProps(this,e),n&&this.updater.enqueueCallback(this,n)}},R=function(){};g(R.prototype,f.prototype,P);var M={createClass:function(e){var n=function(e,o,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?N(this instanceof n,"Something is calling a React component directly. Use a factory or JSX instead. See: https://fb.me/react-legacyfactory"):void 0),this.__reactAutoBindMap&&p(this),this.props=e,this.context=o,this.refs=_,this.updater=r||y,this.state=null;var i=this.getInitialState?this.getInitialState():null;"production"!==t.env.NODE_ENV&&"undefined"==typeof i&&this.getInitialState._isMockFunction&&(i=null),"object"!=typeof i||Array.isArray(i)?"production"!==t.env.NODE_ENV?b(!1,"%s.getInitialState(): must return an object or null",n.displayName||"ReactCompositeComponent"):b(!1):void 0,this.state=i};n.prototype=new R,n.prototype.constructor=n,x.forEach(a.bind(null,n)),a(n,e),n.getDefaultProps&&(n.defaultProps=n.getDefaultProps()),"production"!==t.env.NODE_ENV&&(n.getDefaultProps&&(n.getDefaultProps.isReactClassApproved={}),n.prototype.getInitialState&&(n.prototype.getInitialState.isReactClassApproved={})),n.prototype.render?void 0:"production"!==t.env.NODE_ENV?b(!1,"createClass(...): Class specification must implement a `render` method."):b(!1),"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?N(!n.prototype.componentShouldUpdate,"%s has a method called componentShouldUpdate(). Did you mean shouldComponentUpdate()? The name is phrased as a question because the function is expected to return a value.",e.displayName||"A component"):void 0,"production"!==t.env.NODE_ENV?N(!n.prototype.componentWillRecieveProps,"%s has a method called componentWillRecieveProps(). Did you mean componentWillReceiveProps()?",e.displayName||"A component"):void 0);for(var o in O)n.prototype[o]||(n.prototype[o]=null);return n},injection:{injectMixin:function(e){x.push(e)}}};e.exports=M}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,t,n){this.props=e,this.context=t,this.refs=a,this.updater=n||r}var r=n(134),i=n(64),a=n(72),s=n(20),l=n(26);if(o.prototype.isReactComponent={},o.prototype.setState=function(e,n){"object"!=typeof e&&"function"!=typeof e&&null!=e?"production"!==t.env.NODE_ENV?s(!1,"setState(...): takes an object of state variables to update or a function which returns an object of state variables."):s(!1):void 0,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(null!=e,"setState(...): You passed an undefined or null state object; instead, use forceUpdate()."):void 0),this.updater.enqueueSetState(this,e),n&&this.updater.enqueueCallback(this,n)},o.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this),e&&this.updater.enqueueCallback(this,e)},"production"!==t.env.NODE_ENV){var u={getDOMNode:["getDOMNode","Use ReactDOM.findDOMNode(component) instead."],isMounted:["isMounted","Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."],replaceProps:["replaceProps","Instead, call render again at the top level."],replaceState:["replaceState","Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."],setProps:["setProps","Instead, call render again at the top level."]},c=function(e,n){i&&Object.defineProperty(o.prototype,e,{get:function(){"production"!==t.env.NODE_ENV?l(!1,"%s(...) is deprecated in plain JavaScript React classes. %s",n[0],n[1]):void 0}})};for(var d in u)u.hasOwnProperty(d)&&c(d,u[d])}e.exports=o}).call(t,n(16))},function(e,t,n){(function(t){"use strict";function o(e,n){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?r(!1,"%s(...): Can only update a mounted or mounting component. This usually means you called %s() on an unmounted component. This is a no-op. Please check the code for the %s component.",n,n,e.constructor&&e.constructor.displayName||""):void 0)}var r=n(26),i={isMounted:function(e){return!1},enqueueCallback:function(e,t){},enqueueForceUpdate:function(e){o(e,"forceUpdate")},enqueueReplaceState:function(e,t){o(e,"replaceState")},enqueueSetState:function(e,t){o(e,"setState")},enqueueSetProps:function(e,t){o(e,"setProps")},enqueueReplaceProps:function(e,t){o(e,"replaceProps")}};e.exports=i}).call(t,n(16))},function(e,t,n){"use strict";function o(e){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=r.getPooled(null),this.useCreateElement=!e&&s.useCreateElement}var r=n(41),i=n(32),a=n(59),s=n(62),l=n(136),u=n(46),c=n(33),d={initialize:l.getSelectionInformation,close:l.restoreSelection},p={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},f={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},h=[d,p,f],v={getTransactionWrappers:function(){return h},getReactMountReady:function(){return this.reactMountReady},destructor:function(){r.release(this.reactMountReady),this.reactMountReady=null}};c(o.prototype,u.Mixin,v),i.addPoolingTo(o),e.exports=o},function(e,t,n){"use strict";function o(e){return i(document.documentElement,e)}var r=n(137),i=n(73),a=n(105),s=n(139),l={hasSelectionCapabilities:function(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&"text"===e.type||"textarea"===t||"true"===e.contentEditable)},getSelectionInformation:function(){var e=s();return{focusedElem:e,selectionRange:l.hasSelectionCapabilities(e)?l.getSelection(e):null}},restoreSelection:function(e){var t=s(),n=e.focusedElem,r=e.selectionRange;t!==n&&o(n)&&(l.hasSelectionCapabilities(n)&&l.setSelection(n,r),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&e.nodeName&&"input"===e.nodeName.toLowerCase()){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&&e.nodeName&&"input"===e.nodeName.toLowerCase()){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",o-n),i.select()}else r.setOffsets(e,t)}};e.exports=l},function(e,t,n){"use strict";function o(e,t,n,o){return e===n&&t===o}function r(e){var t=document.selection,n=t.createRange(),o=n.text.length,r=n.duplicate();r.moveToElementText(e),r.setEndPoint("EndToStart",n);var i=r.text.length,a=i+o;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,r=t.anchorOffset,i=t.focusNode,a=t.focusOffset,s=t.getRangeAt(0);try{s.startContainer.nodeType,s.endContainer.nodeType}catch(l){return null}var u=o(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),c=u?0:s.toString().length,d=s.cloneRange();d.selectNodeContents(e),d.setEnd(s.startContainer,s.startOffset);var p=o(d.startContainer,d.startOffset,d.endContainer,d.endOffset),f=p?0:d.toString().length,h=f+c,v=document.createRange();v.setStart(n,r),v.setEnd(i,a);var m=v.collapsed;return{start:m?h:f,end:m?f:h}}function a(e,t){var n,o,r=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,o=n):t.start>t.end?(n=t.end,o=t.start):(n=t.start,o=t.end),r.moveToElementText(e),r.moveStart("character",n),r.setEndPoint("EndToStart",r),r.moveEnd("character",o-n),r.select()}function s(e,t){if(window.getSelection){var n=window.getSelection(),o=e[c()].length,r=Math.min(t.start,o),i="undefined"==typeof t.end?r:Math.min(t.end,o);if(!n.extend&&r>i){var a=i;i=r,r=a}var s=u(e,r),l=u(e,i);if(s&&l){var d=document.createRange();d.setStart(s.node,s.offset),n.removeAllRanges(),r>i?(n.addRange(d),n.extend(l.node,l.offset)):(d.setEnd(l.node,l.offset),n.addRange(d))}}}var l=n(30),u=n(138),c=n(34),d=l.canUseDOM&&"selection"in document&&!("getSelection"in window),p={getOffsets:d?r:i,setOffsets:d?a:s};e.exports=p},function(e,t){"use strict";function n(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function o(e){for(;e;){if(e.nextSibling)return e.nextSibling;e=e.parentNode}}function r(e,t){for(var r=n(e),i=0,a=0;r;){if(3===r.nodeType){if(a=i+r.textContent.length,t>=i&&a>=t)return{node:r,offset:t-i};i=a}r=n(o(r))}}e.exports=r},function(e,t){"use strict";function n(){if("undefined"==typeof document)return null;try{return document.activeElement||document.body}catch(e){return document.body}}e.exports=n},function(e,t,n){"use strict";function o(e){if("selectionStart"in e&&l.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,t){if(b||null==y||y!==c())return null;var n=o(y);if(!_||!f(_,n)){_=n;var r=u.getPooled(m.select,g,e,t);return r.type="select",r.target=y,a.accumulateTwoPhaseDispatches(r),r}return null}var i=n(18),a=n(21),s=n(30),l=n(136),u=n(36),c=n(139),d=n(49),p=n(38),f=n(6),h=i.topLevelTypes,v=s.canUseDOM&&"documentMode"in document&&document.documentMode<=11,m={select:{phasedRegistrationNames:{bubbled:p({onSelect:null}),captured:p({onSelectCapture:null})},dependencies:[h.topBlur,h.topContextMenu,h.topFocus,h.topKeyDown,h.topMouseDown,h.topMouseUp,h.topSelectionChange]}},y=null,g=null,_=null,b=!1,E=!1,C=p({onSelect:null}),N={eventTypes:m,extractEvents:function(e,t,n,o,i){if(!E)return null;switch(e){case h.topFocus:(d(t)||"true"===t.contentEditable)&&(y=t,g=n,_=null);break;case h.topBlur:y=null,g=null,_=null;break;case h.topMouseDown:b=!0;break;case h.topContextMenu:case h.topMouseUp:return b=!1,r(o,i);case h.topSelectionChange:if(v)break;case h.topKeyDown:case h.topKeyUp:return r(o,i)}return null},didPutListener:function(e,t,n){t===C&&(E=!0)}};e.exports=N},function(e,t){"use strict";var n=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*n)}};e.exports=o},function(e,t,n){(function(t){"use strict";var o=n(18),r=n(129),i=n(21),a=n(57),s=n(143),l=n(36),u=n(144),c=n(145),d=n(53),p=n(148),f=n(149),h=n(54),v=n(150),m=n(27),y=n(146),g=n(20),_=n(38),b=o.topLevelTypes,E={abort:{phasedRegistrationNames:{bubbled:_({onAbort:!0}),captured:_({onAbortCapture:!0})}},blur:{phasedRegistrationNames:{bubbled:_({onBlur:!0}),captured:_({onBlurCapture:!0})}},canPlay:{phasedRegistrationNames:{bubbled:_({onCanPlay:!0}),captured:_({onCanPlayCapture:!0})}},canPlayThrough:{phasedRegistrationNames:{bubbled:_({onCanPlayThrough:!0}),captured:_({onCanPlayThroughCapture:!0})}},click:{phasedRegistrationNames:{bubbled:_({onClick:!0}),captured:_({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:_({onContextMenu:!0}),captured:_({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:_({onCopy:!0}),captured:_({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:_({onCut:!0}),captured:_({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:_({onDoubleClick:!0}),captured:_({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:_({onDrag:!0}),captured:_({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:_({onDragEnd:!0}),captured:_({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:_({onDragEnter:!0}),captured:_({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:_({onDragExit:!0}),captured:_({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:_({onDragLeave:!0}),captured:_({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:_({onDragOver:!0}),captured:_({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:_({onDragStart:!0}),captured:_({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:_({onDrop:!0}),captured:_({onDropCapture:!0})}},durationChange:{phasedRegistrationNames:{bubbled:_({onDurationChange:!0}),captured:_({onDurationChangeCapture:!0})}},emptied:{phasedRegistrationNames:{bubbled:_({onEmptied:!0}),captured:_({onEmptiedCapture:!0})}},encrypted:{phasedRegistrationNames:{bubbled:_({onEncrypted:!0}),captured:_({onEncryptedCapture:!0})}},ended:{phasedRegistrationNames:{bubbled:_({onEnded:!0}),captured:_({onEndedCapture:!0})}},error:{phasedRegistrationNames:{bubbled:_({onError:!0}),captured:_({onErrorCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:_({onFocus:!0}),captured:_({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:_({onInput:!0}),captured:_({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:_({onKeyDown:!0}),captured:_({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:_({onKeyPress:!0}),captured:_({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:_({onKeyUp:!0}),captured:_({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:_({onLoad:!0}),captured:_({onLoadCapture:!0})}},loadedData:{phasedRegistrationNames:{bubbled:_({onLoadedData:!0}),captured:_({onLoadedDataCapture:!0})}},loadedMetadata:{phasedRegistrationNames:{bubbled:_({onLoadedMetadata:!0}),captured:_({onLoadedMetadataCapture:!0})}},loadStart:{phasedRegistrationNames:{bubbled:_({onLoadStart:!0}),captured:_({onLoadStartCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:_({onMouseDown:!0}),captured:_({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:_({onMouseMove:!0}),captured:_({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:_({onMouseOut:!0}),captured:_({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:_({onMouseOver:!0}),captured:_({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:_({onMouseUp:!0}),captured:_({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:_({onPaste:!0}),captured:_({onPasteCapture:!0})}},pause:{phasedRegistrationNames:{bubbled:_({onPause:!0}),captured:_({onPauseCapture:!0})}},play:{phasedRegistrationNames:{bubbled:_({onPlay:!0}),captured:_({onPlayCapture:!0})}},playing:{phasedRegistrationNames:{bubbled:_({onPlaying:!0}),captured:_({onPlayingCapture:!0})}},progress:{phasedRegistrationNames:{bubbled:_({onProgress:!0}),captured:_({onProgressCapture:!0})}},rateChange:{phasedRegistrationNames:{bubbled:_({onRateChange:!0}),captured:_({onRateChangeCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:_({onReset:!0}),captured:_({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:_({onScroll:!0}),captured:_({onScrollCapture:!0})}},seeked:{phasedRegistrationNames:{bubbled:_({onSeeked:!0}),captured:_({onSeekedCapture:!0})}},seeking:{phasedRegistrationNames:{bubbled:_({onSeeking:!0}),captured:_({onSeekingCapture:!0})}},stalled:{phasedRegistrationNames:{bubbled:_({onStalled:!0}),captured:_({onStalledCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:_({onSubmit:!0}),captured:_({onSubmitCapture:!0})}},suspend:{phasedRegistrationNames:{bubbled:_({onSuspend:!0}),captured:_({onSuspendCapture:!0})}},timeUpdate:{phasedRegistrationNames:{bubbled:_({onTimeUpdate:!0}),captured:_({onTimeUpdateCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:_({onTouchCancel:!0}),captured:_({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:_({onTouchEnd:!0}),captured:_({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:_({onTouchMove:!0}),captured:_({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:_({onTouchStart:!0}),captured:_({onTouchStartCapture:!0})}},volumeChange:{phasedRegistrationNames:{bubbled:_({onVolumeChange:!0}),captured:_({onVolumeChangeCapture:!0})}},waiting:{phasedRegistrationNames:{bubbled:_({onWaiting:!0}),captured:_({onWaitingCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:_({onWheel:!0}),captured:_({onWheelCapture:!0})}}},C={topAbort:E.abort,topBlur:E.blur,topCanPlay:E.canPlay,topCanPlayThrough:E.canPlayThrough,topClick:E.click,topContextMenu:E.contextMenu,topCopy:E.copy,topCut:E.cut,topDoubleClick:E.doubleClick,topDrag:E.drag,topDragEnd:E.dragEnd,topDragEnter:E.dragEnter,topDragExit:E.dragExit,topDragLeave:E.dragLeave,topDragOver:E.dragOver,topDragStart:E.dragStart,topDrop:E.drop,topDurationChange:E.durationChange,topEmptied:E.emptied,topEncrypted:E.encrypted,topEnded:E.ended,topError:E.error,topFocus:E.focus,topInput:E.input,topKeyDown:E.keyDown,topKeyPress:E.keyPress,topKeyUp:E.keyUp,topLoad:E.load,topLoadedData:E.loadedData,topLoadedMetadata:E.loadedMetadata,topLoadStart:E.loadStart,topMouseDown:E.mouseDown,topMouseMove:E.mouseMove,topMouseOut:E.mouseOut,topMouseOver:E.mouseOver,topMouseUp:E.mouseUp,topPaste:E.paste,topPause:E.pause,topPlay:E.play,topPlaying:E.playing,topProgress:E.progress,topRateChange:E.rateChange,topReset:E.reset,topScroll:E.scroll,topSeeked:E.seeked,topSeeking:E.seeking,topStalled:E.stalled,topSubmit:E.submit,topSuspend:E.suspend,topTimeUpdate:E.timeUpdate,topTouchCancel:E.touchCancel,topTouchEnd:E.touchEnd,topTouchMove:E.touchMove,topTouchStart:E.touchStart,topVolumeChange:E.volumeChange,topWaiting:E.waiting,topWheel:E.wheel};for(var N in C)C[N].dependencies=[N];var w=_({onClick:null}),S={},x={eventTypes:E,extractEvents:function(e,n,o,r,a){var m=C[e];if(!m)return null;var _;switch(e){case b.topAbort:case b.topCanPlay:case b.topCanPlayThrough:case b.topDurationChange:case b.topEmptied:case b.topEncrypted:case b.topEnded:case b.topError:case b.topInput:case b.topLoad:case b.topLoadedData:case b.topLoadedMetadata:case b.topLoadStart:case b.topPause:case b.topPlay:case b.topPlaying:case b.topProgress:case b.topRateChange:case b.topReset:case b.topSeeked:case b.topSeeking:case b.topStalled:case b.topSubmit:case b.topSuspend:case b.topTimeUpdate:case b.topVolumeChange:case b.topWaiting:_=l;break;case b.topKeyPress:if(0===y(r))return null;case b.topKeyDown:case b.topKeyUp:_=c;break;case b.topBlur:case b.topFocus:_=u;break;case b.topClick:if(2===r.button)return null;case b.topContextMenu:case b.topDoubleClick:case b.topMouseDown:case b.topMouseMove:case b.topMouseOut:case b.topMouseOver:case b.topMouseUp:_=d;break;case b.topDrag:case b.topDragEnd:case b.topDragEnter:case b.topDragExit:case b.topDragLeave:case b.topDragOver:case b.topDragStart:case b.topDrop:_=p;break;case b.topTouchCancel:case b.topTouchEnd:case b.topTouchMove:case b.topTouchStart:_=f;break;case b.topScroll:_=h;break;case b.topWheel:_=v;break;case b.topCopy:case b.topCut:case b.topPaste:_=s}_?void 0:"production"!==t.env.NODE_ENV?g(!1,"SimpleEventPlugin: Unhandled event type, `%s`.",e):g(!1);var E=_.getPooled(m,o,r,a);return i.accumulateTwoPhaseDispatches(E),E},didPutListener:function(e,t,n){if(t===w){var o=a.getNode(e);S[e]||(S[e]=r.listen(o,"click",m))}},willDeleteListener:function(e,t){t===w&&(S[e].remove(),delete S[e])}};e.exports=x}).call(t,n(16))},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(36),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(54),i={relatedTarget:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(54),i=n(146),a=n(147),s=n(56),l={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:s,charCode:function(e){return"keypress"===e.type?i(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?i(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}};r.augmentClass(o,l),e.exports=o},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}e.exports=n},function(e,t,n){"use strict";function o(e){if(e.key){var t=i[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?a[e.keyCode]||"Unidentified":""}var r=n(146),i={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},a={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"};e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(53),i={dataTransfer:null};r.augmentClass(o,i),e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(54),i=n(56),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};r.augmentClass(o,a),e.exports=o},function(e,t,n){"use strict";function o(e,t,n,o){r.call(this,e,t,n,o)}var r=n(53),i={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(o,i),e.exports=o},function(e,t,n){"use strict";var o=n(58),r=o.injection.MUST_USE_ATTRIBUTE,i={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},a={Properties:{clipPath:r,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,xlinkActuate:r,xlinkArcrole:r,xlinkHref:r,xlinkRole:r,xlinkShow:r,xlinkTitle:r,xlinkType:r,xmlBase:r,xmlLang:r,xmlSpace:r,y1:r,y2:r,y:r},DOMAttributeNamespaces:{xlinkActuate:i.xlink,xlinkArcrole:i.xlink,xlinkHref:i.xlink,xlinkRole:i.xlink,xlinkShow:i.xlink,xlinkTitle:i.xlink,xlinkType:i.xlink,xmlBase:i.xml,xmlLang:i.xml,xmlSpace:i.xml},DOMAttributeNames:{clipPath:"clip-path",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",xlinkActuate:"xlink:actuate",xlinkArcrole:"xlink:arcrole",xlinkHref:"xlink:href",xlinkRole:"xlink:role",xlinkShow:"xlink:show",xlinkTitle:"xlink:title",xlinkType:"xlink:type",xmlBase:"xml:base",xmlLang:"xml:lang",xmlSpace:"xml:space"}};e.exports=a},function(e,t,n){"use strict";function o(e){return Math.floor(100*e)/100}function r(e,t,n){e[t]=(e[t]||0)+n}var i=n(58),a=n(153),s=n(57),l=n(42),u=n(154),c={_allMeasurements:[],_mountStack:[0],_injected:!1,start:function(){c._injected||l.injection.injectMeasure(c.measure),c._allMeasurements.length=0,l.enableMeasure=!0},stop:function(){l.enableMeasure=!1},getLastMeasurements:function(){return c._allMeasurements},printExclusive:function(e){e=e||c._allMeasurements;var t=a.getExclusiveSummary(e);console.table(t.map(function(e){return{"Component class name":e.componentName,"Total inclusive time (ms)":o(e.inclusive),"Exclusive mount time (ms)":o(e.exclusive),"Exclusive render time (ms)":o(e.render),"Mount time per instance (ms)":o(e.exclusive/e.count),"Render time per instance (ms)":o(e.render/e.count),Instances:e.count}}))},printInclusive:function(e){e=e||c._allMeasurements;var t=a.getInclusiveSummary(e);console.table(t.map(function(e){return{"Owner > component":e.componentName,"Inclusive time (ms)":o(e.time),Instances:e.count}})),console.log("Total time:",a.getTotalTime(e).toFixed(2)+" ms")},getMeasurementsSummaryMap:function(e){var t=a.getInclusiveSummary(e,!0);return t.map(function(e){return{"Owner > component":e.componentName,"Wasted time (ms)":e.time,Instances:e.count}})},printWasted:function(e){e=e||c._allMeasurements,console.table(c.getMeasurementsSummaryMap(e)),console.log("Total time:",a.getTotalTime(e).toFixed(2)+" ms")},printDOM:function(e){e=e||c._allMeasurements;var t=a.getDOMSummary(e);console.table(t.map(function(e){var t={};return t[i.ID_ATTRIBUTE_NAME]=e.id,t.type=e.type,t.args=JSON.stringify(e.args),t})),console.log("Total time:",a.getTotalTime(e).toFixed(2)+" ms")},_recordWrite:function(e,t,n,o){var r=c._allMeasurements[c._allMeasurements.length-1].writes;r[e]=r[e]||[],r[e].push({type:t,time:n,args:o})},measure:function(e,t,n){return function(){for(var o=arguments.length,i=Array(o),a=0;o>a;a++)i[a]=arguments[a];var l,d,p;if("_renderNewRootComponent"===t||"flushBatchedUpdates"===t)return c._allMeasurements.push({exclusive:{},inclusive:{},render:{},counts:{},writes:{},displayNames:{},totalTime:0,created:{}}),p=u(),d=n.apply(this,i),c._allMeasurements[c._allMeasurements.length-1].totalTime=u()-p,d;if("_mountImageIntoNode"===t||"ReactBrowserEventEmitter"===e||"ReactDOMIDOperations"===e||"CSSPropertyOperations"===e||"DOMChildrenOperations"===e||"DOMPropertyOperations"===e){if(p=u(),d=n.apply(this,i),l=u()-p,"_mountImageIntoNode"===t){var f=s.getID(i[1]);c._recordWrite(f,t,l,i[0])}else if("dangerouslyProcessChildrenUpdates"===t)i[0].forEach(function(e){var t={};null!==e.fromIndex&&(t.fromIndex=e.fromIndex),null!==e.toIndex&&(t.toIndex=e.toIndex),null!==e.textContent&&(t.textContent=e.textContent),null!==e.markupIndex&&(t.markup=i[1][e.markupIndex]),c._recordWrite(e.parentID,e.type,l,t)});else{var h=i[0];"object"==typeof h&&(h=s.getID(i[0])),c._recordWrite(h,t,l,Array.prototype.slice.call(i,1))}return d}if("ReactCompositeComponent"!==e||"mountComponent"!==t&&"updateComponent"!==t&&"_renderValidatedComponent"!==t)return n.apply(this,i);if(this._currentElement.type===s.TopLevelWrapper)return n.apply(this,i);var v="mountComponent"===t?i[0]:this._rootNodeID,m="_renderValidatedComponent"===t,y="mountComponent"===t,g=c._mountStack,_=c._allMeasurements[c._allMeasurements.length-1];if(m?r(_.counts,v,1):y&&(_.created[v]=!0,g.push(0)),p=u(),d=n.apply(this,i),l=u()-p,m)r(_.render,v,l);else if(y){var b=g.pop();g[g.length-1]+=l,r(_.exclusive,v,l-b),r(_.inclusive,v,l)}else r(_.inclusive,v,l);return _.displayNames[v]={current:this.getName(),owner:this._currentElement._owner?this._currentElement._owner.getName():"<root>"},d}}};e.exports=c},function(e,t,n){"use strict";function o(e){for(var t=0,n=0;n<e.length;n++){var o=e[n];t+=o.totalTime}return t}function r(e){var t=[];return e.forEach(function(e){Object.keys(e.writes).forEach(function(n){e.writes[n].forEach(function(e){t.push({id:n,type:c[e.type]||e.type,args:e.args})})})}),t}function i(e){for(var t,n={},o=0;o<e.length;o++){var r=e[o],i=l({},r.exclusive,r.inclusive);for(var a in i)t=r.displayNames[a].current,n[t]=n[t]||{componentName:t,inclusive:0,exclusive:0,render:0,count:0},r.render[a]&&(n[t].render+=r.render[a]),r.exclusive[a]&&(n[t].exclusive+=r.exclusive[a]),r.inclusive[a]&&(n[t].inclusive+=r.inclusive[a]),r.counts[a]&&(n[t].count+=r.counts[a])}var s=[];for(t in n)n[t].exclusive>=u&&s.push(n[t]);return s.sort(function(e,t){return t.exclusive-e.exclusive}),s}function a(e,t){for(var n,o={},r=0;r<e.length;r++){var i,a=e[r],c=l({},a.exclusive,a.inclusive);t&&(i=s(a));for(var d in c)if(!t||i[d]){var p=a.displayNames[d];n=p.owner+" > "+p.current,o[n]=o[n]||{componentName:n,time:0,count:0},a.inclusive[d]&&(o[n].time+=a.inclusive[d]),a.counts[d]&&(o[n].count+=a.counts[d])}}var f=[];for(n in o)o[n].time>=u&&f.push(o[n]);return f.sort(function(e,t){return t.time-e.time}),
f}function s(e){var t={},n=Object.keys(e.writes),o=l({},e.exclusive,e.inclusive);for(var r in o){for(var i=!1,a=0;a<n.length;a++)if(0===n[a].indexOf(r)){i=!0;break}e.created[r]&&(i=!0),!i&&e.counts[r]>0&&(t[r]=!0)}return t}var l=n(33),u=1.2,c={_mountImageIntoNode:"set innerHTML",INSERT_MARKUP:"set innerHTML",MOVE_EXISTING:"move",REMOVE_NODE:"remove",SET_MARKUP:"set innerHTML",TEXT_CONTENT:"set textContent",setValueForProperty:"update attribute",setValueForAttribute:"update attribute",deleteValueForProperty:"remove attribute",setValueForStyles:"update styles",replaceNodeWithMarkup:"replace",updateTextContent:"set textContent"},d={getExclusiveSummary:i,getInclusiveSummary:a,getDOMSummary:r,getTotalTime:o};e.exports=d},function(e,t,n){"use strict";var o,r=n(155);o=r.now?function(){return r.now()}:function(){return Date.now()},e.exports=o},function(e,t,n){"use strict";var o,r=n(30);r.canUseDOM&&(o=window.performance||window.msPerformance||window.webkitPerformance),e.exports=o||{}},function(e,t,n){(function(t){"use strict";function o(e){a.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?h(!1,"renderToString(): You must pass a valid ReactElement."):h(!1);var n;try{d.injection.injectBatchingStrategy(u);var o=s.createReactRootID();return n=c.getPooled(!1),n.perform(function(){var t=f(e,null),r=t.mountComponent(o,n,p);return l.addChecksumToMarkup(r)},null)}finally{c.release(n),d.injection.injectBatchingStrategy(i)}}function r(e){a.isValidElement(e)?void 0:"production"!==t.env.NODE_ENV?h(!1,"renderToStaticMarkup(): You must pass a valid ReactElement."):h(!1);var n;try{d.injection.injectBatchingStrategy(u);var o=s.createReactRootID();return n=c.getPooled(!0),n.perform(function(){var t=f(e,null);return t.mountComponent(o,n,p)},null)}finally{c.release(n),d.injection.injectBatchingStrategy(i)}}var i=n(102),a=n(63),s=n(66),l=n(69),u=n(157),c=n(158),d=n(40),p=n(72),f=n(76),h=n(20);e.exports={renderToString:o,renderToStaticMarkup:r}}).call(t,n(16))},function(e,t){"use strict";var n={isBatchingUpdates:!1,batchedUpdates:function(e){}};e.exports=n},function(e,t,n){"use strict";function o(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null),this.useCreateElement=!1}var r=n(32),i=n(41),a=n(46),s=n(33),l=n(27),u={initialize:function(){this.reactMountReady.reset()},close:l},c=[u],d={getTransactionWrappers:function(){return c},getReactMountReady:function(){return this.reactMountReady},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};s(o.prototype,a.Mixin,d),r.addPoolingTo(o),e.exports=o},function(e,t){"use strict";e.exports="0.14.7"},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Collection=t["default"]=void 0;var r=n(161),i=o(r);t["default"]=i["default"],t.Collection=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){var n={};for(var o in e)t.indexOf(o)>=0||Object.prototype.hasOwnProperty.call(e,o)&&(n[o]=e[o]);return n}function i(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(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)}function l(e){var t=e.cellRenderer,n=e.cellSizeAndPositionGetter,o=e.indices,r=e.isScrolling;return o.map(function(e){var o=n({index:e}),i=t({index:e,isScrolling:r});return null==i||i===!1?null:u("div",{className:"Collection__cell",style:{height:o.height,left:o.x,top:o.y,width:o.width}},e,i)}).filter(function(e){return!!e})}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}(),c=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},d=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),p=n(3),f=o(p),h=n(162),v=o(h),m=n(169),y=o(m),g=n(172),_=o(g),b=n(4),E=o(b),C=function(e){function t(e,n){i(this,t);var o=a(this,Object.getPrototypeOf(t).call(this,e,n));return o._cellMetadata=[],o._lastRenderedCellIndices=[],o}return s(t,e),d(t,[{key:"render",value:function(){var e=r(this.props,[]);return f["default"].createElement(v["default"],c({cellLayoutManager:this,ref:"CollectionView"},e))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,E["default"])(this,e,t)}},{key:"calculateSizeAndPositionData",value:function(){var e=this.props,t=e.cellCount,n=e.cellSizeAndPositionGetter,o=e.sectionSize,r=(0,y["default"])({cellCount:t,cellSizeAndPositionGetter:n,sectionSize:o});this._cellMetadata=r.cellMetadata,this._sectionManager=r.sectionManager,this._height=r.height,this._width=r.width}},{key:"getLastRenderedIndices",value:function(){return this._lastRenderedCellIndices}},{key:"getScrollPositionForCell",value:function(e){var t=e.cellIndex,n=e.height,o=e.scrollLeft,r=e.scrollTop,i=e.width,a=this.props.cellCount;if(t>=0&&a>t){var s=this._cellMetadata[t];o=(0,_["default"])({cellOffset:s.x,cellSize:s.width,containerSize:i,currentOffset:o,targetIndex:t}),r=(0,_["default"])({cellOffset:s.y,cellSize:s.height,containerSize:n,currentOffset:r,targetIndex:t})}return{scrollLeft:o,scrollTop:r}}},{key:"getTotalSize",value:function(){return{height:this._height,width:this._width}}},{key:"cellRenderers",value:function(e){var t=this,n=e.height,o=e.isScrolling,r=e.width,i=e.x,a=e.y,s=this.props,l=s.cellGroupRenderer,u=s.cellRenderer;return this._lastRenderedCellIndices=this._sectionManager.getCellIndices({height:n,width:r,x:i,y:a}),l({cellRenderer:u,cellSizeAndPositionGetter:function(e){var n=e.index;return t._sectionManager.getCellMetadata({index:n})},indices:this._lastRenderedCellIndices,isScrolling:o})}}]),t}(p.Component);C.propTypes={"aria-label":p.PropTypes.string,cellCount:p.PropTypes.number.isRequired,cellGroupRenderer:p.PropTypes.func.isRequired,cellRenderer:p.PropTypes.func.isRequired,cellSizeAndPositionGetter:p.PropTypes.func.isRequired,sectionSize:p.PropTypes.number},C.defaultProps={"aria-label":"grid",cellGroupRenderer:l},t["default"]=C},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}(),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),c=n(3),d=o(c),p=n(163),f=o(p),h=n(164),v=o(h),m=n(165),y=o(m),g=n(167),_=o(g),b=n(4),E=o(b),C=150,N={OBSERVED:"observed",REQUESTED:"requested"},w=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={calculateSizeAndPositionDataOnNextUpdate:!1,isScrolling:!1,scrollLeft:0,scrollTop:0},o._onSectionRenderedMemoizer=(0,v["default"])(),o._onScrollMemoizer=(0,v["default"])(!1),o._invokeOnSectionRenderedHelper=o._invokeOnSectionRenderedHelper.bind(o),o._onScroll=o._onScroll.bind(o),o._updateScrollPositionForScrollToCell=o._updateScrollPositionForScrollToCell.bind(o),o}return a(t,e),u(t,[{key:"recomputeCellSizesAndPositions",value:function(){this.setState({calculateSizeAndPositionDataOnNextUpdate:!0})}},{key:"componentDidMount",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.scrollLeft,o=e.scrollToCell,r=e.scrollTop;this._scrollbarSize=(0,y["default"])(),o>=0?this._updateScrollPositionForScrollToCell():(n>=0||r>=0)&&this._setScrollPosition({scrollLeft:n,scrollTop:r}),this._invokeOnSectionRenderedHelper();var i=t.getTotalSize(),a=i.height,s=i.width;this._invokeOnScrollMemoizer({scrollLeft:n||0,scrollTop:r||0,totalHeight:a,totalWidth:s})}},{key:"componentDidUpdate",value:function(e,t){var n=this.props,o=n.height,r=n.scrollToCell,i=n.width,a=this.state,s=a.scrollLeft,l=a.scrollPositionChangeReason,u=a.scrollTop;l===N.REQUESTED&&(s>=0&&s!==t.scrollLeft&&s!==this.refs.scrollingContainer.scrollLeft&&(this.refs.scrollingContainer.scrollLeft=s),u>=0&&u!==t.scrollTop&&u!==this.refs.scrollingContainer.scrollTop&&(this.refs.scrollingContainer.scrollTop=u)),o===e.height&&r===e.scrollToCell&&i===e.width||this._updateScrollPositionForScrollToCell(),this._invokeOnSectionRenderedHelper()}},{key:"componentWillMount",value:function(){var e=this.props.cellLayoutManager;e.calculateSizeAndPositionData()}},{key:"componentWillUnmount",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._setNextStateAnimationFrameId&&_["default"].cancel(this._setNextStateAnimationFrameId)}},{key:"componentWillUpdate",value:function(e,t){0!==e.cellCount||0===t.scrollLeft&&0===t.scrollTop?e.scrollLeft===this.props.scrollLeft&&e.scrollTop===this.props.scrollTop||this._setScrollPosition({scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}):this._setScrollPosition({scrollLeft:0,scrollTop:0}),(e.cellCount!==this.props.cellCount||e.cellLayoutManager!==this.props.cellLayoutManager||t.calculateSizeAndPositionDataOnNextUpdate)&&e.cellLayoutManager.calculateSizeAndPositionData(),t.calculateSizeAndPositionDataOnNextUpdate&&this.setState({calculateSizeAndPositionDataOnNextUpdate:!1})}},{key:"render",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.className,o=e.height,r=e.noContentRenderer,i=e.style,a=e.width,u=this.state,c=u.isScrolling,p=u.scrollLeft,h=u.scrollTop,v=o>0&&a>0?t.cellRenderers({height:o,isScrolling:c,width:a,x:p,y:h}):[],m=t.getTotalSize(),y=m.height,g=m.width,_=l({},i,{height:o,width:a});return o>=y&&(_.overflowY="hidden"),a>=g&&(_.overflowX="hidden"),d["default"].createElement("div",{ref:"scrollingContainer","aria-label":this.props["aria-label"],className:(0,f["default"])("Collection",n),onScroll:this._onScroll,role:"grid",style:_,tabIndex:0},v.length>0&&s("div",{className:"Collection__innerScrollContainer",style:{height:y,maxHeight:y,maxWidth:g,pointerEvents:c?"none":"auto",width:g}},void 0,v),0===v.length&&r())}},{key:"shouldComponentUpdate",value:function(e,t){return(0,E["default"])(this,e,t)}},{key:"_enablePointerEventsAfterDelay",value:function(){var e=this;this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(function(){e._disablePointerEventsTimeoutId=null,e.setState({isScrolling:!1})},C)}},{key:"_invokeOnSectionRenderedHelper",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.onSectionRendered;this._onSectionRenderedMemoizer({callback:n,indices:{indices:t.getLastRenderedIndices()}})}},{key:"_invokeOnScrollMemoizer",value:function(e){var t=this,n=e.scrollLeft,o=e.scrollTop,r=e.totalHeight,i=e.totalWidth;this._onScrollMemoizer({callback:function(e){var n=e.scrollLeft,o=e.scrollTop,a=t.props,s=a.height,l=a.onScroll,u=a.width;l({clientHeight:s,clientWidth:u,scrollHeight:r,scrollLeft:n,scrollTop:o,scrollWidth:i})},indices:{scrollLeft:n,scrollTop:o}})}},{key:"_setNextState",value:function(e){var t=this;this._setNextStateAnimationFrameId&&_["default"].cancel(this._setNextStateAnimationFrameId),this._setNextStateAnimationFrameId=(0,_["default"])(function(){t._setNextStateAnimationFrameId=null,t.setState(e)})}},{key:"_setScrollPosition",value:function(e){var t=e.scrollLeft,n=e.scrollTop,o={scrollPositionChangeReason:N.REQUESTED};t>=0&&(o.scrollLeft=t),n>=0&&(o.scrollTop=n),(t>=0&&t!==this.state.scrollLeft||n>=0&&n!==this.state.scrollTop)&&this.setState(o)}},{key:"_updateScrollPositionForScrollToCell",value:function(){var e=this.props,t=e.cellLayoutManager,n=e.height,o=e.scrollToCell,r=e.width,i=this.state,a=i.scrollLeft,s=i.scrollTop;if(o>=0){var l=t.getScrollPositionForCell({cellIndex:o,height:n,scrollLeft:a,scrollTop:s,width:r});l.scrollLeft===a&&l.scrollTop===s||this._setScrollPosition(l)}}},{key:"_onScroll",value:function(e){if(e.target===this.refs.scrollingContainer){this._enablePointerEventsAfterDelay();var t=this.props,n=t.cellLayoutManager,o=t.height,r=t.width,i=this._scrollbarSize,a=n.getTotalSize(),s=a.height,l=a.width,u=Math.min(l-r+i,e.target.scrollLeft),c=Math.min(s-o+i,e.target.scrollTop);if(this.state.scrollLeft!==u||this.state.scrollTop!==c){var d=e.cancelable?N.OBSERVED:N.REQUESTED;this.state.isScrolling||this.setState({isScrolling:!0}),this._setNextState({isScrolling:!0,scrollLeft:u,scrollPositionChangeReason:d,scrollTop:c})}this._invokeOnScrollMemoizer({scrollLeft:u,scrollTop:c,totalWidth:l,totalHeight:s})}}}]),t}(c.Component);w.propTypes={"aria-label":c.PropTypes.string,cellCount:c.PropTypes.number.isRequired,cellLayoutManager:c.PropTypes.object.isRequired,className:c.PropTypes.string,height:c.PropTypes.number.isRequired,noContentRenderer:c.PropTypes.func.isRequired,onScroll:c.PropTypes.func.isRequired,onSectionRendered:c.PropTypes.func.isRequired,scrollLeft:c.PropTypes.number,scrollToCell:c.PropTypes.number,scrollTop:c.PropTypes.number,style:c.PropTypes.object,width:c.PropTypes.number.isRequired},w.defaultProps={"aria-label":"grid",noContentRenderer:function(){return null},onScroll:function(){return null},onSectionRendered:function(){return null},style:{}},t["default"]=w},function(e,t,n){var o,r;!function(){"use strict";function n(){for(var e=[],t=0;t<arguments.length;t++){var o=arguments[t];if(o){var r=typeof o;if("string"===r||"number"===r)e.push(o);else if(Array.isArray(o))e.push(n.apply(null,o));else if("object"===r)for(var a in o)i.call(o,a)&&o[a]&&e.push(a)}}return e.join(" ")}var i={}.hasOwnProperty;"undefined"!=typeof e&&e.exports?e.exports=n:(o=[],r=function(){return n}.apply(t,o),!(void 0!==r&&(e.exports=r)))}()},function(e,t){"use strict";function n(){var e=arguments.length<=0||void 0===arguments[0]?!0:arguments[0],t={};return function(n){var o=n.callback,r=n.indices,i=Object.keys(r),a=!e||i.every(function(e){var t=r[e];return Array.isArray(t)?t.length>0:t>=0}),s=i.length!==Object.keys(t).length||i.some(function(e){var n=t[e],o=r[e];return Array.isArray(o)?n.join(",")!==o.join(","):n!==o});t=r,a&&s&&o(r)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";var o,r=n(166);e.exports=function(e){if((!o||e)&&r){var t=document.createElement("div");t.style.position="absolute",t.style.top="-9999px",t.style.width="50px",t.style.height="50px",t.style.overflow="scroll",document.body.appendChild(t),o=t.offsetWidth-t.clientWidth,document.body.removeChild(t)}return o}},function(e,t){"use strict";e.exports=!("undefined"==typeof window||!window.document||!window.document.createElement)},function(e,t,n){(function(t){for(var o=n(168),r="undefined"==typeof window?t:window,i=["moz","webkit"],a="AnimationFrame",s=r["request"+a],l=r["cancel"+a]||r["cancelRequest"+a],u=0;!s&&u<i.length;u++)s=r[i[u]+"Request"+a],l=r[i[u]+"Cancel"+a]||r[i[u]+"CancelRequest"+a];if(!s||!l){var c=0,d=0,p=[],f=1e3/60;s=function(e){if(0===p.length){var t=o(),n=Math.max(0,f-(t-c));c=n+t,setTimeout(function(){var e=p.slice(0);p.length=0;for(var t=0;t<e.length;t++)if(!e[t].cancelled)try{e[t].callback(c)}catch(n){setTimeout(function(){throw n},0)}},Math.round(n))}return p.push({handle:++d,callback:e,cancelled:!1}),d},l=function(e){for(var t=0;t<p.length;t++)p[t].handle===e&&(p[t].cancelled=!0)}}e.exports=function(e){return s.call(r,e)},e.exports.cancel=function(){l.apply(r,arguments)},e.exports.polyfill=function(){r.requestAnimationFrame=s,r.cancelAnimationFrame=l}}).call(t,function(){return this}())},function(e,t,n){(function(t){(function(){var n,o,r;"undefined"!=typeof performance&&null!==performance&&performance.now?e.exports=function(){return performance.now()}:"undefined"!=typeof t&&null!==t&&t.hrtime?(e.exports=function(){return(n()-r)/1e6},o=t.hrtime,n=function(){var e;return e=o(),1e9*e[0]+e[1]},r=n()):Date.now?(e.exports=function(){return Date.now()-r},r=Date.now()):(e.exports=function(){return(new Date).getTime()-r},r=(new Date).getTime())}).call(this)}).call(t,n(16))},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){for(var t=e.cellCount,n=e.cellSizeAndPositionGetter,o=e.sectionSize,r=[],i=new a["default"](o),s=0,l=0,u=0;t>u;u++){var c=n({index:u});if(null==c.height||isNaN(c.height)||null==c.width||isNaN(c.width)||null==c.x||isNaN(c.x)||null==c.y||isNaN(c.y))throw Error("Invalid metadata returned for cell "+u+":\n x:"+c.x+", y:"+c.y+", width:"+c.width+", height:"+c.height);s=Math.max(s,c.y+c.height),l=Math.max(l,c.x+c.width),r[u]=c,i.registerCell({cellMetadatum:c,index:u})}return{cellMetadata:r,height:s,sectionManager:i,width:l}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var i=n(170),a=o(i)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),a=n(171),s=o(a),l=100,u=function(){function e(){var t=arguments.length<=0||void 0===arguments[0]?l:arguments[0];r(this,e),this._sectionSize=t,this._cellMetadata=[],this._sections={}}return i(e,[{key:"getCellIndices",value:function(e){var t=e.height,n=e.width,o=e.x,r=e.y,i={};return this.getSections({height:t,width:n,x:o,y:r}).forEach(function(e){return e.getCellIndices().forEach(function(e){return i[e]=e})}),Object.keys(i).map(function(e){return i[e]})}},{key:"getCellMetadata",value:function(e){var t=e.index;return this._cellMetadata[t]}},{key:"getSections",value:function(e){for(var t=e.height,n=e.width,o=e.x,r=e.y,i=Math.floor(o/this._sectionSize),a=Math.floor((o+n-1)/this._sectionSize),l=Math.floor(r/this._sectionSize),u=Math.floor((r+t-1)/this._sectionSize),c=[],d=i;a>=d;d++)for(var p=l;u>=p;p++){var f=d+"."+p;this._sections[f]||(this._sections[f]=new s["default"]({height:this._sectionSize,width:this._sectionSize,x:d*this._sectionSize,y:p*this._sectionSize})),c.push(this._sections[f])}return c}},{key:"getTotalSectionCount",value:function(){return Object.keys(this._sections).length}},{key:"toString",value:function(){var e=this;return Object.keys(this._sections).map(function(t){return e._sections[t].toString()})}},{key:"registerCell",value:function(e){var t=e.cellMetadatum,n=e.index;this._cellMetadata[n]=t,this.getSections(t).forEach(function(e){return e.addCellIndex({index:n})})}}]),e}();t["default"]=u},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),r=function(){function e(t){var o=t.height,r=t.width,i=t.x,a=t.y;n(this,e),this.height=o,this.width=r,this.x=i,this.y=a,this._indexMap={},this._indices=[]}return o(e,[{key:"addCellIndex",value:function(e){var t=e.index;this._indexMap[t]||(this._indexMap[t]=!0,this._indices.push(t))}},{key:"getCellIndices",value:function(){return this._indices}},{key:"toString",value:function(){return this.x+","+this.y+" "+this.width+"x"+this.height}}]),e}();t["default"]=r},function(e,t){"use strict";function n(e){var t=e.cellOffset,n=e.cellSize,o=e.containerSize,r=e.currentOffset,i=t,a=i-o+n,s=Math.max(a,Math.min(i,r));return s}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ColumnSizer=t["default"]=void 0;var r=n(174),i=o(r);t["default"]=i["default"],t.ColumnSizer=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(3),u=n(4),c=o(u),d=n(175),p=o(d),f=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._registerChild=o._registerChild.bind(o),o}return a(t,e),s(t,[{key:"componentDidUpdate",value:function(e,t){var n=this.props,o=n.columnMaxWidth,r=n.columnMinWidth,i=n.columnCount,a=n.width;o===e.columnMaxWidth&&r===e.columnMinWidth&&i===e.columnCount&&a===e.width||this._registeredChild&&this._registeredChild.recomputeGridSize()}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.columnMaxWidth,o=e.columnMinWidth,r=e.columnCount,i=e.width,a=o||1,s=n?Math.min(n,i):i,l=i/r;l=Math.max(a,l),l=Math.min(s,l),l=Math.floor(l);var u=Math.min(i,l*r);return t({adjustedWidth:u,getColumnWidth:function(){return l},registerChild:this._registerChild})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,c["default"])(this,e,t)}},{key:"_registerChild",value:function(e){if(null!==e&&!(e instanceof p["default"]))throw Error("Unexpected child type registered; only Grid children are supported.");this._registeredChild=e,this._registeredChild&&this._registeredChild.recomputeGridSize()}}]),t}(l.Component);f.propTypes={children:l.PropTypes.func.isRequired,columnMaxWidth:l.PropTypes.number,columnMinWidth:l.PropTypes.number,columnCount:l.PropTypes.number.isRequired,width:l.PropTypes.number.isRequired},t["default"]=f},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.Grid=t["default"]=void 0;var r=n(176),i=o(r);t["default"]=i["default"],t.Grid=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}(),l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),c=n(3),d=o(c),p=n(163),f=o(p),h=n(177),v=o(h),m=n(178),y=o(m),g=n(164),_=o(g),b=n(179),E=o(b),C=n(165),N=o(C),w=n(172),S=o(w),x=n(167),D=o(x),O=n(4),T=o(O),P=n(180),R=o(P),M=n(181),I=o(M),k=150,A={OBSERVED:"observed",REQUESTED:"requested"},V=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={isScrolling:!1,scrollLeft:0,scrollTop:0},o._onGridRenderedMemoizer=(0,_["default"])(),o._onScrollMemoizer=(0,_["default"])(!1),o._invokeOnGridRenderedHelper=o._invokeOnGridRenderedHelper.bind(o),o._onScroll=o._onScroll.bind(o),o._updateScrollLeftForScrollToColumn=o._updateScrollLeftForScrollToColumn.bind(o),o._updateScrollTopForScrollToRow=o._updateScrollTopForScrollToRow.bind(o),o._columnWidthGetter=o._wrapSizeGetter(e.columnWidth),o._rowHeightGetter=o._wrapSizeGetter(e.rowHeight),o._columnSizeAndPositionManager=new y["default"]({cellCount:e.columnCount,cellSizeGetter:function(e){return o._columnWidthGetter(e)},estimatedCellSize:o._getEstimatedColumnSize(e)}),o._rowSizeAndPositionManager=new y["default"]({cellCount:e.rowCount,cellSizeGetter:function(e){return o._rowHeightGetter(e)},estimatedCellSize:o._getEstimatedRowSize(e)}),o._cellCache={},o}return a(t,e),u(t,[{key:"recomputeGridSize",value:function(){this._columnSizeAndPositionManager.resetCell(0),this._rowSizeAndPositionManager.resetCell(0)}},{key:"componentDidMount",value:function(){var e=this.props,t=e.scrollLeft,n=e.scrollToColumn,o=e.scrollTop,r=e.scrollToRow;this._scrollbarSize=(0,N["default"])(),(t>=0||o>=0)&&this._setScrollPosition({scrollLeft:t,scrollTop:o}),(n>=0||r>=0)&&(this._updateScrollLeftForScrollToColumn(),this._updateScrollTopForScrollToRow()),this._invokeOnGridRenderedHelper(),this._invokeOnScrollMemoizer({scrollLeft:t||0,scrollTop:o||0,totalColumnsWidth:this._columnSizeAndPositionManager.getTotalSize(),totalRowsHeight:this._rowSizeAndPositionManager.getTotalSize()})}},{key:"componentDidUpdate",value:function(e,t){var n=this,o=this.props,r=o.height,i=o.scrollToColumn,a=o.scrollToRow,s=o.width,u=this.state,c=u.scrollLeft,d=u.scrollPositionChangeReason,p=u.scrollTop;d===A.REQUESTED&&(c>=0&&c!==t.scrollLeft&&c!==this.refs.scrollingContainer.scrollLeft&&(this.refs.scrollingContainer.scrollLeft=c),p>=0&&p!==t.scrollTop&&p!==this.refs.scrollingContainer.scrollTop&&(this.refs.scrollingContainer.scrollTop=p)),(0,R["default"])({cellSizeAndPositionManager:this._columnSizeAndPositionManager,previousCellsCount:e.columnCount,previousCellSize:e.columnWidth,previousScrollToIndex:e.scrollToColumn,previousSize:e.width,scrollOffset:c,scrollToIndex:i,size:s,updateScrollIndexCallback:function(e){return n._updateScrollLeftForScrollToColumn(l({},n.props,{scrollToColumn:e}))}}),(0,R["default"])({cellSizeAndPositionManager:this._rowSizeAndPositionManager,previousCellsCount:e.rowCount,previousCellSize:e.rowHeight,previousScrollToIndex:e.scrollToRow,previousSize:e.height,scrollOffset:p,scrollToIndex:a,size:r,updateScrollIndexCallback:function(e){return n._updateScrollTopForScrollToRow(l({},n.props,{scrollToRow:e}))}}),this._invokeOnGridRenderedHelper()}},{key:"componentWillUnmount",value:function(){this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._setNextStateAnimationFrameId&&D["default"].cancel(this._setNextStateAnimationFrameId)}},{key:"componentWillUpdate",value:function(e,t){var n=this;0===e.columnCount&&0!==t.scrollLeft||0===e.rowCount&&0!==t.scrollTop?this._setScrollPosition({scrollLeft:0,scrollTop:0}):e.scrollLeft===this.props.scrollLeft&&e.scrollTop===this.props.scrollTop||this._setScrollPosition({scrollLeft:e.scrollLeft,scrollTop:e.scrollTop}),this._columnWidthGetter=this._wrapSizeGetter(e.columnWidth),this._rowHeightGetter=this._wrapSizeGetter(e.rowHeight),this._columnSizeAndPositionManager.configure({cellCount:e.columnCount,estimatedCellSize:this._getEstimatedColumnSize(e)}),this._rowSizeAndPositionManager.configure({cellCount:e.rowCount,estimatedCellSize:this._getEstimatedRowSize(e)}),(0,v["default"])({cellCount:this.props.columnCount,cellSize:this.props.columnWidth,computeMetadataCallback:function(){return n._columnSizeAndPositionManager.resetCell(0)},computeMetadataCallbackProps:e,nextCellsCount:e.columnCount,nextCellSize:e.columnWidth,nextScrollToIndex:e.scrollToColumn,scrollToIndex:this.props.scrollToColumn,updateScrollOffsetForScrollToIndex:function(){return n._updateScrollLeftForScrollToColumn(e,t)}}),(0,v["default"])({cellCount:this.props.rowCount,cellSize:this.props.rowHeight,computeMetadataCallback:function(){return n._rowSizeAndPositionManager.resetCell(0)},computeMetadataCallbackProps:e,nextCellsCount:e.rowCount,nextCellSize:e.rowHeight,nextScrollToIndex:e.scrollToRow,scrollToIndex:this.props.scrollToRow,updateScrollOffsetForScrollToIndex:function(){return n._updateScrollTopForScrollToRow(e,t)}})}},{key:"render",value:function(){var e=this.props,t=e.cellRenderer,n=e.cellRangeRenderer,o=e.className,r=e.columnCount,i=e.height,a=e.noContentRenderer,u=e.overscanColumnCount,c=e.overscanRowCount,p=e.rowCount,h=e.style,v=e.width,m=this.state,y=m.isScrolling,g=m.scrollLeft,_=m.scrollTop,b=[];if(i>0&&v>0){var C=this._columnSizeAndPositionManager.getVisibleCellRange({containerSize:v,offset:g}),N=this._rowSizeAndPositionManager.getVisibleCellRange({containerSize:i,offset:_});this._renderedColumnStartIndex=C.start,this._renderedColumnStopIndex=C.stop,this._renderedRowStartIndex=N.start,this._renderedRowStopIndex=N.stop;var w=(0,E["default"])({cellCount:r,overscanCellsCount:u,startIndex:this._renderedColumnStartIndex,stopIndex:this._renderedColumnStopIndex}),S=(0,E["default"])({cellCount:p,overscanCellsCount:c,startIndex:this._renderedRowStartIndex,stopIndex:this._renderedRowStopIndex});this._columnStartIndex=w.overscanStartIndex,this._columnStopIndex=w.overscanStopIndex,this._rowStartIndex=S.overscanStartIndex,this._rowStopIndex=S.overscanStopIndex,b=n({cellCache:this._cellCache,cellRenderer:t,columnSizeAndPositionManager:this._columnSizeAndPositionManager,
columnStartIndex:this._columnStartIndex,columnStopIndex:this._columnStopIndex,isScrolling:y,rowSizeAndPositionManager:this._rowSizeAndPositionManager,rowStartIndex:this._rowStartIndex,rowStopIndex:this._rowStopIndex})}var x=l({},h,{height:i,width:v}),D=this._columnSizeAndPositionManager.getTotalSize(),O=this._rowSizeAndPositionManager.getTotalSize();return v>=D&&(x.overflowX="hidden"),i>=O&&(x.overflowY="hidden"),d["default"].createElement("div",{ref:"scrollingContainer","aria-label":this.props["aria-label"],className:(0,f["default"])("Grid",o),onScroll:this._onScroll,role:"grid",style:x,tabIndex:0},b.length>0&&s("div",{className:"Grid__innerScrollContainer",style:{width:D,height:O,maxWidth:D,maxHeight:O,pointerEvents:y?"none":"auto"}},void 0,b),0===b.length&&a())}},{key:"shouldComponentUpdate",value:function(e,t){return(0,T["default"])(this,e,t)}},{key:"_enablePointerEventsAfterDelay",value:function(){var e=this;this._disablePointerEventsTimeoutId&&clearTimeout(this._disablePointerEventsTimeoutId),this._disablePointerEventsTimeoutId=setTimeout(function(){e._disablePointerEventsTimeoutId=null,e._cellCache={},e.setState({isScrolling:!1})},k)}},{key:"_getEstimatedColumnSize",value:function(e){return"number"==typeof e.columnWidth?e.columnWidth:e.estimatedColumnSize}},{key:"_getEstimatedRowSize",value:function(e){return"number"==typeof e.rowHeight?e.rowHeight:e.estimatedRowSize}},{key:"_invokeOnGridRenderedHelper",value:function(){var e=this.props.onSectionRendered;this._onGridRenderedMemoizer({callback:e,indices:{columnOverscanStartIndex:this._columnStartIndex,columnOverscanStopIndex:this._columnStopIndex,columnStartIndex:this._renderedColumnStartIndex,columnStopIndex:this._renderedColumnStopIndex,rowOverscanStartIndex:this._rowStartIndex,rowOverscanStopIndex:this._rowStopIndex,rowStartIndex:this._renderedRowStartIndex,rowStopIndex:this._renderedRowStopIndex}})}},{key:"_invokeOnScrollMemoizer",value:function(e){var t=this,n=e.scrollLeft,o=e.scrollTop,r=e.totalColumnsWidth,i=e.totalRowsHeight;this._onScrollMemoizer({callback:function(e){var n=e.scrollLeft,o=e.scrollTop,a=t.props,s=a.height,l=a.onScroll,u=a.width;l({clientHeight:s,clientWidth:u,scrollHeight:i,scrollLeft:n,scrollTop:o,scrollWidth:r})},indices:{scrollLeft:n,scrollTop:o}})}},{key:"_setNextState",value:function(e){var t=this;this._setNextStateAnimationFrameId&&D["default"].cancel(this._setNextStateAnimationFrameId),this._setNextStateAnimationFrameId=(0,D["default"])(function(){t._setNextStateAnimationFrameId=null,t.setState(e)})}},{key:"_setScrollPosition",value:function(e){var t=e.scrollLeft,n=e.scrollTop,o={scrollPositionChangeReason:A.REQUESTED};t>=0&&(o.scrollLeft=t),n>=0&&(o.scrollTop=n),(t>=0&&t!==this.state.scrollLeft||n>=0&&n!==this.state.scrollTop)&&this.setState(o)}},{key:"_wrapSizeGetter",value:function(e){return"function"==typeof e?e:function(){return e}}},{key:"_updateScrollLeftForScrollToColumn",value:function(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],t=arguments.length<=1||void 0===arguments[1]?null:arguments[1],n=e||this.props,o=n.columnCount,r=n.scrollToColumn,i=n.width,a=t||this.state,s=a.scrollLeft;if(r>=0&&o>0){var l=Math.max(0,Math.min(o-1,r)),u=this._columnSizeAndPositionManager.getSizeAndPositionOfCell(l),c=(0,S["default"])({cellOffset:u.offset,cellSize:u.size,containerSize:i,currentOffset:s,targetIndex:r});s!==c&&this._setScrollPosition({scrollLeft:c})}}},{key:"_updateScrollTopForScrollToRow",value:function(){var e=arguments.length<=0||void 0===arguments[0]?null:arguments[0],t=arguments.length<=1||void 0===arguments[1]?null:arguments[1],n=e||this.props,o=n.height,r=n.rowCount,i=n.scrollToRow,a=t||this.state,s=a.scrollTop;if(i>=0&&r>0){var l=Math.max(0,Math.min(r-1,i)),u=this._rowSizeAndPositionManager.getSizeAndPositionOfCell(l),c=(0,S["default"])({cellOffset:u.offset,cellSize:u.size,containerSize:o,currentOffset:s,targetIndex:i});s!==c&&this._setScrollPosition({scrollTop:c})}}},{key:"_onScroll",value:function(e){if(e.target===this.refs.scrollingContainer){this._enablePointerEventsAfterDelay();var t=this.props,n=t.height,o=t.width,r=this._scrollbarSize,i=this._rowSizeAndPositionManager.getTotalSize(),a=this._columnSizeAndPositionManager.getTotalSize(),s=Math.min(a-o+r,e.target.scrollLeft),l=Math.min(i-n+r,e.target.scrollTop);if(this.state.scrollLeft!==s||this.state.scrollTop!==l){var u=e.cancelable?A.OBSERVED:A.REQUESTED;this.state.isScrolling||this.setState({isScrolling:!0}),this._setNextState({isScrolling:!0,scrollLeft:s,scrollPositionChangeReason:u,scrollTop:l})}this._invokeOnScrollMemoizer({scrollLeft:s,scrollTop:l,totalColumnsWidth:a,totalRowsHeight:i})}}}]),t}(c.Component);V.propTypes={"aria-label":c.PropTypes.string,cellRenderer:c.PropTypes.func.isRequired,cellRangeRenderer:c.PropTypes.func.isRequired,className:c.PropTypes.string,columnCount:c.PropTypes.number.isRequired,columnWidth:c.PropTypes.oneOfType([c.PropTypes.number,c.PropTypes.func]).isRequired,estimatedColumnSize:c.PropTypes.number.isRequired,estimatedRowSize:c.PropTypes.number.isRequired,height:c.PropTypes.number.isRequired,noContentRenderer:c.PropTypes.func.isRequired,onScroll:c.PropTypes.func.isRequired,onSectionRendered:c.PropTypes.func.isRequired,overscanColumnCount:c.PropTypes.number.isRequired,overscanRowCount:c.PropTypes.number.isRequired,rowHeight:c.PropTypes.oneOfType([c.PropTypes.number,c.PropTypes.func]).isRequired,rowCount:c.PropTypes.number.isRequired,scrollLeft:c.PropTypes.number,scrollToColumn:c.PropTypes.number,scrollTop:c.PropTypes.number,scrollToRow:c.PropTypes.number,style:c.PropTypes.object,width:c.PropTypes.number.isRequired},V.defaultProps={"aria-label":"grid",cellRangeRenderer:I["default"],estimatedColumnSize:100,estimatedRowSize:30,noContentRenderer:function(){return null},onScroll:function(){return null},onSectionRendered:function(){return null},overscanColumnCount:0,overscanRowCount:10,style:{}},t["default"]=V},function(e,t){"use strict";function n(e){var t=e.cellCount,n=e.cellSize,o=e.computeMetadataCallback,r=e.computeMetadataCallbackProps,i=e.nextCellsCount,a=e.nextCellSize,s=e.nextScrollToIndex,l=e.scrollToIndex,u=e.updateScrollOffsetForScrollToIndex;t===i&&("number"!=typeof n&&"number"!=typeof a||n===a)||(o(r),l>=0&&l===s&&u())}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var o=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),r=function(){function e(t){var o=t.cellCount,r=t.cellSizeGetter,i=t.estimatedCellSize;n(this,e),this._cellSizeGetter=r,this._cellCount=o,this._estimatedCellSize=i,this._cellSizeAndPositionData={},this._lastMeasuredIndex=-1}return o(e,[{key:"configure",value:function(e){var t=e.cellCount,n=e.estimatedCellSize;this._cellCount=t,this._estimatedCellSize=n}},{key:"findNearestCell",value:function(e){if(Number.isNaN(e))throw Error("Invalid offset "+e+" specified");e=Math.max(0,e);var t=this.getSizeAndPositionOfLastMeasuredCell(),n=Math.max(0,this._lastMeasuredIndex);return t.offset>=e?this._binarySearch({high:n,low:0,offset:e}):this._exponentialSearch({index:n,offset:e})}},{key:"getCellCount",value:function(){return this._cellCount}},{key:"getEstimatedCellSize",value:function(){return this._estimatedCellSize}},{key:"getLastMeasuredIndex",value:function(){return this._lastMeasuredIndex}},{key:"getSizeAndPositionOfCell",value:function(e){if(0>e||e>=this._cellCount)throw Error("Requested index "+e+" is outside of range 0.."+this._cellCount);if(e>this._lastMeasuredIndex){for(var t=this.getSizeAndPositionOfLastMeasuredCell(),n=t.offset+t.size,o=this._lastMeasuredIndex+1;e>=o;o++){var r=this._cellSizeGetter({index:o});if(null==r||isNaN(r))throw Error("Invalid size returned for cell "+o+" of value "+r);this._cellSizeAndPositionData[o]={offset:n,size:r},n+=r}this._lastMeasuredIndex=e}return this._cellSizeAndPositionData[e]}},{key:"getSizeAndPositionOfLastMeasuredCell",value:function(){return this._lastMeasuredIndex>=0?this._cellSizeAndPositionData[this._lastMeasuredIndex]:{offset:0,size:0}}},{key:"getTotalSize",value:function(){var e=this.getSizeAndPositionOfLastMeasuredCell();return e.offset+e.size+(this._cellCount-this._lastMeasuredIndex-1)*this._estimatedCellSize}},{key:"getVisibleCellRange",value:function(e){var t=e.containerSize,n=e.offset,o=this.getTotalSize();if(0===o)return{};var r=n+t,i=this.findNearestCell(n),a=this.getSizeAndPositionOfCell(i);n=a.offset+a.size;for(var s=i;r>n&&s<this._cellCount-1;)s++,n+=this.getSizeAndPositionOfCell(s).size;return{start:i,stop:s}}},{key:"resetCell",value:function(e){this._lastMeasuredIndex=e-1}},{key:"_binarySearch",value:function(e){for(var t=e.high,n=e.low,o=e.offset,r=void 0,i=void 0;t>=n;){if(r=n+Math.floor((t-n)/2),i=this.getSizeAndPositionOfCell(r).offset,i===o)return r;o>i?n=r+1:i>o&&(t=r-1)}return n>0?n-1:void 0}},{key:"_exponentialSearch",value:function(e){for(var t=e.index,n=e.offset,o=1;t<this._cellCount&&this.getSizeAndPositionOfCell(t).offset<n;)t+=o,o*=2;return this._binarySearch({high:Math.min(t,this._cellCount-1),low:Math.floor(t/2),offset:n})}}]),e}();t["default"]=r},function(e,t){"use strict";function n(e){var t=e.cellCount,n=e.overscanCellsCount,o=e.startIndex,r=e.stopIndex;return{overscanStartIndex:Math.max(0,o-n),overscanStopIndex:Math.min(t-1,r+n)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.cellSize,n=e.cellSizeAndPositionManager,o=e.previousCellsCount,r=e.previousCellSize,i=e.previousScrollToIndex,s=e.previousSize,l=e.scrollOffset,u=e.scrollToIndex,c=e.size,d=e.updateScrollIndexCallback,p=n.getCellCount(),f=u>=0&&p>u,h=c!==s||!r||"number"==typeof t&&t!==r;if(f&&(h||u!==i))d(u);else if(!f&&p>0&&(s>c||o>p)){u=p-1;var v=n.getSizeAndPositionOfCell(u),m=(0,a["default"])({cellOffset:v.offset,cellSize:v.size,containerSize:c,currentOffset:l});l>m&&d(p-1)}}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=r;var i=n(172),a=o(i)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){for(var t=e.cellCache,n=e.cellRenderer,o=e.columnSizeAndPositionManager,r=e.columnStartIndex,a=e.columnStopIndex,s=e.isScrolling,l=e.rowSizeAndPositionManager,u=e.rowStartIndex,c=e.rowStopIndex,d=[],p=u;c>=p;p++)for(var f=l.getSizeAndPositionOfCell(p),h=r;a>=h;h++){var v=o.getSizeAndPositionOfCell(h),m=p+"-"+h,y=void 0;if(s?(t[m]||(t[m]=n({columnIndex:h,isScrolling:s,rowIndex:p})),y=t[m]):y=n({columnIndex:h,isScrolling:s,rowIndex:p}),null!=y&&y!==!1){var g=i("div",{className:"Grid__cell",style:{height:f.size,left:v.offset,top:f.offset,width:v.size}},m,y);d.push(g)}}return d}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}();t["default"]=r;var a=n(3),s=(o(a),n(178));o(s)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.SortIndicator=t.SortDirection=t.FlexColumn=t.FlexTable=t["default"]=void 0;var r=n(183),i=o(r),a=n(184),s=o(a),l=n(187),u=o(l),c=n(186),d=o(c);t["default"]=i["default"],t.FlexTable=i["default"],t.FlexColumn=s["default"],t.SortDirection=u["default"],t.SortIndicator=d["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)Object.prototype.hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},l=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}(),u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),c=n(163),d=o(c),p=n(184),f=o(p),h=n(3),v=o(h),m=n(12),y=n(4),g=o(y),_=n(175),b=o(_),E=n(187),C=o(E),N=function(e){function t(e){r(this,t);var n=i(this,Object.getPrototypeOf(t).call(this,e));return n.state={scrollbarWidth:0},n._createRow=n._createRow.bind(n),n}return a(t,e),u(t,[{key:"recomputeRowHeights",value:function(){this.refs.Grid.recomputeGridSize()}},{key:"componentDidMount",value:function(){this._setScrollbarWidth()}},{key:"componentDidUpdate",value:function(){this._setScrollbarWidth()}},{key:"render",value:function(){var e=this,t=this.props,n=t.className,o=t.disableHeader,r=t.headerHeight,i=t.height,a=t.noRowsRenderer,u=t.onRowsRendered,c=t.onScroll,p=t.overscanRowCount,f=t.rowClassName,h=t.rowHeight,m=t.rowCount,y=t.rowStyle,g=t.scrollToIndex,_=t.scrollTop,E=t.style,C=t.width,N=this.state.scrollbarWidth,w=i-r,S=function(t){var n=t.index,o=t.isScrolling;return e._createRow({index:n,isScrolling:o})},x=f instanceof Function?f({index:-1}):f;return l("div",{className:(0,d["default"])("FlexTable",n),style:E},void 0,!o&&l("div",{className:(0,d["default"])("FlexTable__headerRow",x),style:s({},y,{height:r,paddingRight:N,width:C})},void 0,this._getRenderedHeaderRow()),v["default"].createElement(b["default"],{"aria-label":this.props["aria-label"],ref:"Grid",className:"FlexTable__Grid",columnWidth:C,columnCount:1,height:w,noContentRenderer:a,onScroll:function(e){var t=e.clientHeight,n=e.scrollHeight,o=e.scrollTop;return c({clientHeight:t,scrollHeight:n,scrollTop:o})},onSectionRendered:function(e){var t=e.rowOverscanStartIndex,n=e.rowOverscanStopIndex,o=e.rowStartIndex,r=e.rowStopIndex;return u({overscanStartIndex:t,overscanStopIndex:n,startIndex:o,stopIndex:r})},overscanRowCount:p,cellRenderer:function(e){var t=(e.columnIndex,e.isScrolling),n=e.rowIndex;return S({index:n,isScrolling:t})},rowHeight:h,rowCount:m,scrollToRow:g,scrollTop:_,width:C}))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,g["default"])(this,e,t)}},{key:"_createColumn",value:function(e){var t=e.column,n=e.columnIndex,o=e.isScrolling,r=e.rowData,i=e.rowIndex,a=t.props,s=a.cellDataGetter,u=a.cellRenderer,c=a.className,p=a.columnData,f=a.dataKey,h=a.style,v=s({columnData:p,dataKey:f,rowData:r}),m=u({cellData:v,columnData:p,dataKey:f,isScrolling:o,rowData:r,rowIndex:i}),y=this._getFlexStyleForColumn(t,h),g="string"==typeof m?m:null;return l("div",{className:(0,d["default"])("FlexTable__rowColumn",c),style:y},"Row"+i+"-Col"+n,l("div",{className:"FlexTable__truncatedColumnText",title:g},void 0,m))}},{key:"_createHeader",value:function(e,t){var n=this.props,o=n.headerClassName,r=n.headerStyle,i=n.onHeaderClick,a=n.sort,l=n.sortBy,u=n.sortDirection,c=e.props,p=c.dataKey,f=c.disableSort,h=c.headerRenderer,m=c.label,y=c.columnData,g=!f&&a,_=(0,d["default"])("FlexTable__headerColumn",o,e.props.headerClassName,{FlexTable__sortableHeaderColumn:g}),b=this._getFlexStyleForColumn(e,r),E=h({columnData:y,dataKey:p,disableSort:f,label:m,sortBy:l,sortDirection:u}),N={};return(g||i)&&!function(){var t=l!==p||u===C["default"].DESC?C["default"].ASC:C["default"].DESC,n=function(){g&&a({sortBy:p,sortDirection:t}),i&&i({columnData:y,dataKey:p})},o=function(e){"Enter"!==e.key&&" "!==e.key||n()};N["aria-label"]=e.props["aria-label"]||m||p,N.role="rowheader",N.tabIndex=0,N.onClick=n,N.onKeyDown=o}(),v["default"].createElement("div",s({},N,{key:"Header-Col"+t,className:_,style:b}),E)}},{key:"_createRow",value:function(e){var t=this,n=e.index,o=e.isScrolling,r=this.props,i=r.children,a=r.onRowClick,l=r.rowClassName,u=r.rowGetter,c=r.rowStyle,p=this.state.scrollbarWidth,f=l instanceof Function?l({index:n}):l,h=u({index:n}),m=v["default"].Children.toArray(i).map(function(e,r){return t._createColumn({column:e,columnIndex:r,isScrolling:o,rowData:h,rowIndex:n})}),y={};return a&&(y["aria-label"]="row",y.role="row",y.tabIndex=0,y.onClick=function(){return a({index:n})}),v["default"].createElement("div",s({},y,{key:n,className:(0,d["default"])("FlexTable__row",f),style:s({},c,{height:this._getRowHeight(n),paddingRight:p})}),m)}},{key:"_getFlexStyleForColumn",value:function(e){var t=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=e.props.flexGrow+" "+e.props.flexShrink+" "+e.props.width+"px",o=s({},t,{flex:n,msFlex:n,WebkitFlex:n});return e.props.maxWidth&&(o.maxWidth=e.props.maxWidth),e.props.minWidth&&(o.minWidth=e.props.minWidth),o}},{key:"_getRenderedHeaderRow",value:function(){var e=this,t=this.props,n=t.children,o=t.disableHeader,r=o?[]:v["default"].Children.toArray(n);return r.map(function(t,n){return e._createHeader(t,n)})}},{key:"_getRowHeight",value:function(e){var t=this.props.rowHeight;return t instanceof Function?t({index:e}):t}},{key:"_setScrollbarWidth",value:function(){var e=(0,m.findDOMNode)(this.refs.Grid),t=e.clientWidth||0,n=e.offsetWidth||0,o=n-t;this.setState({scrollbarWidth:o})}}]),t}(h.Component);N.propTypes={"aria-label":h.PropTypes.string,children:function w(e,t,n){for(var w=v["default"].Children.toArray(e.children),o=0;o<w.length;o++)if(w[o].type!==f["default"])return new Error("FlexTable only accepts children of type FlexColumn")},className:h.PropTypes.string,disableHeader:h.PropTypes.bool,headerClassName:h.PropTypes.string,headerHeight:h.PropTypes.number.isRequired,height:h.PropTypes.number.isRequired,noRowsRenderer:h.PropTypes.func,onHeaderClick:h.PropTypes.func,headerStyle:h.PropTypes.object,onRowClick:h.PropTypes.func,onRowsRendered:h.PropTypes.func,onScroll:h.PropTypes.func.isRequired,overscanRowCount:h.PropTypes.number.isRequired,rowClassName:h.PropTypes.oneOfType([h.PropTypes.string,h.PropTypes.func]),rowGetter:h.PropTypes.func.isRequired,rowHeight:h.PropTypes.oneOfType([h.PropTypes.number,h.PropTypes.func]).isRequired,rowCount:h.PropTypes.number.isRequired,rowStyle:h.PropTypes.object,scrollToIndex:h.PropTypes.number,scrollTop:h.PropTypes.number,sort:h.PropTypes.func,sortBy:h.PropTypes.string,sortDirection:h.PropTypes.oneOf([C["default"].ASC,C["default"].DESC]),style:h.PropTypes.object,width:h.PropTypes.number.isRequired},N.defaultProps={disableHeader:!1,headerHeight:0,headerStyle:{},noRowsRenderer:function(){return null},onRowsRendered:function(){return null},onScroll:function(){return null},overscanRowCount:10,rowStyle:{},style:{}},t["default"]=N},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=n(3),l=n(185),u=o(l),c=n(188),d=o(c),p=n(189),f=o(p),h=function(e){function t(){return r(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),t}(s.Component);h.defaultProps={cellDataGetter:f["default"],cellRenderer:d["default"],cellStyle:{},flexGrow:0,flexShrink:1,headerRenderer:u["default"]},h.propTypes={"aria-label":s.PropTypes.string,cellDataGetter:s.PropTypes.func,cellRenderer:s.PropTypes.func,className:s.PropTypes.string,columnData:s.PropTypes.object,dataKey:s.PropTypes.any.isRequired,disableSort:s.PropTypes.bool,flexGrow:s.PropTypes.number,flexShrink:s.PropTypes.number,headerClassName:s.PropTypes.string,headerRenderer:s.PropTypes.func.isRequired,label:s.PropTypes.string,maxWidth:s.PropTypes.number,minWidth:s.PropTypes.number,style:s.PropTypes.object,width:s.PropTypes.number.isRequired},t["default"]=h},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=(e.columnData,e.dataKey),n=(e.disableSort,e.label),o=e.sortBy,r=e.sortDirection,a=o===t,s=[i("div",{className:"FlexTable__headerTruncatedText",title:n},"label",n)];return a&&s.push(i(l["default"],{sortDirection:r},"SortIndicator")),s}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}();t["default"]=r;var a=n(3),s=(o(a),n(186)),l=o(s)},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(e){var t=e.sortDirection,n=(0,l["default"])("FlexTable__sortableHeaderIcon",{"FlexTable__sortableHeaderIcon--ASC":t===c["default"].ASC,"FlexTable__sortableHeaderIcon--DESC":t===c["default"].DESC});return i("svg",{className:n,width:18,height:18,viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg"},void 0,t===c["default"].ASC?i("path",{d:"M7 14l5-5 5 5z"}):i("path",{d:"M7 10l5 5 5-5z"}),i("path",{d:"M0 0h24v24H0z",fill:"none"}))}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){var e="function"==typeof Symbol&&Symbol["for"]&&Symbol["for"]("react.element")||60103;return function(t,n,o,r){var i=t&&t.defaultProps,a=arguments.length-3;if(n||0===a||(n={}),n&&i)for(var s in i)void 0===n[s]&&(n[s]=i[s]);else n||(n=i||{});if(1===a)n.children=r;else if(a>1){for(var l=Array(a),u=0;a>u;u++)l[u]=arguments[u+3];n.children=l}return{$$typeof:e,type:t,key:void 0===o?null:""+o,ref:null,props:n,_owner:null}}}();t["default"]=r;var a=n(3),s=(o(a),n(163)),l=o(s),u=n(187),c=o(u);r.propTypes={sortDirection:a.PropTypes.oneOf([c["default"].ASC,c["default"].DESC])}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={ASC:"ASC",DESC:"DESC"};t["default"]=n},function(e,t){"use strict";function n(e){var t=e.cellData;return e.cellDataKey,e.columnData,e.rowData,e.rowIndex,null===t||void 0===t?"":String(t)}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t){"use strict";function n(e){var t=(e.columnData,e.dataKey),n=e.rowData;return n.get instanceof Function?n.get(t):n[t]}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.InfiniteLoader=t["default"]=void 0;var r=n(191),i=o(r);t["default"]=i["default"],t.InfiniteLoader=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}function s(e){var t=e.lastRenderedStartIndex,n=e.lastRenderedStopIndex,o=e.startIndex,r=e.stopIndex;return!(o>n||t>r)}function l(e){for(var t=e.isRowLoaded,n=e.minimumBatchSize,o=e.rowCount,r=e.startIndex,i=e.stopIndex,a=[],s=null,l=null,u=r;i>=u;u++){var c=t({index:u});c?null!==l&&(a.push({startIndex:s,stopIndex:l}),s=l=null):(l=u,null===s&&(s=u))}if(null!==l){for(var d=Math.min(Math.max(l,s+n-1),o-1),u=l+1;d>=u&&!t({index:u});u++)l=u;a.push({startIndex:s,stopIndex:l})}return a}Object.defineProperty(t,"__esModule",{value:!0});var u=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}();t.isRangeVisible=s,t.scanForUnloadedRanges=l;var c=n(3),d=n(4),p=o(d),f=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o._onRowsRendered=o._onRowsRendered.bind(o),o._registerChild=o._registerChild.bind(o),o}return a(t,e),u(t,[{key:"render",value:function(){var e=this.props.children;return e({onRowsRendered:this._onRowsRendered,registerChild:this._registerChild})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,p["default"])(this,e,t)}},{key:"_onRowsRendered",value:function(e){var t=this,n=e.startIndex,o=e.stopIndex,r=this.props,i=r.isRowLoaded,a=r.loadMoreRows,u=r.minimumBatchSize,c=r.rowCount,d=r.threshold;this._lastRenderedStartIndex=n,this._lastRenderedStopIndex=o;var p=l({isRowLoaded:i,minimumBatchSize:u,rowCount:c,startIndex:Math.max(0,n-d),stopIndex:Math.min(c-1,o+d)});p.forEach(function(e){var n=a(e);n&&n.then(function(){s({lastRenderedStartIndex:t._lastRenderedStartIndex,lastRenderedStopIndex:t._lastRenderedStopIndex,startIndex:e.startIndex,stopIndex:e.stopIndex})&&t._registeredChild&&t._registeredChild.forceUpdate()})})}},{key:"_registerChild",value:function(e){this._registeredChild=e}}]),t}(c.Component);f.propTypes={children:c.PropTypes.func.isRequired,isRowLoaded:c.PropTypes.func.isRequired,loadMoreRows:c.PropTypes.func.isRequired,minimumBatchSize:c.PropTypes.number.isRequired,rowCount:c.PropTypes.number.isRequired,threshold:c.PropTypes.number.isRequired},f.defaultProps={minimumBatchSize:10,rowCount:0,threshold:15},t["default"]=f},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollSync=t["default"]=void 0;var r=n(193),i=o(r);t["default"]=i["default"],t.ScrollSync=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(3),u=n(4),c=o(u),d=function(e){function t(e,n){r(this,t);var o=i(this,Object.getPrototypeOf(t).call(this,e,n));return o.state={clientHeight:0,clientWidth:0,scrollHeight:0,scrollLeft:0,scrollTop:0,scrollWidth:0},o._onScroll=o._onScroll.bind(o),o}return a(t,e),s(t,[{key:"render",value:function(){var e=this.props.children,t=this.state,n=t.clientHeight,o=t.clientWidth,r=t.scrollHeight,i=t.scrollLeft,a=t.scrollTop,s=t.scrollWidth;return e({clientHeight:n,clientWidth:o,onScroll:this._onScroll,scrollHeight:r,scrollLeft:i,scrollTop:a,scrollWidth:s})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,c["default"])(this,e,t)}},{key:"_onScroll",value:function(e){var t=e.clientHeight,n=e.clientWidth,o=e.scrollHeight,r=e.scrollLeft,i=e.scrollTop,a=e.scrollWidth;this.setState({clientHeight:t,clientWidth:n,scrollHeight:o,scrollLeft:r,scrollTop:i,scrollWidth:a})}}]),t}(l.Component);d.propTypes={children:l.PropTypes.func.isRequired},t["default"]=d},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0}),t.VirtualScroll=t["default"]=void 0;var r=n(195),i=o(r);t["default"]=i["default"],t.VirtualScroll=i["default"]},function(e,t,n){"use strict";function o(e){return e&&e.__esModule?e:{"default":e}}function r(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 a(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)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),l=n(175),u=o(l),c=n(3),d=o(c),p=n(163),f=o(p),h=n(4),v=o(h),m=function(e){function t(){return r(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),s(t,[{key:"recomputeRowHeights",value:function(){this.refs.Grid.recomputeGridSize()}},{key:"render",value:function(){var e=this.props,t=e.className,n=e.height,o=e.noRowsRenderer,r=e.onRowsRendered,i=e.onScroll,a=e.rowHeight,s=e.rowRenderer,l=e.overscanRowCount,c=e.rowCount,p=e.scrollToIndex,h=e.scrollTop,v=e.style,m=e.width,y=(0,f["default"])("VirtualScroll",t);return d["default"].createElement(u["default"],{ref:"Grid","aria-label":this.props["aria-label"],className:y,columnWidth:m,columnCount:1,height:n,noContentRenderer:o,onScroll:function(e){var t=e.clientHeight,n=e.scrollHeight,o=e.scrollTop;return i({clientHeight:t,scrollHeight:n,scrollTop:o})},onSectionRendered:function(e){var t=e.rowOverscanStartIndex,n=e.rowOverscanStopIndex,o=e.rowStartIndex,i=e.rowStopIndex;return r({overscanStartIndex:t,overscanStopIndex:n,startIndex:o,stopIndex:i})},overscanRowCount:l,cellRenderer:function(e){var t=(e.columnIndex,e.isScrolling),n=e.rowIndex;return s({index:n,isScrolling:t})},rowHeight:a,rowCount:c,scrollToRow:p,scrollTop:h,style:v,width:m})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,v["default"])(this,e,t)}}]),t}(c.Component);m.propTypes={"aria-label":c.PropTypes.string,className:c.PropTypes.string,height:c.PropTypes.number.isRequired,noRowsRenderer:c.PropTypes.func.isRequired,onRowsRendered:c.PropTypes.func.isRequired,overscanRowCount:c.PropTypes.number.isRequired,onScroll:c.PropTypes.func.isRequired,
rowHeight:c.PropTypes.oneOfType([c.PropTypes.number,c.PropTypes.func]).isRequired,rowRenderer:c.PropTypes.func.isRequired,rowCount:c.PropTypes.number.isRequired,scrollToIndex:c.PropTypes.number,scrollTop:c.PropTypes.number,style:c.PropTypes.object,width:c.PropTypes.number.isRequired},m.defaultProps={noRowsRenderer:function(){return null},onRowsRendered:function(){return null},onScroll:function(){return null},overscanRowCount:10,style:{}},t["default"]=m}])});
//# sourceMappingURL=react-virtualized.min.js.map
|
client/extensions/woocommerce/app/settings/taxes/taxes-taxjar.js
|
Automattic/woocommerce-connect-client
|
/**
* External dependencies
*
* @format
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { localize } from 'i18n-calypso';
/**
* Internal dependencies
*/
import ActionHeader from 'woocommerce/components/action-header';
import Card from 'components/card';
import ExternalLink from 'components/external-link';
import { getLink } from 'woocommerce/lib/nav-utils';
import SettingsNavigation from '../navigation';
class SettingsTaxesTaxJar extends Component {
static propTypes = {
className: PropTypes.string,
site: PropTypes.shape( {
options: PropTypes.shape( {
admin_url: PropTypes.string.isRequired,
} ),
} ).isRequired,
};
render = () => {
const { site, translate } = this.props;
const breadcrumbs = [
<a href={ getLink( '/store/settings/:site/', site ) }>{ translate( 'Settings' ) }</a>,
<span>{ translate( 'Taxes' ) }</span>,
];
const adminUrl =
site.options.admin_url +
'admin.php?page=wc-settings&tab=integration§ion=taxjar-integration';
const pluginUrl = getLink( '/plugins/taxjar-simplified-taxes-for-woocommerce/:site', site );
return (
<div>
<ActionHeader breadcrumbs={ breadcrumbs } />
<SettingsNavigation activeSection="taxes" />
<div>
<Card className="taxes__tax-jar-info">
<p>
{ translate(
"Your store's taxes are being managed by the {{b}}TaxJar - Sales Tax Automation " +
'for WooCommerce{{/b}} plugin. This optional plugin provides features such as:',
{
components: {
b: <strong />,
},
}
) }
</p>
<ul>
<li>{ translate( 'Automated reporting & filing' ) }</li>
<li>{ translate( 'Multi-nexus support' ) }</li>
</ul>
<p>
{ translate(
"If you don't need these features we recommend {{a}}removing this plugin{{/a}}. Don't worry, " +
"{{b}}we'll still handle sales tax calculations for you{{/b}}.",
{
components: {
a: <a href={ pluginUrl } />,
b: <strong />,
},
}
) }
</p>
<p>
{ translate( "You can manage this plugin's settings in wp-admin. " ) }
<ExternalLink icon href={ adminUrl } rel="noopener noreferrer">
{ translate( 'Plugin settings' ) }
</ExternalLink>
</p>
</Card>
</div>
</div>
);
};
}
export default localize( SettingsTaxesTaxJar );
|
packages/material-ui-icons/src/FormatColorTextSharp.js
|
allanalexandre/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".36" d="M0 20h24v4H0v-4z" /><path d="M11 3L5.5 17h2.25l1.12-3h6.25l1.12 3h2.25L13 3h-2zm-1.38 9L12 5.67 14.38 12H9.62z" /></React.Fragment>
, 'FormatColorTextSharp');
|
src/app/Header.js
|
nkbt/esnext-quickstart
|
import React from 'react';
import styles from './Header.css';
const Header = () =>
<header className={styles.header}>
<a className={styles.logo} href="/">Logo</a>
</header>;
export default Header;
|
src/components/Install.react.js
|
EaglesoftZJ/iGem_Web
|
/*
* Copyright (C) 2015-2016 Actor LLC. <https://actor.im>
*/
import React, { Component } from 'react';
import { FormattedHTMLMessage } from 'react-intl';
import SharedContainer from '../utils/SharedContainer';
import { appName } from '../constants/ActorAppConstants';
class Install extends Component {
constructor(props){
super(props);
const SharedActor = SharedContainer.get();
this.appName = SharedActor.appName ? SharedActor.appName : appName;
}
render() {
return (
<section className="mobile-placeholder col-xs row center-xs middle-xs">
<div>
<img alt={`${this.appName} messenger`}
className="logo"
src="assets/images/logo.png"
srcSet="assets/images/logo@2x.png 2x"/>
<FormattedHTMLMessage id="main.install" values={{ appName: this.appName }}/>
</div>
</section>
);
}
}
export default Install;
|
src/applications/disability-benefits/disability-rating-calculator/createCalculator.js
|
department-of-veterans-affairs/vets-website
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
export default function createDisabilityRatingCalculator(store, widgetType) {
const root = document.querySelector(`[data-widget-type="${widgetType}"]`);
if (root) {
import(/* webpackChunkName: "disability-rating-calculator" */
'./calculator-entry').then(module => {
const { DisabilityRatingCalculator } = module.default;
ReactDOM.render(
<Provider store={store}>
<DisabilityRatingCalculator />
</Provider>,
root,
);
});
}
}
|
src/client/react/admin/views/LogsView/Filters.js
|
bwyap/ptc-amazing-g-race
|
import React from 'react';
import PropTypes from 'prop-types';
import autobind from 'core-decorators/es/autobind';
import { Button, Intent } from '@blueprintjs/core';
import FormInput from '../../../../../../lib/react/components/forms/FormInput';
@autobind
class Filters extends React.Component {
static propTypes = {
action: PropTypes.string.isRequired,
username: PropTypes.string.isRequired,
skip: PropTypes.string.isRequired,
limit: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onFilter: PropTypes.func.isRequired,
loading: PropTypes.bool.isRequired
}
render() {
return (
<div className='pt-callout'>
<div className='filters'>
<FormInput id='username' label='Username' value={this.props.username} onChange={this.props.onChange} disabled={this.props.loading}/>
<FormInput id='action' label='Action' value={this.props.action} onChange={this.props.onChange} disabled={this.props.loading}/>
<FormInput id='skip' label='Skip' value={this.props.skip} onChange={this.props.onChange} disabled={this.props.loading}/>
<FormInput id='limit' label='Limit' value={this.props.limit} onChange={this.props.onChange} disabled={this.props.loading}/>
</div>
<Button text='Get logs' iconName='cloud-download' className='pt-fill pt-minimal' onClick={this.props.onFilter} loading={this.props.loading}/>
</div>
);
}
}
export default Filters;
|
ajax/libs/react-bootstrap-table/2.3.8/react-bootstrap-table.js
|
brix/cdnjs
|
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"), require("react-dom"));
else if(typeof define === 'function' && define.amd)
define(["react", "react-dom"], factory);
else if(typeof exports === 'object')
exports["ReactBootstrapTable"] = factory(require("react"), require("react-dom"));
else
root["ReactBootstrapTable"] = factory(root["React"], root["ReactDOM"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_5__) {
return /******/ (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__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _BootstrapTable = __webpack_require__(1);
var _BootstrapTable2 = _interopRequireDefault(_BootstrapTable);
var _TableHeaderColumn = __webpack_require__(41);
var _TableHeaderColumn2 = _interopRequireDefault(_TableHeaderColumn);
if (typeof window !== 'undefined') {
window.BootstrapTable = _BootstrapTable2['default'];
window.TableHeaderColumn = _TableHeaderColumn2['default'];
}
exports.BootstrapTable = _BootstrapTable2['default'];
exports.TableHeaderColumn = _TableHeaderColumn2['default'];
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
/* eslint no-alert: 0 */
/* eslint max-len: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _TableHeader = __webpack_require__(4);
var _TableHeader2 = _interopRequireDefault(_TableHeader);
var _TableBody = __webpack_require__(8);
var _TableBody2 = _interopRequireDefault(_TableBody);
var _paginationPaginationList = __webpack_require__(29);
var _paginationPaginationList2 = _interopRequireDefault(_paginationPaginationList);
var _toolbarToolBar = __webpack_require__(31);
var _toolbarToolBar2 = _interopRequireDefault(_toolbarToolBar);
var _TableFilter = __webpack_require__(32);
var _TableFilter2 = _interopRequireDefault(_TableFilter);
var _storeTableDataStore = __webpack_require__(33);
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
var _csv_export_util = __webpack_require__(35);
var _csv_export_util2 = _interopRequireDefault(_csv_export_util);
var _Filter = __webpack_require__(39);
var BootstrapTable = (function (_Component) {
_inherits(BootstrapTable, _Component);
function BootstrapTable(props) {
var _this = this;
_classCallCheck(this, BootstrapTable);
_get(Object.getPrototypeOf(BootstrapTable.prototype), 'constructor', this).call(this, props);
this.handleSort = function (order, sortField) {
if (_this.props.options.onSortChange) {
_this.props.options.onSortChange(sortField, order, _this.props);
}
if (_this.isRemoteDataSource()) {
_this.store.setSortInfo(order, sortField);
return;
}
var result = _this.store.sort(order, sortField).get();
_this.setState({
data: result
});
};
this.handlePaginationData = function (page, sizePerPage) {
var _props$options = _this.props.options;
var onPageChange = _props$options.onPageChange;
var pageStartIndex = _props$options.pageStartIndex;
if (onPageChange) {
onPageChange(page, sizePerPage);
}
_this.setState({
currPage: page,
sizePerPage: sizePerPage
});
if (_this.isRemoteDataSource()) {
return;
}
// We calculate an offset here in order to properly fetch the indexed data,
// despite the page start index not always being 1
var normalizedPage = undefined;
if (pageStartIndex !== undefined) {
var offset = Math.abs(_Const2['default'].PAGE_START_INDEX - pageStartIndex);
normalizedPage = page + offset;
} else {
normalizedPage = page;
}
var result = _this.store.page(normalizedPage, sizePerPage).get();
_this.setState({ data: result });
};
this.handleMouseLeave = function () {
if (_this.props.options.onMouseLeave) {
_this.props.options.onMouseLeave();
}
};
this.handleMouseEnter = function () {
if (_this.props.options.onMouseEnter) {
_this.props.options.onMouseEnter();
}
};
this.handleRowMouseOut = function (row, event) {
if (_this.props.options.onRowMouseOut) {
_this.props.options.onRowMouseOut(row, event);
}
};
this.handleRowMouseOver = function (row, event) {
if (_this.props.options.onRowMouseOver) {
_this.props.options.onRowMouseOver(row, event);
}
};
this.handleRowClick = function (row) {
if (_this.props.options.onRowClick) {
_this.props.options.onRowClick(row);
}
};
this.handleSelectAllRow = function (e) {
var isSelected = e.currentTarget.checked;
var keyField = _this.store.getKeyField();
var _props$selectRow = _this.props.selectRow;
var onSelectAll = _props$selectRow.onSelectAll;
var unselectable = _props$selectRow.unselectable;
var selectedRowKeys = [];
var result = true;
var rows = _this.store.get();
if (isSelected && unselectable && unselectable.length > 0) {
rows = rows.filter(function (r) {
return unselectable.indexOf(r[keyField]) === -1;
});
}
if (onSelectAll) {
result = _this.props.selectRow.onSelectAll(isSelected, isSelected ? rows : _this.store.getRowByKey(_this.state.selectedRowKeys));
}
if (typeof result == 'undefined' || result !== false) {
if (isSelected) {
selectedRowKeys = Array.isArray(result) ? result : rows.map(function (r) {
return r[keyField];
});
}
_this.store.setSelectedRowKey(selectedRowKeys);
_this.setState({ selectedRowKeys: selectedRowKeys });
}
};
this.handleShowOnlySelected = function () {
_this.store.ignoreNonSelected();
var result = undefined;
if (_this.props.pagination) {
result = _this.store.page(1, _this.state.sizePerPage).get();
} else {
result = _this.store.get();
}
_this.setState({
data: result,
currPage: _this.props.options.pageStartIndex || _Const2['default'].PAGE_START_INDEX
});
};
this.handleSelectRow = function (row, isSelected, e) {
var result = true;
var currSelected = _this.store.getSelectedRowKeys();
var rowKey = row[_this.store.getKeyField()];
var selectRow = _this.props.selectRow;
if (selectRow.onSelect) {
result = selectRow.onSelect(row, isSelected, e);
}
if (typeof result === 'undefined' || result !== false) {
if (selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE) {
currSelected = isSelected ? [rowKey] : [];
} else {
if (isSelected) {
currSelected.push(rowKey);
} else {
currSelected = currSelected.filter(function (key) {
return rowKey !== key;
});
}
}
_this.store.setSelectedRowKey(currSelected);
_this.setState({
selectedRowKeys: currSelected
});
}
};
this.handleAddRow = function (newObj) {
var onAddRow = _this.props.options.onAddRow;
if (onAddRow) {
var colInfos = _this.store.getColInfos();
onAddRow(newObj, colInfos);
}
if (_this.isRemoteDataSource()) {
if (_this.props.options.afterInsertRow) {
_this.props.options.afterInsertRow(newObj);
}
return null;
}
try {
_this.store.add(newObj);
} catch (e) {
return e;
}
_this._handleAfterAddingRow(newObj);
};
this.getPageByRowKey = function (rowKey) {
var sizePerPage = _this.state.sizePerPage;
var currentData = _this.store.getCurrentDisplayData();
var keyField = _this.store.getKeyField();
var result = currentData.findIndex(function (x) {
return x[keyField] === rowKey;
});
if (result > -1) {
return parseInt(result / sizePerPage, 10) + 1;
} else {
return result;
}
};
this.handleDropRow = function (rowKeys) {
var dropRowKeys = rowKeys ? rowKeys : _this.store.getSelectedRowKeys();
// add confirm before the delete action if that option is set.
if (dropRowKeys && dropRowKeys.length > 0) {
if (_this.props.options.handleConfirmDeleteRow) {
_this.props.options.handleConfirmDeleteRow(function () {
_this.deleteRow(dropRowKeys);
}, dropRowKeys);
} else if (confirm('Are you sure you want to delete?')) {
_this.deleteRow(dropRowKeys);
}
}
};
this.handleFilterData = function (filterObj) {
var onFilterChange = _this.props.options.onFilterChange;
if (onFilterChange) {
var colInfos = _this.store.getColInfos();
onFilterChange(filterObj, colInfos);
}
_this.setState({
currPage: _this.props.options.pageStartIndex || _Const2['default'].PAGE_START_INDEX
});
if (_this.isRemoteDataSource()) {
if (_this.props.options.afterColumnFilter) {
_this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination());
}
return;
}
_this.store.filter(filterObj);
var sortObj = _this.store.getSortInfo();
if (sortObj) {
_this.store.sort(sortObj.order, sortObj.sortField);
}
var result = undefined;
if (_this.props.pagination) {
var sizePerPage = _this.state.sizePerPage;
result = _this.store.page(1, sizePerPage).get();
} else {
result = _this.store.get();
}
if (_this.props.options.afterColumnFilter) {
_this.props.options.afterColumnFilter(filterObj, _this.store.getDataIgnoringPagination());
}
_this.setState({
data: result
});
};
this.handleExportCSV = function () {
var result = {};
var onExportToCSV = _this.props.options.onExportToCSV;
if (onExportToCSV) {
result = onExportToCSV();
}
var keys = [];
_this.props.children.map(function (column) {
console.log(column.props['export']);
if (column.props['export'] === true || typeof column.props['export'] === 'undefined' && column.props.hidden === false) {
keys.push({
field: column.props.dataField,
format: column.props.csvFormat,
header: column.props.csvHeader || column.props.dataField
});
}
});
if (_this.isRemoteDataSource()) {
(0, _csv_export_util2['default'])(result, keys, _this.props.csvFileName);
return;
}
result = _this.store.getDataIgnoringPagination();
(0, _csv_export_util2['default'])(result, keys, _this.props.csvFileName);
};
this.handleSearch = function (searchText) {
var onSearchChange = _this.props.options.onSearchChange;
if (onSearchChange) {
var colInfos = _this.store.getColInfos();
onSearchChange(searchText, colInfos, _this.props.multiColumnSearch);
}
_this.setState({
currPage: _this.props.options.pageStartIndex || _Const2['default'].PAGE_START_INDEX
});
if (_this.isRemoteDataSource()) {
if (_this.props.options.afterSearch) {
_this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination());
}
return;
}
_this.store.search(searchText);
var result = undefined;
if (_this.props.pagination) {
var sizePerPage = _this.state.sizePerPage;
result = _this.store.page(1, sizePerPage).get();
} else {
result = _this.store.get();
}
if (_this.props.options.afterSearch) {
_this.props.options.afterSearch(searchText, _this.store.getDataIgnoringPagination());
}
_this.setState({
data: result
});
};
this._scrollHeader = function (e) {
_this.refs.header.refs.container.scrollLeft = e.currentTarget.scrollLeft;
};
this._adjustTable = function () {
_this._adjustHeaderWidth();
_this._adjustHeight();
};
this._adjustHeaderWidth = function () {
var header = _this.refs.header.refs.header;
var headerContainer = _this.refs.header.refs.container;
var tbody = _this.refs.body.refs.tbody;
var firstRow = tbody.childNodes[0];
var isScroll = headerContainer.offsetWidth !== tbody.parentNode.offsetWidth;
var scrollBarWidth = isScroll ? _util2['default'].getScrollBarWidth() : 0;
if (firstRow && _this.store.getDataNum()) {
var cells = firstRow.childNodes;
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
var computedStyle = getComputedStyle(cell);
var width = parseFloat(computedStyle.width.replace('px', ''));
if (_this.isIE) {
var paddingLeftWidth = parseFloat(computedStyle.paddingLeft.replace('px', ''));
var paddingRightWidth = parseFloat(computedStyle.paddingRight.replace('px', ''));
var borderRightWidth = parseFloat(computedStyle.borderRightWidth.replace('px', ''));
var borderLeftWidth = parseFloat(computedStyle.borderLeftWidth.replace('px', ''));
width = width + paddingLeftWidth + paddingRightWidth + borderRightWidth + borderLeftWidth;
}
var lastPadding = cells.length - 1 === i ? scrollBarWidth : 0;
if (width <= 0) {
width = 120;
cell.width = width + lastPadding + 'px';
}
var result = width + lastPadding + 'px';
header.childNodes[i].style.width = result;
header.childNodes[i].style.minWidth = result;
}
}
};
this._adjustHeight = function () {
if (_this.props.height.indexOf('%') === -1) {
_this.refs.body.refs.container.style.height = parseFloat(_this.props.height, 10) - _this.refs.header.refs.container.offsetHeight + 'px';
}
};
this.isIE = false;
this._attachCellEditFunc();
if (_util2['default'].canUseDOM()) {
this.isIE = document.documentMode;
}
this.store = new _storeTableDataStore.TableDataStore(this.props.data.slice());
this.initTable(this.props);
if (this.filter) {
this.filter.on('onFilterChange', function (currentFilter) {
_this.handleFilterData(currentFilter);
});
}
if (this.props.selectRow && this.props.selectRow.selected) {
var copy = this.props.selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
}
var currPage = _Const2['default'].PAGE_START_INDEX;
if (typeof this.props.options.page !== 'undefined') {
currPage = this.props.options.page;
} else if (typeof this.props.options.pageStartIndex !== 'undefined') {
currPage = this.props.options.pageStartIndex;
}
this.state = {
data: this.getTableData(),
currPage: currPage,
sizePerPage: this.props.options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0],
selectedRowKeys: this.store.getSelectedRowKeys()
};
}
_createClass(BootstrapTable, [{
key: 'initTable',
value: function initTable(props) {
var _this2 = this;
var keyField = props.keyField;
var isKeyFieldDefined = typeof keyField === 'string' && keyField.length;
_react2['default'].Children.forEach(props.children, function (column) {
if (column.props.isKey) {
if (keyField) {
throw 'Error. Multiple key column be detected in TableHeaderColumn.';
}
keyField = column.props.dataField;
}
if (column.props.filter) {
// a column contains a filter
if (!_this2.filter) {
// first time create the filter on the BootstrapTable
_this2.filter = new _Filter.Filter();
}
// pass the filter to column with filter
column.props.filter.emitter = _this2.filter;
}
});
this.colInfos = this.getColumnsDescription(props).reduce(function (prev, curr) {
prev[curr.name] = curr;
return prev;
}, {});
if (!isKeyFieldDefined && !keyField) {
throw 'Error. No any key column defined in TableHeaderColumn.\n Use \'isKey={true}\' to specify a unique column after version 0.5.4.';
}
this.store.setProps({
isPagination: props.pagination,
keyField: keyField,
colInfos: this.colInfos,
multiColumnSearch: props.multiColumnSearch,
remote: this.isRemoteDataSource()
});
}
}, {
key: 'getTableData',
value: function getTableData() {
var result = [];
var _props = this.props;
var options = _props.options;
var pagination = _props.pagination;
var sortName = options.defaultSortName || options.sortName;
var sortOrder = options.defaultSortOrder || options.sortOrder;
if (sortName && sortOrder) {
this.store.sort(sortOrder, sortName);
}
if (pagination) {
var page = undefined;
var sizePerPage = undefined;
if (this.store.isChangedPage()) {
sizePerPage = this.state.sizePerPage;
page = this.state.currPage;
} else {
sizePerPage = options.sizePerPage || _Const2['default'].SIZE_PER_PAGE_LIST[0];
page = options.page || 1;
}
result = this.store.page(page, sizePerPage).get();
} else {
result = this.store.get();
}
return result;
}
}, {
key: 'getColumnsDescription',
value: function getColumnsDescription(_ref) {
var children = _ref.children;
return _react2['default'].Children.map(children, function (column, i) {
return {
name: column.props.dataField,
align: column.props.dataAlign,
sort: column.props.dataSort,
format: column.props.dataFormat,
formatExtraData: column.props.formatExtraData,
filterFormatted: column.props.filterFormatted,
editable: column.props.editable,
hidden: column.props.hidden,
hiddenOnInsert: column.props.hiddenOnInsert,
searchable: column.props.searchable,
className: column.props.columnClassName,
columnTitle: column.props.columnTitle,
width: column.props.width,
text: column.props.children,
sortFunc: column.props.sortFunc,
sortFuncExtraData: column.props.sortFuncExtraData,
'export': column.props['export'],
index: i
};
});
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
this.initTable(nextProps);
var options = nextProps.options;
var selectRow = nextProps.selectRow;
this.store.setData(nextProps.data.slice());
// from #481
var page = this.state.currPage;
if (this.props.options.page !== options.page) {
page = options.page;
}
// from #481
var sizePerPage = this.state.sizePerPage;
if (this.props.options.sizePerPage !== options.sizePerPage) {
sizePerPage = options.sizePerPage;
}
if (this.isRemoteDataSource()) {
this.setState({
data: nextProps.data.slice(),
currPage: page
});
} else {
// #125
if (!options.page && page > Math.ceil(nextProps.data.length / sizePerPage)) {
page = 1;
}
var sortInfo = this.store.getSortInfo();
var sortField = options.sortName || (sortInfo ? sortInfo.sortField : undefined);
var sortOrder = options.sortOrder || (sortInfo ? sortInfo.order : undefined);
if (sortField && sortOrder) this.store.sort(sortOrder, sortField);
var data = this.store.page(page, sizePerPage).get();
this.setState({
data: data,
currPage: page,
sizePerPage: sizePerPage
});
}
if (selectRow && selectRow.selected) {
// set default select rows to store.
var copy = selectRow.selected.slice();
this.store.setSelectedRowKey(copy);
this.setState({
selectedRowKeys: copy
});
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this._adjustTable();
window.addEventListener('resize', this._adjustTable);
this.refs.body.refs.container.addEventListener('scroll', this._scrollHeader);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
window.removeEventListener('resize', this._adjustTable);
this.refs.body.refs.container.removeEventListener('scroll', this._scrollHeader);
if (this.filter) {
this.filter.removeAllListeners('onFilterChange');
}
}
}, {
key: 'componentDidUpdate',
value: function componentDidUpdate() {
this._adjustTable();
this._attachCellEditFunc();
if (this.props.options.afterTableComplete) {
this.props.options.afterTableComplete();
}
}
}, {
key: '_attachCellEditFunc',
value: function _attachCellEditFunc() {
var cellEdit = this.props.cellEdit;
if (cellEdit) {
this.props.cellEdit.__onCompleteEdit__ = this.handleEditCell.bind(this);
if (cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE) {
this.props.selectRow.clickToSelect = false;
}
}
}
/**
* Returns true if in the current configuration,
* the datagrid should load its data remotely.
*
* @param {Object} [props] Optional. If not given, this.props will be used
* @return {Boolean}
*/
}, {
key: 'isRemoteDataSource',
value: function isRemoteDataSource(props) {
return (props || this.props).remote;
}
}, {
key: 'render',
value: function render() {
var style = {
height: this.props.height,
maxHeight: this.props.maxHeight
};
var columns = this.getColumnsDescription(this.props);
var sortInfo = this.store.getSortInfo();
var pagination = this.renderPagination();
var toolBar = this.renderToolBar();
var tableFilter = this.renderTableFilter(columns);
var isSelectAll = this.isSelectAll();
var sortIndicator = this.props.options.sortIndicator;
if (typeof this.props.options.sortIndicator === 'undefined') sortIndicator = true;
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-container', style: this.props.containerStyle },
toolBar,
_react2['default'].createElement(
'div',
{ className: 'react-bs-table', ref: 'table', style: _extends({}, style, this.props.tableStyle),
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave },
_react2['default'].createElement(
_TableHeader2['default'],
{
ref: 'header',
tableHeaderClass: this.props.tableHeaderClass,
style: this.props.headerStyle,
rowSelectType: this.props.selectRow.mode,
hideSelectColumn: this.props.selectRow.hideSelectColumn,
sortName: sortInfo ? sortInfo.sortField : undefined,
sortOrder: sortInfo ? sortInfo.order : undefined,
sortIndicator: sortIndicator,
onSort: this.handleSort,
onSelectAllRow: this.handleSelectAllRow,
bordered: this.props.bordered,
condensed: this.props.condensed,
isFiltered: this.filter ? true : false,
isSelectAll: isSelectAll },
this.props.children
),
_react2['default'].createElement(_TableBody2['default'], { ref: 'body',
tableBodyClass: this.props.tableBodyClass,
style: _extends({}, style, this.props.bodyStyle),
data: this.state.data,
columns: columns,
trClassName: this.props.trClassName,
striped: this.props.striped,
bordered: this.props.bordered,
hover: this.props.hover,
keyField: this.store.getKeyField(),
condensed: this.props.condensed,
selectRow: this.props.selectRow,
cellEdit: this.props.cellEdit,
selectedRowKeys: this.state.selectedRowKeys,
onRowClick: this.handleRowClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow,
noDataText: this.props.options.noDataText })
),
tableFilter,
pagination
);
}
}, {
key: 'isSelectAll',
value: function isSelectAll() {
if (this.store.isEmpty()) return false;
var defaultSelectRowKeys = this.store.getSelectedRowKeys();
var allRowKeys = this.store.getAllRowkey();
if (defaultSelectRowKeys.length === 0) return false;
var match = 0;
var noFound = 0;
defaultSelectRowKeys.forEach(function (selected) {
if (allRowKeys.indexOf(selected) !== -1) match++;else noFound++;
});
if (noFound === defaultSelectRowKeys.length) return false;
return match === allRowKeys.length ? true : 'indeterminate';
}
}, {
key: 'cleanSelected',
value: function cleanSelected() {
this.store.setSelectedRowKey([]);
this.setState({
selectedRowKeys: []
});
}
}, {
key: 'handleEditCell',
value: function handleEditCell(newVal, rowIndex, colIndex) {
var _props$cellEdit = this.props.cellEdit;
var beforeSaveCell = _props$cellEdit.beforeSaveCell;
var afterSaveCell = _props$cellEdit.afterSaveCell;
var fieldName = undefined;
_react2['default'].Children.forEach(this.props.children, function (column, i) {
if (i === colIndex) {
fieldName = column.props.dataField;
return false;
}
});
if (beforeSaveCell) {
var isValid = beforeSaveCell(this.state.data[rowIndex], fieldName, newVal);
if (!isValid && typeof isValid !== 'undefined') {
this.setState({
data: this.store.get()
});
return;
}
}
var result = this.store.edit(newVal, rowIndex, fieldName).get();
this.setState({
data: result
});
if (afterSaveCell) {
afterSaveCell(this.state.data[rowIndex], fieldName, newVal);
}
}
}, {
key: 'handleAddRowAtBegin',
value: function handleAddRowAtBegin(newObj) {
try {
this.store.addAtBegin(newObj);
} catch (e) {
return e;
}
this._handleAfterAddingRow(newObj);
}
}, {
key: 'getSizePerPage',
value: function getSizePerPage() {
return this.state.sizePerPage;
}
}, {
key: 'getCurrentPage',
value: function getCurrentPage() {
return this.state.currPage;
}
}, {
key: 'getTableDataIgnorePaging',
value: function getTableDataIgnorePaging() {
return this.store.getCurrentDisplayData();
}
}, {
key: 'deleteRow',
value: function deleteRow(dropRowKeys) {
var onDeleteRow = this.props.options.onDeleteRow;
if (onDeleteRow) {
onDeleteRow(dropRowKeys);
}
this.store.setSelectedRowKey([]); // clear selected row key
if (this.isRemoteDataSource()) {
if (this.props.options.afterDeleteRow) {
this.props.options.afterDeleteRow(dropRowKeys);
}
return;
}
this.store.remove(dropRowKeys); // remove selected Row
var result = undefined;
if (this.props.pagination) {
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
var currPage = this.state.currPage;
if (currPage > currLastPage) currPage = currLastPage;
result = this.store.page(currPage, sizePerPage).get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys(),
currPage: currPage
});
} else {
result = this.store.get();
this.setState({
data: result,
selectedRowKeys: this.store.getSelectedRowKeys()
});
}
if (this.props.options.afterDeleteRow) {
this.props.options.afterDeleteRow(dropRowKeys);
}
}
}, {
key: 'renderPagination',
value: function renderPagination() {
if (this.props.pagination) {
var dataSize = undefined;
if (this.isRemoteDataSource()) {
dataSize = this.props.fetchInfo.dataTotalSize;
} else {
dataSize = this.store.getDataNum();
}
var options = this.props.options;
if (Math.ceil(dataSize / this.state.sizePerPage) <= 1 && this.props.ignoreSinglePage) return null;
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-pagination' },
_react2['default'].createElement(_paginationPaginationList2['default'], {
ref: 'pagination',
currPage: this.state.currPage,
changePage: this.handlePaginationData,
sizePerPage: this.state.sizePerPage,
sizePerPageList: options.sizePerPageList || _Const2['default'].SIZE_PER_PAGE_LIST,
pageStartIndex: options.pageStartIndex,
paginationShowsTotal: options.paginationShowsTotal,
paginationSize: options.paginationSize || _Const2['default'].PAGINATION_SIZE,
remote: this.isRemoteDataSource(),
dataSize: dataSize,
onSizePerPageList: options.onSizePerPageList,
prePage: options.prePage || _Const2['default'].PRE_PAGE,
nextPage: options.nextPage || _Const2['default'].NEXT_PAGE,
firstPage: options.firstPage || _Const2['default'].FIRST_PAGE,
lastPage: options.lastPage || _Const2['default'].LAST_PAGE,
hideSizePerPage: options.hideSizePerPage })
);
}
return null;
}
}, {
key: 'renderToolBar',
value: function renderToolBar() {
var _props2 = this.props;
var selectRow = _props2.selectRow;
var insertRow = _props2.insertRow;
var deleteRow = _props2.deleteRow;
var search = _props2.search;
var children = _props2.children;
var enableShowOnlySelected = selectRow && selectRow.showOnlySelected;
if (enableShowOnlySelected || insertRow || deleteRow || search || this.props.exportCSV) {
var columns = undefined;
if (Array.isArray(children)) {
columns = children.map(function (column) {
var props = column.props;
return {
name: props.children,
field: props.dataField,
hiddenOnInsert: props.hiddenOnInsert,
// when you want same auto generate value and not allow edit, example ID field
autoValue: props.autoValue || false,
// for create editor, no params for column.editable() indicate that editor for new row
editable: props.editable && typeof props.editable === 'function' ? props.editable() : props.editable,
format: props.dataFormat ? function (value) {
return props.dataFormat(value, null, props.formatExtraData).replace(/<.*?>/g, '');
} : false
};
});
} else {
columns = [{
name: children.props.children,
field: children.props.dataField,
editable: children.props.editable,
hiddenOnInsert: children.props.hiddenOnInsert
}];
}
return _react2['default'].createElement(
'div',
{ className: 'react-bs-table-tool-bar' },
_react2['default'].createElement(_toolbarToolBar2['default'], {
clearSearch: this.props.options.clearSearch,
searchDelayTime: this.props.options.searchDelayTime,
enableInsert: insertRow,
enableDelete: deleteRow,
enableSearch: search,
enableExportCSV: this.props.exportCSV,
enableShowOnlySelected: enableShowOnlySelected,
columns: columns,
searchPlaceholder: this.props.searchPlaceholder,
exportCSVText: this.props.options.exportCSVText,
insertText: this.props.options.insertText,
deleteText: this.props.options.deleteText,
saveText: this.props.options.saveText,
closeText: this.props.options.closeText,
ignoreEditable: this.props.options.ignoreEditable,
onAddRow: this.handleAddRow,
onDropRow: this.handleDropRow,
onSearch: this.handleSearch,
onExportCSV: this.handleExportCSV,
onShowOnlySelected: this.handleShowOnlySelected })
);
} else {
return null;
}
}
}, {
key: 'renderTableFilter',
value: function renderTableFilter(columns) {
if (this.props.columnFilter) {
return _react2['default'].createElement(_TableFilter2['default'], { columns: columns,
rowSelectType: this.props.selectRow.mode,
onFilter: this.handleFilterData });
} else {
return null;
}
}
}, {
key: '_handleAfterAddingRow',
value: function _handleAfterAddingRow(newObj) {
var result = undefined;
if (this.props.pagination) {
// if pagination is enabled and insert row be trigger, change to last page
var sizePerPage = this.state.sizePerPage;
var currLastPage = Math.ceil(this.store.getDataNum() / sizePerPage);
result = this.store.page(currLastPage, sizePerPage).get();
this.setState({
data: result,
currPage: currLastPage
});
} else {
result = this.store.get();
this.setState({
data: result
});
}
if (this.props.options.afterInsertRow) {
this.props.options.afterInsertRow(newObj);
}
}
}]);
return BootstrapTable;
})(_react.Component);
BootstrapTable.propTypes = {
keyField: _react.PropTypes.string,
height: _react.PropTypes.string,
maxHeight: _react.PropTypes.string,
data: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]),
remote: _react.PropTypes.bool, // remote data, default is false
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
pagination: _react.PropTypes.bool,
searchPlaceholder: _react.PropTypes.string,
selectRow: _react.PropTypes.shape({
mode: _react.PropTypes.oneOf([_Const2['default'].ROW_SELECT_NONE, _Const2['default'].ROW_SELECT_SINGLE, _Const2['default'].ROW_SELECT_MULTI]),
bgColor: _react.PropTypes.string,
selected: _react.PropTypes.array,
onSelect: _react.PropTypes.func,
onSelectAll: _react.PropTypes.func,
clickToSelect: _react.PropTypes.bool,
hideSelectColumn: _react.PropTypes.bool,
clickToSelectAndEditCell: _react.PropTypes.bool,
showOnlySelected: _react.PropTypes.bool,
unselectable: _react.PropTypes.array
}),
cellEdit: _react.PropTypes.shape({
mode: _react.PropTypes.string,
blurToSave: _react.PropTypes.bool,
beforeSaveCell: _react.PropTypes.func,
afterSaveCell: _react.PropTypes.func
}),
insertRow: _react.PropTypes.bool,
deleteRow: _react.PropTypes.bool,
search: _react.PropTypes.bool,
columnFilter: _react.PropTypes.bool,
trClassName: _react.PropTypes.any,
tableStyle: _react.PropTypes.object,
containerStyle: _react.PropTypes.object,
headerStyle: _react.PropTypes.object,
bodyStyle: _react.PropTypes.object,
tableHeaderClass: _react.PropTypes.string,
tableBodyClass: _react.PropTypes.string,
options: _react.PropTypes.shape({
clearSearch: _react.PropTypes.bool,
sortName: _react.PropTypes.string,
sortOrder: _react.PropTypes.string,
defaultSortName: _react.PropTypes.string,
defaultSortOrder: _react.PropTypes.string,
sortIndicator: _react.PropTypes.bool,
afterTableComplete: _react.PropTypes.func,
afterDeleteRow: _react.PropTypes.func,
afterInsertRow: _react.PropTypes.func,
afterSearch: _react.PropTypes.func,
afterColumnFilter: _react.PropTypes.func,
onRowClick: _react.PropTypes.func,
page: _react.PropTypes.number,
pageStartIndex: _react.PropTypes.number,
paginationShowsTotal: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
sizePerPageList: _react.PropTypes.array,
sizePerPage: _react.PropTypes.number,
paginationSize: _react.PropTypes.number,
hideSizePerPage: _react.PropTypes.bool,
onSortChange: _react.PropTypes.func,
onPageChange: _react.PropTypes.func,
onSizePerPageList: _react.PropTypes.func,
onFilterChange: _react2['default'].PropTypes.func,
onSearchChange: _react2['default'].PropTypes.func,
onAddRow: _react2['default'].PropTypes.func,
onExportToCSV: _react2['default'].PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
handleConfirmDeleteRow: _react.PropTypes.func,
prePage: _react.PropTypes.string,
nextPage: _react.PropTypes.string,
firstPage: _react.PropTypes.string,
lastPage: _react.PropTypes.string,
searchDelayTime: _react.PropTypes.number,
exportCSVText: _react.PropTypes.string,
insertText: _react.PropTypes.string,
deleteText: _react.PropTypes.string,
saveText: _react.PropTypes.string,
closeText: _react.PropTypes.string,
ignoreEditable: _react.PropTypes.bool
}),
fetchInfo: _react.PropTypes.shape({
dataTotalSize: _react.PropTypes.number
}),
exportCSV: _react.PropTypes.bool,
csvFileName: _react.PropTypes.string,
ignoreSinglePage: _react.PropTypes.bool
};
BootstrapTable.defaultProps = {
height: '100%',
maxHeight: undefined,
striped: false,
bordered: true,
hover: false,
condensed: false,
pagination: false,
searchPlaceholder: undefined,
selectRow: {
mode: _Const2['default'].ROW_SELECT_NONE,
bgColor: _Const2['default'].ROW_SELECT_BG_COLOR,
selected: [],
onSelect: undefined,
onSelectAll: undefined,
clickToSelect: false,
hideSelectColumn: false,
clickToSelectAndEditCell: false,
showOnlySelected: false,
unselectable: []
},
cellEdit: {
mode: _Const2['default'].CELL_EDIT_NONE,
blurToSave: false,
beforeSaveCell: undefined,
afterSaveCell: undefined
},
insertRow: false,
deleteRow: false,
search: false,
multiColumnSearch: false,
columnFilter: false,
trClassName: '',
tableStyle: undefined,
containerStyle: undefined,
headerStyle: undefined,
bodyStyle: undefined,
tableHeaderClass: null,
tableBodyClass: null,
options: {
clearSearch: false,
sortName: undefined,
sortOrder: undefined,
defaultSortName: undefined,
defaultSortOrder: undefined,
sortIndicator: true,
afterTableComplete: undefined,
afterDeleteRow: undefined,
afterInsertRow: undefined,
afterSearch: undefined,
afterColumnFilter: undefined,
onRowClick: undefined,
onMouseLeave: undefined,
onMouseEnter: undefined,
onRowMouseOut: undefined,
onRowMouseOver: undefined,
page: undefined,
paginationShowsTotal: false,
sizePerPageList: _Const2['default'].SIZE_PER_PAGE_LIST,
sizePerPage: undefined,
paginationSize: _Const2['default'].PAGINATION_SIZE,
hideSizePerPage: false,
onSizePerPageList: undefined,
noDataText: undefined,
handleConfirmDeleteRow: undefined,
prePage: _Const2['default'].PRE_PAGE,
nextPage: _Const2['default'].NEXT_PAGE,
firstPage: _Const2['default'].FIRST_PAGE,
lastPage: _Const2['default'].LAST_PAGE,
pageStartIndex: undefined,
searchDelayTime: undefined,
exportCSVText: _Const2['default'].EXPORT_CSV_TEXT,
insertText: _Const2['default'].INSERT_BTN_TEXT,
deleteText: _Const2['default'].DELETE_BTN_TEXT,
saveText: _Const2['default'].SAVE_BTN_TEXT,
closeText: _Const2['default'].CLOSE_BTN_TEXT,
ignoreEditable: false
},
fetchInfo: {
dataTotalSize: 0
},
exportCSV: false,
csvFileName: 'spreadsheet.csv',
ignoreSinglePage: false
};
exports['default'] = BootstrapTable;
module.exports = exports['default'];
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
exports['default'] = {
SORT_DESC: 'desc',
SORT_ASC: 'asc',
SIZE_PER_PAGE: 10,
NEXT_PAGE: '>',
LAST_PAGE: '>>',
PRE_PAGE: '<',
FIRST_PAGE: '<<',
PAGE_START_INDEX: 1,
ROW_SELECT_BG_COLOR: '',
ROW_SELECT_NONE: 'none',
ROW_SELECT_SINGLE: 'radio',
ROW_SELECT_MULTI: 'checkbox',
CELL_EDIT_NONE: 'none',
CELL_EDIT_CLICK: 'click',
CELL_EDIT_DBCLICK: 'dbclick',
SIZE_PER_PAGE_LIST: [10, 25, 30, 50],
PAGINATION_SIZE: 5,
NO_DATA_TEXT: 'There is no data to display',
SHOW_ONLY_SELECT: 'Show Selected Only',
SHOW_ALL: 'Show All',
EXPORT_CSV_TEXT: 'Export to CSV',
INSERT_BTN_TEXT: 'New',
DELETE_BTN_TEXT: 'Delete',
SAVE_BTN_TEXT: 'Save',
CLOSE_BTN_TEXT: 'Close',
FILTER_DELAY: 500,
FILTER_TYPE: {
TEXT: 'TextFilter',
REGEX: 'RegexFilter',
SELECT: 'SelectFilter',
NUMBER: 'NumberFilter',
DATE: 'DateFilter',
CUSTOM: 'CustomFilter'
}
};
module.exports = exports['default'];
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _SelectRowHeaderColumn = __webpack_require__(7);
var _SelectRowHeaderColumn2 = _interopRequireDefault(_SelectRowHeaderColumn);
var Checkbox = (function (_Component) {
_inherits(Checkbox, _Component);
function Checkbox() {
_classCallCheck(this, Checkbox);
_get(Object.getPrototypeOf(Checkbox.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Checkbox, [{
key: 'componentDidMount',
value: function componentDidMount() {
this.update(this.props.checked);
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(props) {
this.update(props.checked);
}
}, {
key: 'update',
value: function update(checked) {
_reactDom2['default'].findDOMNode(this).indeterminate = checked === 'indeterminate';
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement('input', { className: 'react-bs-select-all',
type: 'checkbox',
checked: this.props.checked,
onChange: this.props.onChange });
}
}]);
return Checkbox;
})(_react.Component);
var TableHeader = (function (_Component2) {
_inherits(TableHeader, _Component2);
function TableHeader() {
_classCallCheck(this, TableHeader);
_get(Object.getPrototypeOf(TableHeader.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(TableHeader, [{
key: 'render',
value: function render() {
var _this = this;
var containerClasses = (0, _classnames2['default'])('react-bs-container-header', 'table-header-wrapper');
var tableClasses = (0, _classnames2['default'])('table', 'table-hover', {
'table-bordered': this.props.bordered,
'table-condensed': this.props.condensed
}, this.props.tableHeaderClass);
var selectRowHeaderCol = null;
if (!this.props.hideSelectColumn) selectRowHeaderCol = this.renderSelectRowHeader();
var i = 0;
return _react2['default'].createElement(
'div',
{ ref: 'container', className: containerClasses, style: this.props.style },
_react2['default'].createElement(
'table',
{ className: tableClasses },
_react2['default'].createElement(
'thead',
null,
_react2['default'].createElement(
'tr',
{ ref: 'header' },
selectRowHeaderCol,
_react2['default'].Children.map(this.props.children, function (elm) {
var _props = _this.props;
var sortIndicator = _props.sortIndicator;
var sortName = _props.sortName;
var sortOrder = _props.sortOrder;
var onSort = _props.onSort;
var _elm$props = elm.props;
var dataField = _elm$props.dataField;
var dataSort = _elm$props.dataSort;
var sort = dataSort && dataField === sortName ? sortOrder : undefined;
return _react2['default'].cloneElement(elm, { key: i++, onSort: onSort, sort: sort, sortIndicator: sortIndicator });
})
)
)
)
);
}
}, {
key: 'renderSelectRowHeader',
value: function renderSelectRowHeader() {
if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_SINGLE) {
return _react2['default'].createElement(_SelectRowHeaderColumn2['default'], null);
} else if (this.props.rowSelectType === _Const2['default'].ROW_SELECT_MULTI) {
return _react2['default'].createElement(
_SelectRowHeaderColumn2['default'],
null,
_react2['default'].createElement(Checkbox, {
onChange: this.props.onSelectAllRow,
checked: this.props.isSelectAll })
);
} else {
return null;
}
}
}]);
return TableHeader;
})(_react.Component);
TableHeader.propTypes = {
tableHeaderClass: _react.PropTypes.string,
style: _react.PropTypes.object,
rowSelectType: _react.PropTypes.string,
onSort: _react.PropTypes.func,
onSelectAllRow: _react.PropTypes.func,
sortName: _react.PropTypes.string,
sortOrder: _react.PropTypes.string,
hideSelectColumn: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
isFiltered: _react.PropTypes.bool,
isSelectAll: _react.PropTypes.oneOf([true, 'indeterminate', false]),
sortIndicator: _react.PropTypes.bool
};
exports['default'] = TableHeader;
module.exports = exports['default'];
/***/ },
/* 5 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_5__;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*!
Copyright (c) 2016 Jed Watson.
Licensed under the MIT License (MIT), see
http://jedwatson.github.io/classnames
*/
/* global define */
(function () {
'use strict';
var hasOwn = {}.hasOwnProperty;
function classNames () {
var classes = [];
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i];
if (!arg) continue;
var argType = typeof arg;
if (argType === 'string' || argType === 'number') {
classes.push(arg);
} else if (Array.isArray(arg)) {
classes.push(classNames.apply(null, arg));
} else if (argType === 'object') {
for (var key in arg) {
if (hasOwn.call(arg, key) && arg[key]) {
classes.push(key);
}
}
}
}
return classes.join(' ');
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = classNames;
} else if (true) {
// register as 'classnames', consistent with npm package name
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return classNames;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else {
window.classNames = classNames;
}
}());
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var SelectRowHeaderColumn = (function (_Component) {
_inherits(SelectRowHeaderColumn, _Component);
function SelectRowHeaderColumn() {
_classCallCheck(this, SelectRowHeaderColumn);
_get(Object.getPrototypeOf(SelectRowHeaderColumn.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(SelectRowHeaderColumn, [{
key: 'render',
value: function render() {
return _react2['default'].createElement(
'th',
{ style: { textAlign: 'center' } },
this.props.children
);
}
}]);
return SelectRowHeaderColumn;
})(_react.Component);
SelectRowHeaderColumn.propTypes = {
children: _react.PropTypes.node
};
exports['default'] = SelectRowHeaderColumn;
module.exports = exports['default'];
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _TableRow = __webpack_require__(9);
var _TableRow2 = _interopRequireDefault(_TableRow);
var _TableColumn = __webpack_require__(10);
var _TableColumn2 = _interopRequireDefault(_TableColumn);
var _TableEditColumn = __webpack_require__(11);
var _TableEditColumn2 = _interopRequireDefault(_TableEditColumn);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var isFun = function isFun(obj) {
return obj && typeof obj === 'function';
};
var TableBody = (function (_Component) {
_inherits(TableBody, _Component);
function TableBody(props) {
var _this = this;
_classCallCheck(this, TableBody);
_get(Object.getPrototypeOf(TableBody.prototype), 'constructor', this).call(this, props);
this.handleRowMouseOut = function (rowIndex, event) {
var targetRow = _this.props.data[rowIndex];
_this.props.onRowMouseOut(targetRow, event);
};
this.handleRowMouseOver = function (rowIndex, event) {
var targetRow = _this.props.data[rowIndex];
_this.props.onRowMouseOver(targetRow, event);
};
this.handleRowClick = function (rowIndex) {
var selectedRow = undefined;
var _props = _this.props;
var data = _props.data;
var onRowClick = _props.onRowClick;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
}
});
onRowClick(selectedRow);
};
this.handleSelectRow = function (rowIndex, isSelected, e) {
var selectedRow = undefined;
var _props2 = _this.props;
var data = _props2.data;
var onSelectRow = _props2.onSelectRow;
data.forEach(function (row, i) {
if (i === rowIndex - 1) {
selectedRow = row;
return false;
}
});
onSelectRow(selectedRow, isSelected, e);
};
this.handleSelectRowColumChange = function (e) {
if (!_this.props.selectRow.clickToSelect || !_this.props.selectRow.clickToSelectAndEditCell) {
_this.handleSelectRow(e.currentTarget.parentElement.parentElement.rowIndex + 1, e.currentTarget.checked, e);
}
};
this.handleEditCell = function (rowIndex, columnIndex, e) {
_this.editing = true;
if (_this._isSelectRowDefined()) {
columnIndex--;
if (_this.props.selectRow.hideSelectColumn) columnIndex++;
}
rowIndex--;
var stateObj = {
currEditCell: {
rid: rowIndex,
cid: columnIndex
}
};
if (_this.props.selectRow.clickToSelectAndEditCell && _this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_DBCLICK) {
var selected = _this.props.selectedRowKeys.indexOf(_this.props.data[rowIndex][_this.props.keyField]) !== -1;
_this.handleSelectRow(rowIndex + 1, !selected, e);
}
_this.setState(stateObj);
};
this.handleCompleteEditCell = function (newVal, rowIndex, columnIndex) {
_this.setState({ currEditCell: null });
if (newVal !== null) {
_this.props.cellEdit.__onCompleteEdit__(newVal, rowIndex, columnIndex);
}
};
this.state = {
currEditCell: null
};
this.editing = false;
}
_createClass(TableBody, [{
key: 'render',
value: function render() {
var tableClasses = (0, _classnames2['default'])('table', {
'table-striped': this.props.striped,
'table-bordered': this.props.bordered,
'table-hover': this.props.hover,
'table-condensed': this.props.condensed
}, this.props.tableBodyClass);
var unselectable = this.props.selectRow.unselectable || [];
var isSelectRowDefined = this._isSelectRowDefined();
var tableHeader = this.renderTableHeader(isSelectRowDefined);
var inputType = this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE ? 'radio' : 'checkbox';
var tableRows = this.props.data.map(function (data, r) {
var tableColumns = this.props.columns.map(function (column, i) {
var fieldValue = data[column.name];
if (this.editing && column.name !== this.props.keyField && // Key field can't be edit
column.editable && // column is editable? default is true, user can set it false
this.state.currEditCell !== null && this.state.currEditCell.rid === r && this.state.currEditCell.cid === i) {
var editable = column.editable;
var format = column.format ? function (value) {
return column.format(value, data, column.formatExtraData).replace(/<.*?>/g, '');
} : false;
if (isFun(column.editable)) {
editable = column.editable(fieldValue, data, r, i);
}
return _react2['default'].createElement(
_TableEditColumn2['default'],
{
completeEdit: this.handleCompleteEditCell,
// add by bluespring for column editor customize
editable: editable,
format: column.format ? format : false,
key: i,
blurToSave: this.props.cellEdit.blurToSave,
rowIndex: r,
colIndex: i },
fieldValue
);
} else {
// add by bluespring for className customize
var columnChild = fieldValue;
var columnTitle = null;
var tdClassName = column.className;
if (isFun(column.className)) {
tdClassName = column.className(fieldValue, data, r, i);
}
if (typeof column.format !== 'undefined') {
var formattedValue = column.format(fieldValue, data, column.formatExtraData);
if (!_react2['default'].isValidElement(formattedValue)) {
columnChild = _react2['default'].createElement('div', { dangerouslySetInnerHTML: { __html: formattedValue } });
} else {
columnChild = formattedValue;
columnTitle = column.columnTitle && formattedValue ? formattedValue.toString() : null;
}
} else {
columnTitle = column.columnTitle && fieldValue ? fieldValue.toString() : null;
}
return _react2['default'].createElement(
_TableColumn2['default'],
{ key: i,
dataAlign: column.align,
className: tdClassName,
columnTitle: columnTitle,
cellEdit: this.props.cellEdit,
hidden: column.hidden,
onEdit: this.handleEditCell,
width: column.width },
columnChild
);
}
}, this);
var key = data[this.props.keyField];
var disable = unselectable.indexOf(key) !== -1;
var selected = this.props.selectedRowKeys.indexOf(key) !== -1;
var selectRowColumn = isSelectRowDefined && !this.props.selectRow.hideSelectColumn ? this.renderSelectRowColumn(selected, inputType, disable) : null;
// add by bluespring for className customize
var trClassName = this.props.trClassName;
if (isFun(this.props.trClassName)) {
trClassName = this.props.trClassName(data, r);
}
return _react2['default'].createElement(
_TableRow2['default'],
{ isSelected: selected, key: key, className: trClassName,
selectRow: isSelectRowDefined ? this.props.selectRow : undefined,
enableCellEdit: this.props.cellEdit.mode !== _Const2['default'].CELL_EDIT_NONE,
onRowClick: this.handleRowClick,
onRowMouseOver: this.handleRowMouseOver,
onRowMouseOut: this.handleRowMouseOut,
onSelectRow: this.handleSelectRow,
unselectableRow: disable },
selectRowColumn,
tableColumns
);
}, this);
if (tableRows.length === 0) {
tableRows.push(_react2['default'].createElement(
_TableRow2['default'],
{ key: '##table-empty##' },
_react2['default'].createElement(
'td',
{ colSpan: this.props.columns.length + (isSelectRowDefined ? 1 : 0),
className: 'react-bs-table-no-data' },
this.props.noDataText || _Const2['default'].NO_DATA_TEXT
)
));
}
this.editing = false;
return _react2['default'].createElement(
'div',
{ ref: 'container', className: 'react-bs-container-body', style: this.props.style },
_react2['default'].createElement(
'table',
{ className: tableClasses },
tableHeader,
_react2['default'].createElement(
'tbody',
{ ref: 'tbody' },
tableRows
)
)
);
}
}, {
key: 'renderTableHeader',
value: function renderTableHeader(isSelectRowDefined) {
var selectRowHeader = null;
if (isSelectRowDefined) {
var style = {
width: 30,
minWidth: 30
};
if (!this.props.selectRow.hideSelectColumn) {
selectRowHeader = _react2['default'].createElement('col', { style: style, key: -1 });
}
}
var theader = this.props.columns.map(function (column, i) {
var style = {
display: column.hidden ? 'none' : null
};
if (column.width) {
var width = parseInt(column.width, 10);
style.width = width;
/** add min-wdth to fix user assign column width
not eq offsetWidth in large column table **/
style.minWidth = width;
}
return _react2['default'].createElement('col', { style: style, key: i, className: column.className });
});
return _react2['default'].createElement(
'colgroup',
{ ref: 'header' },
selectRowHeader,
theader
);
}
}, {
key: 'renderSelectRowColumn',
value: function renderSelectRowColumn(selected, inputType, disabled) {
return _react2['default'].createElement(
_TableColumn2['default'],
{ dataAlign: 'center' },
_react2['default'].createElement('input', { type: inputType, checked: selected, disabled: disabled,
onChange: this.handleSelectRowColumChange })
);
}
}, {
key: '_isSelectRowDefined',
value: function _isSelectRowDefined() {
return this.props.selectRow.mode === _Const2['default'].ROW_SELECT_SINGLE || this.props.selectRow.mode === _Const2['default'].ROW_SELECT_MULTI;
}
}]);
return TableBody;
})(_react.Component);
TableBody.propTypes = {
data: _react.PropTypes.array,
columns: _react.PropTypes.array,
striped: _react.PropTypes.bool,
bordered: _react.PropTypes.bool,
hover: _react.PropTypes.bool,
condensed: _react.PropTypes.bool,
keyField: _react.PropTypes.string,
selectedRowKeys: _react.PropTypes.array,
onRowClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
noDataText: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]),
style: _react.PropTypes.object,
tableBodyClass: _react.PropTypes.string
};
exports['default'] = TableBody;
module.exports = exports['default'];
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var TableRow = (function (_Component) {
_inherits(TableRow, _Component);
function TableRow(props) {
var _this = this;
_classCallCheck(this, TableRow);
_get(Object.getPrototypeOf(TableRow.prototype), 'constructor', this).call(this, props);
this.rowClick = function (e) {
if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'SELECT' && e.target.tagName !== 'TEXTAREA') {
(function () {
var rowIndex = e.currentTarget.rowIndex + 1;
var _props = _this.props;
var selectRow = _props.selectRow;
var unselectableRow = _props.unselectableRow;
var isSelected = _props.isSelected;
var onSelectRow = _props.onSelectRow;
if (selectRow) {
if (selectRow.clickToSelect && !unselectableRow) {
onSelectRow(rowIndex, !isSelected, e);
} else if (selectRow.clickToSelectAndEditCell && !unselectableRow) {
_this.clickNum++;
/** if clickToSelectAndEditCell is enabled,
* there should be a delay to prevent a selection changed when
* user dblick to edit cell on same row but different cell
**/
setTimeout(function () {
if (_this.clickNum === 1) {
onSelectRow(rowIndex, !isSelected, e);
}
_this.clickNum = 0;
}, 200);
}
}
if (_this.props.onRowClick) _this.props.onRowClick(rowIndex);
})();
}
};
this.rowMouseOut = function (e) {
if (_this.props.onRowMouseOut) {
_this.props.onRowMouseOut(e.currentTarget.rowIndex, e);
}
};
this.rowMouseOver = function (e) {
if (_this.props.onRowMouseOver) {
_this.props.onRowMouseOver(e.currentTarget.rowIndex, e);
}
};
this.clickNum = 0;
}
_createClass(TableRow, [{
key: 'render',
value: function render() {
this.clickNum = 0;
var trCss = {
style: {
backgroundColor: this.props.isSelected ? this.props.selectRow.bgColor : null
},
className: (0, _classnames2['default'])(this.props.isSelected ? this.props.selectRow.className : null, this.props.className)
};
if (this.props.selectRow && (this.props.selectRow.clickToSelect || this.props.selectRow.clickToSelectAndEditCell) || this.props.onRowClick) {
return _react2['default'].createElement(
'tr',
_extends({}, trCss, {
onMouseOver: this.rowMouseOver,
onMouseOut: this.rowMouseOut,
onClick: this.rowClick }),
this.props.children
);
} else {
return _react2['default'].createElement(
'tr',
trCss,
this.props.children
);
}
}
}]);
return TableRow;
})(_react.Component);
TableRow.propTypes = {
isSelected: _react.PropTypes.bool,
enableCellEdit: _react.PropTypes.bool,
onRowClick: _react.PropTypes.func,
onSelectRow: _react.PropTypes.func,
onRowMouseOut: _react.PropTypes.func,
onRowMouseOver: _react.PropTypes.func,
unselectableRow: _react.PropTypes.bool
};
TableRow.defaultProps = {
onRowClick: undefined
};
exports['default'] = TableRow;
module.exports = exports['default'];
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var TableColumn = (function (_Component) {
_inherits(TableColumn, _Component);
function TableColumn(props) {
var _this = this;
_classCallCheck(this, TableColumn);
_get(Object.getPrototypeOf(TableColumn.prototype), 'constructor', this).call(this, props);
this.handleCellEdit = function (e) {
if (_this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) {
if (document.selection && document.selection.empty) {
document.selection.empty();
} else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
}
}
_this.props.onEdit(e.currentTarget.parentElement.rowIndex + 1, e.currentTarget.cellIndex, e);
};
}
/* eslint no-unused-vars: [0, { "args": "after-used" }] */
_createClass(TableColumn, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
var children = this.props.children;
var shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || typeof children !== typeof nextProps.children || ('' + this.props.onEdit).toString() !== ('' + nextProps.onEdit).toString();
if (shouldUpdated) {
return shouldUpdated;
}
if (typeof children === 'object' && children !== null && children.props !== null) {
if (children.props.type === 'checkbox' || children.props.type === 'radio') {
shouldUpdated = shouldUpdated || children.props.type !== nextProps.children.props.type || children.props.checked !== nextProps.children.props.checked;
} else {
shouldUpdated = true;
}
} else {
shouldUpdated = shouldUpdated || children !== nextProps.children;
}
if (shouldUpdated) {
return shouldUpdated;
}
if (!(this.props.cellEdit && nextProps.cellEdit)) {
return false;
} else {
return shouldUpdated || this.props.cellEdit.mode !== nextProps.cellEdit.mode;
}
}
}, {
key: 'render',
value: function render() {
var tdStyle = {
textAlign: this.props.dataAlign,
display: this.props.hidden ? 'none' : null
};
var opts = {};
if (this.props.cellEdit) {
if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_CLICK) {
opts.onClick = this.handleCellEdit;
} else if (this.props.cellEdit.mode === _Const2['default'].CELL_EDIT_DBCLICK) {
opts.onDoubleClick = this.handleCellEdit;
}
}
return _react2['default'].createElement(
'td',
_extends({ style: tdStyle,
title: this.props.columnTitle,
className: this.props.className
}, opts),
this.props.children
);
}
}]);
return TableColumn;
})(_react.Component);
TableColumn.propTypes = {
dataAlign: _react.PropTypes.string,
hidden: _react.PropTypes.bool,
className: _react.PropTypes.string,
columnTitle: _react.PropTypes.string,
children: _react.PropTypes.node
};
TableColumn.defaultProps = {
dataAlign: 'left',
hidden: false,
className: ''
};
exports['default'] = TableColumn;
module.exports = exports['default'];
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Editor = __webpack_require__(12);
var _Editor2 = _interopRequireDefault(_Editor);
var _NotificationJs = __webpack_require__(13);
var _NotificationJs2 = _interopRequireDefault(_NotificationJs);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var TableEditColumn = (function (_Component) {
_inherits(TableEditColumn, _Component);
function TableEditColumn(props) {
var _this = this;
_classCallCheck(this, TableEditColumn);
_get(Object.getPrototypeOf(TableEditColumn.prototype), 'constructor', this).call(this, props);
this.handleKeyPress = function (e) {
if (e.keyCode === 13) {
// Pressed ENTER
var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
} else if (e.keyCode === 27) {
_this.props.completeEdit(null, _this.props.rowIndex, _this.props.colIndex);
} else if (e.type === 'click') {
// textarea click save button
var value = e.target.parentElement.firstChild.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
}
};
this.handleBlur = function (e) {
e.stopPropagation();
if (_this.props.blurToSave) {
var value = e.currentTarget.type === 'checkbox' ? _this._getCheckBoxValue(e) : e.currentTarget.value;
if (!_this.validator(value)) {
return;
}
_this.props.completeEdit(value, _this.props.rowIndex, _this.props.colIndex);
}
};
this.timeouteClear = 0;
this.state = {
shakeEditor: false
};
}
_createClass(TableEditColumn, [{
key: 'validator',
value: function validator(value) {
var ts = this;
if (ts.props.editable.validator) {
var valid = ts.props.editable.validator(value);
if (valid !== true) {
ts.refs.notifier.notice('error', valid, 'Pressed ESC can cancel');
var input = ts.refs.inputRef;
// animate input
ts.clearTimeout();
ts.setState({ shakeEditor: true });
ts.timeouteClear = setTimeout(function () {
ts.setState({ shakeEditor: false });
}, 300);
input.focus();
return false;
}
}
return true;
}
}, {
key: 'clearTimeout',
value: (function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
})(function () {
if (this.timeouteClear !== 0) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs.inputRef.focus();
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var editable = _props.editable;
var format = _props.format;
var children = _props.children;
var shakeEditor = this.state.shakeEditor;
var attr = {
ref: 'inputRef',
onKeyDown: this.handleKeyPress,
onBlur: this.handleBlur
};
// put placeholder if exist
editable.placeholder && (attr.placeholder = editable.placeholder);
var editorClass = (0, _classnames2['default'])({ 'animated': shakeEditor, 'shake': shakeEditor });
return _react2['default'].createElement(
'td',
{ ref: 'td', style: { position: 'relative' } },
(0, _Editor2['default'])(editable, attr, format, editorClass, children || ''),
_react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' })
);
}
}, {
key: '_getCheckBoxValue',
value: function _getCheckBoxValue(e) {
var value = '';
var values = e.currentTarget.value.split(':');
value = e.currentTarget.checked ? values[0] : values[1];
return value;
}
}]);
return TableEditColumn;
})(_react.Component);
TableEditColumn.propTypes = {
completeEdit: _react.PropTypes.func,
rowIndex: _react.PropTypes.number,
colIndex: _react.PropTypes.number,
blurToSave: _react.PropTypes.bool,
editable: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.object]),
format: _react.PropTypes.oneOfType([_react.PropTypes.bool, _react.PropTypes.func]),
children: _react.PropTypes.node
};
exports['default'] = TableEditColumn;
module.exports = exports['default'];
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var editor = function editor(editable, attr, format, editorClass, defaultValue, ignoreEditable) {
if (editable === true || editable === false && ignoreEditable || typeof editable === 'string') {
// simple declare
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (!editable) {
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
disabled: 'disabled',
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (editable && (editable.type === undefined || editable.type === null || editable.type.trim() === '')) {
var type = editable ? 'text' : editable;
return _react2['default'].createElement('input', _extends({}, attr, { type: type, defaultValue: defaultValue,
className: (editorClass || '') + ' form-control editor edit-text' }));
} else if (editable.type) {
// standard declare
// put style if exist
editable.style && (attr.style = editable.style);
// put class if exist
attr.className = (editorClass || '') + ' form-control editor edit-' + editable.type + (editable.className ? ' ' + editable.className : '');
if (editable.type === 'select') {
// process select input
var options = [];
var values = editable.options.values;
if (Array.isArray(values)) {
(function () {
// only can use arrray data for options
var rowValue = undefined;
options = values.map(function (d, i) {
rowValue = format ? format(d) : d;
return _react2['default'].createElement(
'option',
{ key: 'option' + i, value: d },
rowValue
);
});
})();
}
return _react2['default'].createElement(
'select',
_extends({}, attr, { defaultValue: defaultValue }),
options
);
} else if (editable.type === 'textarea') {
var _ret2 = (function () {
// process textarea input
// put other if exist
editable.cols && (attr.cols = editable.cols);
editable.rows && (attr.rows = editable.rows);
var saveBtn = undefined;
var keyUpHandler = attr.onKeyDown;
if (keyUpHandler) {
attr.onKeyDown = function (e) {
if (e.keyCode !== 13) {
// not Pressed ENTER
keyUpHandler(e);
}
};
saveBtn = _react2['default'].createElement(
'button',
{
className: 'btn btn-info btn-xs textarea-save-btn',
onClick: keyUpHandler },
'save'
);
}
return {
v: _react2['default'].createElement(
'div',
null,
_react2['default'].createElement('textarea', _extends({}, attr, { defaultValue: defaultValue })),
saveBtn
)
};
})();
if (typeof _ret2 === 'object') return _ret2.v;
} else if (editable.type === 'checkbox') {
var values = 'true:false';
if (editable.options && editable.options.values) {
// values = editable.options.values.split(':');
values = editable.options.values;
}
attr.className = attr.className.replace('form-control', '');
attr.className += ' checkbox pull-right';
var checked = defaultValue && defaultValue.toString() === values.split(':')[0] ? true : false;
return _react2['default'].createElement('input', _extends({}, attr, { type: 'checkbox',
value: values, defaultChecked: checked }));
} else {
// process other input type. as password,url,email...
return _react2['default'].createElement('input', _extends({}, attr, { type: 'text', defaultValue: defaultValue }));
}
}
// default return for other case of editable
return _react2['default'].createElement('input', _extends({}, attr, { type: 'text',
className: (editorClass || '') + ' form-control editor edit-text' }));
};
exports['default'] = editor;
module.exports = exports['default'];
/***/ },
/* 13 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactToastr = __webpack_require__(14);
var ToastrMessageFactory = _react2['default'].createFactory(_reactToastr.ToastMessage.animation);
var Notification = (function (_Component) {
_inherits(Notification, _Component);
function Notification() {
_classCallCheck(this, Notification);
_get(Object.getPrototypeOf(Notification.prototype), 'constructor', this).apply(this, arguments);
}
_createClass(Notification, [{
key: 'notice',
// allow type is success,info,warning,error
value: function notice(type, msg, title) {
this.refs.toastr[type](msg, title, {
mode: 'single',
timeOut: 5000,
extendedTimeOut: 1000,
showAnimation: 'animated bounceIn',
hideAnimation: 'animated bounceOut'
});
}
}, {
key: 'render',
value: function render() {
return _react2['default'].createElement(_reactToastr.ToastContainer, { ref: 'toastr',
toastMessageFactory: ToastrMessageFactory,
id: 'toast-container',
className: 'toast-top-right' });
}
}]);
return Notification;
})(_react.Component);
exports['default'] = Notification;
module.exports = exports['default'];
/***/ },
/* 14 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ToastMessage = exports.ToastContainer = undefined;
var _ToastContainer = __webpack_require__(15);
var _ToastContainer2 = _interopRequireDefault(_ToastContainer);
var _ToastMessage = __webpack_require__(22);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.ToastContainer = _ToastContainer2.default;
exports.ToastMessage = _ToastMessage2.default;
/***/ },
/* 15 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 ("value" in descriptor) 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
});
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(16);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _ToastMessage = __webpack_require__(22);
var _ToastMessage2 = _interopRequireDefault(_ToastMessage);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var ToastContainer = function (_Component) {
_inherits(ToastContainer, _Component);
function ToastContainer() {
var _Object$getPrototypeO;
var _temp, _this, _ret;
_classCallCheck(this, ToastContainer);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(ToastContainer)).call.apply(_Object$getPrototypeO, [this].concat(args))), _this), _this.state = {
toasts: [],
toastId: 0,
previousMessage: null
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(ToastContainer, [{
key: "error",
value: function error(message, title, optionsOverride) {
this._notify(this.props.toastType.error, message, title, optionsOverride);
}
}, {
key: "info",
value: function info(message, title, optionsOverride) {
this._notify(this.props.toastType.info, message, title, optionsOverride);
}
}, {
key: "success",
value: function success(message, title, optionsOverride) {
this._notify(this.props.toastType.success, message, title, optionsOverride);
}
}, {
key: "warning",
value: function warning(message, title, optionsOverride) {
this._notify(this.props.toastType.warning, message, title, optionsOverride);
}
}, {
key: "clear",
value: function clear() {
var _this2 = this;
Object.keys(this.refs).forEach(function (key) {
_this2.refs[key].hideToast(false);
});
}
}, {
key: "render",
value: function render() {
var _this3 = this;
return _react2.default.createElement(
"div",
_extends({}, this.props, { "aria-live": "polite", role: "alert" }),
this.state.toasts.map(function (toast) {
return _this3.props.toastMessageFactory(toast);
})
);
}
}, {
key: "_notify",
value: function _notify(type, message, title) {
var _this4 = this;
var optionsOverride = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3];
if (this.props.preventDuplicates) {
if (this.state.previousMessage === message) {
return;
}
}
var key = this.state.toastId++;
var toastId = key;
var newToast = (0, _reactAddonsUpdate2.default)(optionsOverride, {
$merge: {
type: type,
title: title,
message: message,
toastId: toastId,
key: key,
ref: "toasts__" + key,
handleOnClick: function handleOnClick(e) {
if ("function" === typeof optionsOverride.handleOnClick) {
optionsOverride.handleOnClick();
}
return _this4._handle_toast_on_click(e);
},
handleRemove: this._handle_toast_remove.bind(this)
}
});
var toastOperation = _defineProperty({}, "" + (this.props.newestOnTop ? "$unshift" : "$push"), [newToast]);
var nextState = (0, _reactAddonsUpdate2.default)(this.state, {
toasts: toastOperation,
previousMessage: { $set: message }
});
this.setState(nextState);
}
}, {
key: "_handle_toast_on_click",
value: function _handle_toast_on_click(event) {
this.props.onClick(event);
if (event.defaultPrevented) {
return;
}
event.preventDefault();
event.stopPropagation();
}
}, {
key: "_handle_toast_remove",
value: function _handle_toast_remove(toastId) {
var _this5 = this;
var operationName = "" + (this.props.newestOnTop ? "reduceRight" : "reduce");
this.state.toasts[operationName](function (found, toast, index) {
if (found || toast.toastId !== toastId) {
return false;
}
_this5.setState((0, _reactAddonsUpdate2.default)(_this5.state, {
toasts: { $splice: [[index, 1]] }
}));
return true;
}, false);
}
}]);
return ToastContainer;
}(_react.Component);
ToastContainer.defaultProps = {
toastType: {
error: "error",
info: "info",
success: "success",
warning: "warning"
},
id: "toast-container",
toastMessageFactory: _react2.default.createFactory(_ToastMessage2.default),
preventDuplicates: false,
newestOnTop: true,
onClick: function onClick() {}
};
exports.default = ToastContainer;
/***/ },
/* 16 */
/***/ function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(17);
/***/ },
/* 17 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule update
*/
/* global hasOwnProperty:true */
'use strict';
var assign = __webpack_require__(19);
var keyOf = __webpack_require__(20);
var invariant = __webpack_require__(21);
var hasOwnProperty = ({}).hasOwnProperty;
function shallowCopy(x) {
if (Array.isArray(x)) {
return x.concat();
} else if (x && typeof x === 'object') {
return assign(new x.constructor(), x);
} else {
return x;
}
}
var COMMAND_PUSH = keyOf({ $push: null });
var COMMAND_UNSHIFT = keyOf({ $unshift: null });
var COMMAND_SPLICE = keyOf({ $splice: null });
var COMMAND_SET = keyOf({ $set: null });
var COMMAND_MERGE = keyOf({ $merge: null });
var COMMAND_APPLY = keyOf({ $apply: null });
var ALL_COMMANDS_LIST = [COMMAND_PUSH, COMMAND_UNSHIFT, COMMAND_SPLICE, COMMAND_SET, COMMAND_MERGE, COMMAND_APPLY];
var ALL_COMMANDS_SET = {};
ALL_COMMANDS_LIST.forEach(function (command) {
ALL_COMMANDS_SET[command] = true;
});
function invariantArrayCase(value, spec, command) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected target of %s to be an array; got %s.', command, value) : invariant(false) : undefined;
var specValue = spec[command];
!Array.isArray(specValue) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array; got %s. ' + 'Did you forget to wrap your parameter in an array?', command, specValue) : invariant(false) : undefined;
}
function update(value, spec) {
!(typeof spec === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): You provided a key path to update() that did not contain one ' + 'of %s. Did you forget to include {%s: ...}?', ALL_COMMANDS_LIST.join(', '), COMMAND_SET) : invariant(false) : undefined;
if (hasOwnProperty.call(spec, COMMAND_SET)) {
!(Object.keys(spec).length === 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot have more than one key in an object with %s', COMMAND_SET) : invariant(false) : undefined;
return spec[COMMAND_SET];
}
var nextValue = shallowCopy(value);
if (hasOwnProperty.call(spec, COMMAND_MERGE)) {
var mergeObj = spec[COMMAND_MERGE];
!(mergeObj && typeof mergeObj === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a spec of type \'object\'; got %s', COMMAND_MERGE, mergeObj) : invariant(false) : undefined;
!(nextValue && typeof nextValue === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): %s expects a target of type \'object\'; got %s', COMMAND_MERGE, nextValue) : invariant(false) : undefined;
assign(nextValue, spec[COMMAND_MERGE]);
}
if (hasOwnProperty.call(spec, COMMAND_PUSH)) {
invariantArrayCase(value, spec, COMMAND_PUSH);
spec[COMMAND_PUSH].forEach(function (item) {
nextValue.push(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_UNSHIFT)) {
invariantArrayCase(value, spec, COMMAND_UNSHIFT);
spec[COMMAND_UNSHIFT].forEach(function (item) {
nextValue.unshift(item);
});
}
if (hasOwnProperty.call(spec, COMMAND_SPLICE)) {
!Array.isArray(value) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s target to be an array; got %s', COMMAND_SPLICE, value) : invariant(false) : undefined;
!Array.isArray(spec[COMMAND_SPLICE]) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
spec[COMMAND_SPLICE].forEach(function (args) {
!Array.isArray(args) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be an array of arrays; got %s. ' + 'Did you forget to wrap your parameters in an array?', COMMAND_SPLICE, spec[COMMAND_SPLICE]) : invariant(false) : undefined;
nextValue.splice.apply(nextValue, args);
});
}
if (hasOwnProperty.call(spec, COMMAND_APPLY)) {
!(typeof spec[COMMAND_APPLY] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'update(): expected spec of %s to be a function; got %s.', COMMAND_APPLY, spec[COMMAND_APPLY]) : invariant(false) : undefined;
nextValue = spec[COMMAND_APPLY](nextValue);
}
for (var k in spec) {
if (!(ALL_COMMANDS_SET.hasOwnProperty(k) && ALL_COMMANDS_SET[k])) {
nextValue[k] = update(value[k], spec[k]);
}
}
return nextValue;
}
module.exports = update;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 18 */
/***/ function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ },
/* 19 */
/***/ function(module, exports) {
/**
* Copyright 2014-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.
*
* @providesModule Object.assign
*/
// https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign
'use strict';
function assign(target, sources) {
if (target == null) {
throw new TypeError('Object.assign target cannot be null or undefined');
}
var to = Object(target);
var hasOwnProperty = Object.prototype.hasOwnProperty;
for (var nextIndex = 1; nextIndex < arguments.length; nextIndex++) {
var nextSource = arguments[nextIndex];
if (nextSource == null) {
continue;
}
var from = Object(nextSource);
// We don't currently support accessors nor proxies. Therefore this
// copy cannot throw. If we ever supported this then we must handle
// exceptions and side-effects. We don't support symbols so they won't
// be transferred.
for (var key in from) {
if (hasOwnProperty.call(from, key)) {
to[key] = from[key];
}
}
}
return to;
}
module.exports = assign;
/***/ },
/* 20 */
/***/ function(module, exports) {
/**
* 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.
*
* @providesModule keyOf
*/
/**
* Allows extraction of a minified key. Let's the build system minify keys
* without losing the ability to dynamically use key strings as values
* themselves. Pass in an object with a single key/val pair and it will return
* you the string key of that single record. Suppose you want to grab the
* value for a key 'className' inside of an object. Key/val minification may
* have aliased that key to be 'xa12'. keyOf({className: null}) will return
* 'xa12' in that case. Resolve keys you want to use once at startup time, then
* reuse those resolutions.
*/
"use strict";
var keyOf = function (oneKeyObj) {
var key;
for (key in oneKeyObj) {
if (!oneKeyObj.hasOwnProperty(key)) {
continue;
}
return key;
}
return null;
};
module.exports = keyOf;
/***/ },
/* 21 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 22 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.jQuery = exports.animation = undefined;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactAddonsUpdate = __webpack_require__(16);
var _reactAddonsUpdate2 = _interopRequireDefault(_reactAddonsUpdate);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _animationMixin = __webpack_require__(23);
var _animationMixin2 = _interopRequireDefault(_animationMixin);
var _jQueryMixin = __webpack_require__(28);
var _jQueryMixin2 = _interopRequireDefault(_jQueryMixin);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function noop() {}
var ToastMessageSpec = {
displayName: "ToastMessage",
getDefaultProps: function getDefaultProps() {
var iconClassNames = {
error: "toast-error",
info: "toast-info",
success: "toast-success",
warning: "toast-warning"
};
return {
className: "toast",
iconClassNames: iconClassNames,
titleClassName: "toast-title",
messageClassName: "toast-message",
tapToDismiss: true,
closeButton: false
};
},
handleOnClick: function handleOnClick(event) {
this.props.handleOnClick(event);
if (this.props.tapToDismiss) {
this.hideToast(true);
}
},
_handle_close_button_click: function _handle_close_button_click(event) {
event.stopPropagation();
this.hideToast(true);
},
_handle_remove: function _handle_remove() {
this.props.handleRemove(this.props.toastId);
},
_render_close_button: function _render_close_button() {
return this.props.closeButton ? _react2.default.createElement("button", {
className: "toast-close-button", role: "button",
onClick: this._handle_close_button_click,
dangerouslySetInnerHTML: { __html: "×" }
}) : false;
},
_render_title_element: function _render_title_element() {
return this.props.title ? _react2.default.createElement(
"div",
{ className: this.props.titleClassName },
this.props.title
) : false;
},
_render_message_element: function _render_message_element() {
return this.props.message ? _react2.default.createElement(
"div",
{ className: this.props.messageClassName },
this.props.message
) : false;
},
render: function render() {
var iconClassName = this.props.iconClassName || this.props.iconClassNames[this.props.type];
return _react2.default.createElement(
"div",
{
className: (0, _classnames2.default)(this.props.className, iconClassName),
style: this.props.style,
onClick: this.handleOnClick,
onMouseEnter: this.handleMouseEnter,
onMouseLeave: this.handleMouseLeave
},
this._render_close_button(),
this._render_title_element(),
this._render_message_element()
);
}
};
var animation = exports.animation = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.animation" },
mixins: { $set: [_animationMixin2.default] }
}));
var jQuery = exports.jQuery = _react2.default.createClass((0, _reactAddonsUpdate2.default)(ToastMessageSpec, {
displayName: { $set: "ToastMessage.jQuery" },
mixins: { $set: [_jQueryMixin2.default] }
}));
/*
* assign default noop functions
*/
ToastMessageSpec.handleMouseEnter = noop;
ToastMessageSpec.handleMouseLeave = noop;
ToastMessageSpec.hideToast = noop;
var ToastMessage = _react2.default.createClass(ToastMessageSpec);
ToastMessage.animation = animation;
ToastMessage.jQuery = jQuery;
exports.default = ToastMessage;
/***/ },
/* 23 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _CSSCore = __webpack_require__(24);
var _CSSCore2 = _interopRequireDefault(_CSSCore);
var _ReactTransitionEvents = __webpack_require__(26);
var _ReactTransitionEvents2 = _interopRequireDefault(_ReactTransitionEvents);
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var TICK = 17;
var toString = Object.prototype.toString;
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
transition: null, // some examples defined in index.scss (scale, fadeInOut, rotate)
showAnimation: "animated bounceIn", // or other animations from animate.css
hideAnimation: "animated bounceOut",
timeOut: 5000,
extendedTimeOut: 1000
};
},
componentWillMount: function componentWillMount() {
this.classNameQueue = [];
this.isHiding = false;
this.intervalId = null;
},
componentDidMount: function componentDidMount() {
var _this = this;
this._is_mounted = true;
this._show();
var node = _reactDom2.default.findDOMNode(this);
var onHideComplete = function onHideComplete() {
if (_this.isHiding) {
_this._set_is_hiding(false);
_ReactTransitionEvents2.default.removeEndEventListener(node, onHideComplete);
_this._handle_remove();
}
};
_ReactTransitionEvents2.default.addEndEventListener(node, onHideComplete);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
componentWillUnmount: function componentWillUnmount() {
this._is_mounted = false;
if (this.intervalId) {
clearTimeout(this.intervalId);
}
},
_set_transition: function _set_transition(hide) {
var animationType = hide ? "leave" : "enter";
var node = _reactDom2.default.findDOMNode(this);
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
_CSSCore2.default.removeClass(node, className);
_CSSCore2.default.removeClass(node, activeClassName);
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
_CSSCore2.default.addClass(node, className);
// Need to do this to actually trigger a transition.
this._queue_class(activeClassName);
},
_clear_transition: function _clear_transition(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animationType = hide ? "leave" : "enter";
var className = this.props.transition + "-" + animationType;
var activeClassName = className + "-active";
_CSSCore2.default.removeClass(node, className);
_CSSCore2.default.removeClass(node, activeClassName);
},
_set_animation: function _set_animation(hide) {
var node = _reactDom2.default.findDOMNode(this);
var animations = this._get_animation_classes(hide);
var endListener = function endListener(e) {
if (e && e.target !== node) {
return;
}
animations.forEach(function (anim) {
_CSSCore2.default.removeClass(node, anim);
});
_ReactTransitionEvents2.default.removeEndEventListener(node, endListener);
};
_ReactTransitionEvents2.default.addEndEventListener(node, endListener);
animations.forEach(function (anim) {
_CSSCore2.default.addClass(node, anim);
});
},
_get_animation_classes: function _get_animation_classes(hide) {
var animations = hide ? this.props.hideAnimation : this.props.showAnimation;
if ("[object Array]" === toString.call(animations)) {
return animations;
} else if ("string" === typeof animations) {
return animations.split(" ");
}
},
_clear_animation: function _clear_animation(hide) {
var _this2 = this;
var animations = this._get_animation_classes(hide);
animations.forEach(function (animation) {
_CSSCore2.default.removeClass(_reactDom2.default.findDOMNode(_this2), animation);
});
},
_queue_class: function _queue_class(className) {
this.classNameQueue.push(className);
if (!this.timeout) {
this.timeout = setTimeout(this._flush_class_name_queue, TICK);
}
},
_flush_class_name_queue: function _flush_class_name_queue() {
if (this._is_mounted) {
this.classNameQueue.forEach(_CSSCore2.default.addClass.bind(_CSSCore2.default, _reactDom2.default.findDOMNode(this)));
}
this.classNameQueue.length = 0;
this.timeout = null;
},
_show: function _show() {
if (this.props.transition) {
this._set_transition();
} else if (this.props.showAnimation) {
this._set_animation();
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.intervalId);
this._set_interval_id(null);
if (this.isHiding) {
this._set_is_hiding(false);
if (this.props.hideAnimation) {
this._clear_animation(true);
} else if (this.props.transition) {
this._clear_transition(true);
}
}
},
handleMouseLeave: function handleMouseLeave() {
if (!this.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.isHiding || this.intervalId === null && !override) {
return;
}
this._set_is_hiding(true);
if (this.props.transition) {
this._set_transition(true);
} else if (this.props.hideAnimation) {
this._set_animation(true);
} else {
this._handle_remove();
}
},
_set_interval_id: function _set_interval_id(intervalId) {
this.intervalId = intervalId;
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.isHiding = isHiding;
}
};
/***/ },
/* 24 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule CSSCore
* @typechecks
*/
'use strict';
var invariant = __webpack_require__(25);
/**
* The CSSCore module specifies the API (and implements most of the methods)
* that should be used when dealing with the display of elements (via their
* CSS classes and visibility on screen. It is an API focused on mutating the
* display and not reading it as no logical state should be encoded in the
* display of elements.
*/
var CSSCore = {
/**
* Adds the class passed in to the element if it doesn't already have it.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
addClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.addClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.add(className);
} else if (!CSSCore.hasClass(element, className)) {
element.className = element.className + ' ' + className;
}
}
return element;
},
/**
* Removes the class passed in from the element
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @return {DOMElement} the element passed in
*/
removeClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSSCore.removeClass takes only a single class name. "%s" contains ' + 'multiple classes.', className) : invariant(false) : undefined;
if (className) {
if (element.classList) {
element.classList.remove(className);
} else if (CSSCore.hasClass(element, className)) {
element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ') // multiple spaces to one
.replace(/^\s*|\s*$/g, ''); // trim the ends
}
}
return element;
},
/**
* Helper to add or remove a class from an element based on a condition.
*
* @param {DOMElement} element the element to set the class on
* @param {string} className the CSS className
* @param {*} bool condition to whether to add or remove the class
* @return {DOMElement} the element passed in
*/
conditionClass: function (element, className, bool) {
return (bool ? CSSCore.addClass : CSSCore.removeClass)(element, className);
},
/**
* Tests whether the element has the class specified.
*
* @param {DOMNode|DOMWindow} element the element to set the class on
* @param {string} className the CSS className
* @return {boolean} true if the element has the class, false if not
*/
hasClass: function (element, className) {
!!/\s/.test(className) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'CSS.hasClass takes only a single class name.') : invariant(false) : undefined;
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}
};
module.exports = CSSCore;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 25 */
/***/ function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process) {/**
* 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.
*
* @providesModule invariant
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
function invariant(condition, format, a, b, c, d, e, f) {
if (process.env.NODE_ENV !== 'production') {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.');
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(format.replace(/%s/g, function () {
return args[argIndex++];
}));
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
}
module.exports = invariant;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
/***/ },
/* 26 */
/***/ function(module, exports, __webpack_require__) {
/**
* 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.
*
* @providesModule ReactTransitionEvents
*/
'use strict';
var ExecutionEnvironment = __webpack_require__(27);
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function (endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function (node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function (endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
/***/ },
/* 27 */
/***/ function(module, exports) {
/**
* 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.
*
* @providesModule ExecutionEnvironment
*/
'use strict';
var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement);
/**
* Simple, lightweight module assisting with the detection and context of
* Worker. Helps avoid circular dependencies and allows code to reason about
* whether or not they are in a Worker, even if they never include the main
* `ReactWorker` dependency.
*/
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent),
canUseViewport: canUseDOM && !!window.screen,
isInWorker: !canUseDOM // For now, this is true - might change in the future.
};
module.exports = ExecutionEnvironment;
/***/ },
/* 28 */
/***/ function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _reactDom = __webpack_require__(5);
var _reactDom2 = _interopRequireDefault(_reactDom);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function call_show_method($node, props) {
$node[props.showMethod]({
duration: props.showDuration,
easing: props.showEasing
});
}
exports.default = {
getDefaultProps: function getDefaultProps() {
return {
style: {
display: "none" },
// effective $.hide()
showMethod: "fadeIn", // slideDown, and show are built into jQuery
showDuration: 300,
showEasing: "swing", // and linear are built into jQuery
hideMethod: "fadeOut",
hideDuration: 1000,
hideEasing: "swing",
//
timeOut: 5000,
extendedTimeOut: 1000
};
},
getInitialState: function getInitialState() {
return {
intervalId: null,
isHiding: false
};
},
componentDidMount: function componentDidMount() {
call_show_method(this._get_$_node(), this.props);
if (this.props.timeOut > 0) {
this._set_interval_id(setTimeout(this.hideToast, this.props.timeOut));
}
},
handleMouseEnter: function handleMouseEnter() {
clearTimeout(this.state.intervalId);
this._set_interval_id(null);
this._set_is_hiding(false);
call_show_method(this._get_$_node().stop(true, true), this.props);
},
handleMouseLeave: function handleMouseLeave() {
if (!this.state.isHiding && (this.props.timeOut > 0 || this.props.extendedTimeOut > 0)) {
this._set_interval_id(setTimeout(this.hideToast, this.props.extendedTimeOut));
}
},
hideToast: function hideToast(override) {
if (this.state.isHiding || this.state.intervalId === null && !override) {
return;
}
this.setState({ isHiding: true });
this._get_$_node()[this.props.hideMethod]({
duration: this.props.hideDuration,
easing: this.props.hideEasing,
complete: this._handle_remove
});
},
_get_$_node: function _get_$_node() {
/* eslint-disable no-undef */
return jQuery(_reactDom2.default.findDOMNode(this));
/* eslint-enable no-undef */
},
_set_interval_id: function _set_interval_id(intervalId) {
this.setState({
intervalId: intervalId
});
},
_set_is_hiding: function _set_is_hiding(isHiding) {
this.setState({
isHiding: isHiding
});
}
};
/***/ },
/* 29 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _PageButtonJs = __webpack_require__(30);
var _PageButtonJs2 = _interopRequireDefault(_PageButtonJs);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var PaginationList = (function (_Component) {
_inherits(PaginationList, _Component);
function PaginationList() {
var _this = this;
_classCallCheck(this, PaginationList);
_get(Object.getPrototypeOf(PaginationList.prototype), 'constructor', this).apply(this, arguments);
this.changePage = function (page) {
var _props = _this.props;
var pageStartIndex = _props.pageStartIndex;
var prePage = _props.prePage;
var currPage = _props.currPage;
var nextPage = _props.nextPage;
var lastPage = _props.lastPage;
var firstPage = _props.firstPage;
var sizePerPage = _props.sizePerPage;
if (page === prePage) {
page = currPage - 1 < pageStartIndex ? pageStartIndex : currPage - 1;
} else if (page === nextPage) {
page = currPage + 1 > _this.lastPage ? _this.lastPage : currPage + 1;
} else if (page === lastPage) {
page = _this.lastPage;
} else if (page === firstPage) {
page = pageStartIndex;
} else {
page = parseInt(page, 10);
}
if (page !== currPage) {
_this.props.changePage(page, sizePerPage);
}
};
this.changeSizePerPage = function (e) {
e.preventDefault();
var selectSize = parseInt(e.currentTarget.text, 10);
var currPage = _this.props.currPage;
if (selectSize !== _this.props.sizePerPage) {
_this.totalPages = Math.ceil(_this.props.dataSize / selectSize);
_this.lastPage = _this.props.pageStartIndex + _this.totalPages - 1;
if (currPage > _this.lastPage) currPage = _this.lastPage;
_this.props.changePage(currPage, selectSize);
if (_this.props.onSizePerPageList) {
_this.props.onSizePerPageList(selectSize);
}
}
};
}
_createClass(PaginationList, [{
key: 'render',
value: function render() {
var _this2 = this;
var _props2 = this.props;
var currPage = _props2.currPage;
var dataSize = _props2.dataSize;
var sizePerPage = _props2.sizePerPage;
var sizePerPageList = _props2.sizePerPageList;
var paginationShowsTotal = _props2.paginationShowsTotal;
var pageStartIndex = _props2.pageStartIndex;
var hideSizePerPage = _props2.hideSizePerPage;
this.totalPages = Math.ceil(dataSize / sizePerPage);
this.lastPage = this.props.pageStartIndex + this.totalPages - 1;
var pageBtns = this.makePage();
var pageListStyle = {
float: 'right',
// override the margin-top defined in .pagination class in bootstrap.
marginTop: '0px'
};
var sizePerPageOptions = sizePerPageList.map(function (_sizePerPage) {
return _react2['default'].createElement(
'li',
{ key: _sizePerPage, role: 'presentation' },
_react2['default'].createElement(
'a',
{ role: 'menuitem',
tabIndex: '-1', href: '#',
onClick: _this2.changeSizePerPage },
_sizePerPage
)
);
});
var offset = Math.abs(_Const2['default'].PAGE_START_INDEX - pageStartIndex);
var start = (currPage - pageStartIndex) * sizePerPage;
var to = Math.min(sizePerPage * (currPage + offset) - 1, dataSize);
var total = paginationShowsTotal ? _react2['default'].createElement(
'span',
null,
'Showing rows ',
start,
' to ',
to,
' of ',
dataSize
) : null;
if (typeof paginationShowsTotal === 'function') {
total = paginationShowsTotal(start, to, dataSize);
}
var dropDownStyle = {
visibility: hideSizePerPage ? 'hidden' : 'visible'
};
return _react2['default'].createElement(
'div',
{ className: 'row', style: { marginTop: 15 } },
sizePerPageList.length > 1 ? _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
total,
' ',
_react2['default'].createElement(
'span',
{ className: 'dropdown', style: dropDownStyle },
_react2['default'].createElement(
'button',
{ className: 'btn btn-default dropdown-toggle',
type: 'button', id: 'pageDropDown', 'data-toggle': 'dropdown',
'aria-expanded': 'true' },
sizePerPage,
_react2['default'].createElement(
'span',
null,
' ',
_react2['default'].createElement('span', { className: 'caret' })
)
),
_react2['default'].createElement(
'ul',
{ className: 'dropdown-menu', role: 'menu', 'aria-labelledby': 'pageDropDown' },
sizePerPageOptions
)
)
),
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
_react2['default'].createElement(
'ul',
{ className: 'pagination', style: pageListStyle },
pageBtns
)
)
) : _react2['default'].createElement(
'div',
null,
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
total
),
_react2['default'].createElement(
'div',
{ className: 'col-md-6' },
_react2['default'].createElement(
'ul',
{ className: 'pagination', style: pageListStyle },
pageBtns
)
)
)
);
}
}, {
key: 'makePage',
value: function makePage() {
var pages = this.getPages();
return pages.map(function (page) {
var isActive = page === this.props.currPage;
var disabled = false;
var hidden = false;
if (this.props.currPage === this.props.pageStartIndex && (page === this.props.firstPage || page === this.props.prePage)) {
disabled = true;
hidden = true;
}
if (this.props.currPage === this.lastPage && (page === this.props.nextPage || page === this.props.lastPage)) {
disabled = true;
hidden = true;
}
return _react2['default'].createElement(
_PageButtonJs2['default'],
{ key: page,
changePage: this.changePage,
active: isActive,
disable: disabled,
hidden: hidden },
page
);
}, this);
}
}, {
key: 'getPages',
value: function getPages() {
var pages = undefined;
var endPage = this.totalPages;
if (endPage <= 0) return [];
var startPage = Math.max(this.props.currPage - Math.floor(this.props.paginationSize / 2), this.props.pageStartIndex);
endPage = startPage + this.props.paginationSize - 1;
if (endPage > this.lastPage) {
endPage = this.lastPage;
startPage = endPage - this.props.paginationSize + 1;
}
if (startPage !== this.props.pageStartIndex && this.totalPages > this.props.paginationSize) {
pages = [this.props.firstPage, this.props.prePage];
} else if (this.totalPages > 1) {
pages = [this.props.prePage];
} else {
pages = [];
}
for (var i = startPage; i <= endPage; i++) {
if (i >= this.props.pageStartIndex) pages.push(i);
}
if (endPage < this.lastPage) {
pages.push(this.props.nextPage);
pages.push(this.props.lastPage);
} else if (endPage === this.lastPage && this.props.currPage !== this.lastPage) {
pages.push(this.props.nextPage);
}
return pages;
}
}]);
return PaginationList;
})(_react.Component);
PaginationList.propTypes = {
currPage: _react.PropTypes.number,
sizePerPage: _react.PropTypes.number,
dataSize: _react.PropTypes.number,
changePage: _react.PropTypes.func,
sizePerPageList: _react.PropTypes.array,
paginationShowsTotal: _react.PropTypes.bool,
paginationSize: _react.PropTypes.number,
remote: _react.PropTypes.bool,
onSizePerPageList: _react.PropTypes.func,
prePage: _react.PropTypes.string,
pageStartIndex: _react.PropTypes.number,
hideSizePerPage: _react.PropTypes.bool
};
PaginationList.defaultProps = {
sizePerPage: _Const2['default'].SIZE_PER_PAGE,
pageStartIndex: _Const2['default'].PAGE_START_INDEX
};
exports['default'] = PaginationList;
module.exports = exports['default'];
/***/ },
/* 30 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var PageButton = (function (_Component) {
_inherits(PageButton, _Component);
function PageButton(props) {
var _this = this;
_classCallCheck(this, PageButton);
_get(Object.getPrototypeOf(PageButton.prototype), 'constructor', this).call(this, props);
this.pageBtnClick = function (e) {
e.preventDefault();
_this.props.changePage(e.currentTarget.textContent);
};
}
_createClass(PageButton, [{
key: 'render',
value: function render() {
var classes = (0, _classnames2['default'])({
'active': this.props.active,
'disabled': this.props.disable,
'hidden': this.props.hidden
});
return _react2['default'].createElement(
'li',
{ className: classes },
_react2['default'].createElement(
'a',
{ href: '#', onClick: this.pageBtnClick },
this.props.children
)
);
}
}]);
return PageButton;
})(_react.Component);
PageButton.propTypes = {
changePage: _react.PropTypes.func,
active: _react.PropTypes.bool,
disable: _react.PropTypes.bool,
hidden: _react.PropTypes.bool,
children: _react.PropTypes.node
};
exports['default'] = PageButton;
module.exports = exports['default'];
/***/ },
/* 31 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _Editor = __webpack_require__(12);
var _Editor2 = _interopRequireDefault(_Editor);
var _NotificationJs = __webpack_require__(13);
var _NotificationJs2 = _interopRequireDefault(_NotificationJs);
var ToolBar = (function (_Component) {
_inherits(ToolBar, _Component);
_createClass(ToolBar, null, [{
key: 'modalSeq',
value: 0,
enumerable: true
}]);
function ToolBar(props) {
var _this = this,
_arguments2 = arguments;
_classCallCheck(this, ToolBar);
_get(Object.getPrototypeOf(ToolBar.prototype), 'constructor', this).call(this, props);
this.handleSaveBtnClick = function () {
var newObj = _this.checkAndParseForm();
if (!newObj) {
// validate errors
return;
}
var msg = _this.props.onAddRow(newObj);
if (msg) {
_this.refs.notifier.notice('error', msg, 'Pressed ESC can cancel');
_this.clearTimeout();
// shake form and hack prevent modal hide
_this.setState({
shakeEditor: true,
validateState: 'this is hack for prevent bootstrap modal hide'
});
// clear animate class
_this.timeouteClear = setTimeout(function () {
_this.setState({ shakeEditor: false });
}, 300);
} else {
// reset state and hide modal hide
_this.setState({
validateState: null,
shakeEditor: false
}, function () {
document.querySelector('.modal-backdrop').click();
document.querySelector('.' + _this.modalClassName).click();
});
// reset form
_this.refs.form.reset();
}
};
this.handleShowOnlyToggle = function () {
_this.setState({
showSelected: !_this.state.showSelected
});
_this.props.onShowOnlySelected();
};
this.handleDropRowBtnClick = function () {
_this.props.onDropRow();
};
this.handleDebounce = function (func, wait, immediate) {
var timeout = undefined;
return function () {
var later = function later() {
timeout = null;
if (!immediate) {
func.apply(_this, _arguments2);
}
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait || 0);
if (callNow) {
func.appy(_this, _arguments2);
}
};
};
this.handleKeyUp = function (event) {
event.persist();
_this.debounceCallback(event);
};
this.handleExportCSV = function () {
_this.props.onExportCSV();
};
this.handleClearBtnClick = function () {
_this.refs.seachInput.value = '';
_this.props.onSearch('');
};
this.timeouteClear = 0;
this.modalClassName;
this.state = {
isInsertRowTrigger: true,
validateState: null,
shakeEditor: false,
showSelected: false
};
}
_createClass(ToolBar, [{
key: 'componentWillMount',
value: function componentWillMount() {
var _this2 = this;
var delay = this.props.searchDelayTime ? this.props.searchDelayTime : 0;
this.debounceCallback = this.handleDebounce(function () {
_this2.props.onSearch(_this2.refs.seachInput.value);
}, delay);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
this.clearTimeout();
}
}, {
key: 'clearTimeout',
value: (function (_clearTimeout) {
function clearTimeout() {
return _clearTimeout.apply(this, arguments);
}
clearTimeout.toString = function () {
return _clearTimeout.toString();
};
return clearTimeout;
})(function () {
if (this.timeouteClear) {
clearTimeout(this.timeouteClear);
this.timeouteClear = 0;
}
})
}, {
key: 'checkAndParseForm',
value: function checkAndParseForm() {
var _this3 = this;
var newObj = {};
var validateState = {};
var isValid = true;
var tempValue = undefined;
var tempMsg = undefined;
this.props.columns.forEach(function (column, i) {
if (column.autoValue) {
// when you want same auto generate value and not allow edit, example ID field
var time = new Date().getTime();
tempValue = typeof column.autoValue === 'function' ? column.autoValue() : 'autovalue-' + time;
} else if (column.hiddenOnInsert) {
tempValue = '';
} else {
var dom = this.refs[column.field + i];
tempValue = dom.value;
if (column.editable && column.editable.type === 'checkbox') {
var values = tempValue.split(':');
tempValue = dom.checked ? values[0] : values[1];
}
if (column.editable && column.editable.validator) {
// process validate
tempMsg = column.editable.validator(tempValue);
if (tempMsg !== true) {
isValid = false;
validateState[column.field] = tempMsg;
}
}
}
newObj[column.field] = tempValue;
}, this);
if (isValid) {
return newObj;
} else {
this.clearTimeout();
// show error in form and shake it
this.setState({ validateState: validateState, shakeEditor: true });
// notifier error
this.refs.notifier.notice('error', 'Form validate errors, please checking!', 'Pressed ESC can cancel');
// clear animate class
this.timeouteClear = setTimeout(function () {
_this3.setState({ shakeEditor: false });
}, 300);
return null;
}
}
}, {
key: 'handleCloseBtn',
value: function handleCloseBtn() {
this.refs.warning.style.display = 'none';
}
}, {
key: 'render',
value: function render() {
this.modalClassName = 'bs-table-modal-sm' + ToolBar.modalSeq++;
var insertBtn = null;
var deleteBtn = null;
var exportCSV = null;
var showSelectedOnlyBtn = null;
if (this.props.enableInsert) {
insertBtn = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-info react-bs-table-add-btn',
'data-toggle': 'modal',
'data-target': '.' + this.modalClassName },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-plus' }),
' ',
this.props.insertText
);
}
if (this.props.enableDelete) {
deleteBtn = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-warning react-bs-table-del-btn',
'data-toggle': 'tooltip',
'data-placement': 'right',
title: 'Drop selected row',
onClick: this.handleDropRowBtnClick },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-trash' }),
' ',
this.props.deleteText
);
}
if (this.props.enableShowOnlySelected) {
showSelectedOnlyBtn = _react2['default'].createElement(
'button',
{ type: 'button',
onClick: this.handleShowOnlyToggle,
className: 'btn btn-primary',
'data-toggle': 'button',
'aria-pressed': 'false' },
this.state.showSelected ? _Const2['default'].SHOW_ALL : _Const2['default'].SHOW_ONLY_SELECT
);
}
if (this.props.enableExportCSV) {
exportCSV = _react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-success',
onClick: this.handleExportCSV },
_react2['default'].createElement('i', { className: 'glyphicon glyphicon-export' }),
this.props.exportCSVText
);
}
var searchTextInput = this.renderSearchPanel();
var modal = this.props.enableInsert ? this.renderInsertRowModal() : null;
return _react2['default'].createElement(
'div',
{ className: 'row' },
_react2['default'].createElement(
'div',
{ className: 'col-xs-12 col-sm-6 col-md-6 col-lg-8' },
_react2['default'].createElement(
'div',
{ className: 'btn-group btn-group-sm', role: 'group' },
exportCSV,
insertBtn,
deleteBtn,
showSelectedOnlyBtn
)
),
_react2['default'].createElement(
'div',
{ className: 'col-xs-12 col-sm-6 col-md-6 col-lg-4' },
searchTextInput
),
_react2['default'].createElement(_NotificationJs2['default'], { ref: 'notifier' }),
modal
);
}
}, {
key: 'renderSearchPanel',
value: function renderSearchPanel() {
if (this.props.enableSearch) {
var classNames = 'form-group form-group-sm react-bs-table-search-form';
var clearBtn = null;
if (this.props.clearSearch) {
clearBtn = _react2['default'].createElement(
'span',
{ className: 'input-group-btn' },
_react2['default'].createElement(
'button',
{
className: 'btn btn-default',
type: 'button',
onClick: this.handleClearBtnClick },
'Clear'
)
);
classNames += ' input-group input-group-sm';
}
return _react2['default'].createElement(
'div',
{ className: classNames },
_react2['default'].createElement('input', { ref: 'seachInput',
className: 'form-control',
type: 'text',
placeholder: this.props.searchPlaceholder ? this.props.searchPlaceholder : 'Search',
onKeyUp: this.handleKeyUp }),
clearBtn
);
} else {
return null;
}
}
}, {
key: 'renderInsertRowModal',
value: function renderInsertRowModal() {
var _this4 = this;
var validateState = this.state.validateState || {};
var shakeEditor = this.state.shakeEditor;
var inputField = this.props.columns.map(function (column, i) {
var editable = column.editable;
var format = column.format;
var field = column.field;
var name = column.name;
var autoValue = column.autoValue;
var hiddenOnInsert = column.hiddenOnInsert;
var attr = {
ref: field + i,
placeholder: editable.placeholder ? editable.placeholder : name
};
if (autoValue || hiddenOnInsert) {
// when you want same auto generate value
// and not allow edit, for example ID field
return null;
}
var error = validateState[field] ? _react2['default'].createElement(
'span',
{ className: 'help-block bg-danger' },
validateState[field]
) : null;
// let editor = Editor(editable,attr,format);
// if(editor.props.type && editor.props.type == 'checkbox'){
return _react2['default'].createElement(
'div',
{ className: 'form-group', key: field },
_react2['default'].createElement(
'label',
null,
name
),
(0, _Editor2['default'])(editable, attr, format, '', undefined, _this4.props.ignoreEditable),
error
);
});
var modalClass = (0, _classnames2['default'])('modal', 'fade', this.modalClassName, {
// hack prevent bootstrap modal hide by reRender
'in': shakeEditor || this.state.validateState
});
var dialogClass = (0, _classnames2['default'])('modal-dialog', 'modal-sm', {
'animated': shakeEditor,
'shake': shakeEditor
});
return _react2['default'].createElement(
'div',
{ ref: 'modal', className: modalClass, tabIndex: '-1', role: 'dialog' },
_react2['default'].createElement(
'div',
{ className: dialogClass },
_react2['default'].createElement(
'div',
{ className: 'modal-content' },
_react2['default'].createElement(
'div',
{ className: 'modal-header' },
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'close',
'data-dismiss': 'modal',
'aria-label': 'Close' },
_react2['default'].createElement(
'span',
{ 'aria-hidden': 'true' },
'×'
)
),
_react2['default'].createElement(
'h4',
{ className: 'modal-title' },
'New Record'
)
),
_react2['default'].createElement(
'div',
{ className: 'modal-body' },
_react2['default'].createElement(
'form',
{ ref: 'form' },
inputField
)
),
_react2['default'].createElement(
'div',
{ className: 'modal-footer' },
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-default',
'data-dismiss': 'modal' },
this.props.closeText
),
_react2['default'].createElement(
'button',
{ type: 'button',
className: 'btn btn-info',
onClick: this.handleSaveBtnClick },
this.props.saveText
)
)
)
)
);
}
}]);
return ToolBar;
})(_react.Component);
ToolBar.propTypes = {
onAddRow: _react.PropTypes.func,
onDropRow: _react.PropTypes.func,
onShowOnlySelected: _react.PropTypes.func,
enableInsert: _react.PropTypes.bool,
enableDelete: _react.PropTypes.bool,
enableSearch: _react.PropTypes.bool,
enableShowOnlySelected: _react.PropTypes.bool,
columns: _react.PropTypes.array,
searchPlaceholder: _react.PropTypes.string,
exportCSVText: _react.PropTypes.string,
insertText: _react.PropTypes.string,
deleteText: _react.PropTypes.string,
saveText: _react.PropTypes.string,
closeText: _react.PropTypes.string,
clearSearch: _react.PropTypes.bool,
ignoreEditable: _react.PropTypes.bool
};
ToolBar.defaultProps = {
enableInsert: false,
enableDelete: false,
enableSearch: false,
enableShowOnlySelected: false,
clearSearch: false,
ignoreEditable: false,
exportCSVText: _Const2['default'].EXPORT_CSV_TEXT,
insertText: _Const2['default'].INSERT_BTN_TEXT,
deleteText: _Const2['default'].DELETE_BTN_TEXT,
saveText: _Const2['default'].SAVE_BTN_TEXT,
closeText: _Const2['default'].CLOSE_BTN_TEXT
};
exports['default'] = ToolBar;
module.exports = exports['default'];
/***/ },
/* 32 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var TableFilter = (function (_Component) {
_inherits(TableFilter, _Component);
function TableFilter(props) {
var _this = this;
_classCallCheck(this, TableFilter);
_get(Object.getPrototypeOf(TableFilter.prototype), 'constructor', this).call(this, props);
this.handleKeyUp = function (e) {
var _e$currentTarget = e.currentTarget;
var value = _e$currentTarget.value;
var name = _e$currentTarget.name;
if (value.trim() === '') {
delete _this.filterObj[name];
} else {
_this.filterObj[name] = value;
}
_this.props.onFilter(_this.filterObj);
};
this.filterObj = {};
}
_createClass(TableFilter, [{
key: 'render',
value: function render() {
var _props = this.props;
var striped = _props.striped;
var condensed = _props.condensed;
var rowSelectType = _props.rowSelectType;
var columns = _props.columns;
var tableClasses = (0, _classnames2['default'])('table', {
'table-striped': striped,
'table-condensed': condensed
});
var selectRowHeader = null;
if (rowSelectType === _Const2['default'].ROW_SELECT_SINGLE || rowSelectType === _Const2['default'].ROW_SELECT_MULTI) {
var style = {
width: 35,
paddingLeft: 0,
paddingRight: 0
};
selectRowHeader = _react2['default'].createElement(
'th',
{ style: style, key: -1 },
'Filter'
);
}
var filterField = columns.map(function (column) {
var hidden = column.hidden;
var width = column.width;
var name = column.name;
var thStyle = {
display: hidden ? 'none' : null,
width: width
};
return _react2['default'].createElement(
'th',
{ key: name, style: thStyle },
_react2['default'].createElement(
'div',
{ className: 'th-inner table-header-column' },
_react2['default'].createElement('input', { size: '10', type: 'text',
placeholder: name, name: name, onKeyUp: this.handleKeyUp })
)
);
}, this);
return _react2['default'].createElement(
'table',
{ className: tableClasses, style: { marginTop: 5 } },
_react2['default'].createElement(
'thead',
null,
_react2['default'].createElement(
'tr',
{ style: { borderBottomStyle: 'hidden' } },
selectRowHeader,
filterField
)
)
);
}
}]);
return TableFilter;
})(_react.Component);
TableFilter.propTypes = {
columns: _react.PropTypes.array,
rowSelectType: _react.PropTypes.string,
onFilter: _react.PropTypes.func
};
exports['default'] = TableFilter;
module.exports = exports['default'];
/***/ },
/* 33 */
/***/ function(module, exports, __webpack_require__) {
/* eslint no-nested-ternary: 0 */
/* eslint guard-for-in: 0 */
/* eslint no-console: 0 */
/* eslint eqeqeq: 0 */
/* eslint one-var: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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; }; })();
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
function _sort(arr, sortField, order, sortFunc, sortFuncExtraData) {
order = order.toLowerCase();
var isDesc = order === _Const2['default'].SORT_DESC;
arr.sort(function (a, b) {
if (sortFunc) {
return sortFunc(a, b, order, sortField, sortFuncExtraData);
} else {
var valueA = a[sortField] === null ? '' : a[sortField];
var valueB = b[sortField] === null ? '' : b[sortField];
if (isDesc) {
if (typeof valueB === 'string') {
return valueB.localeCompare(valueA);
} else {
return valueA > valueB ? -1 : valueA < valueB ? 1 : 0;
}
} else {
if (typeof valueA === 'string') {
return valueA.localeCompare(valueB);
} else {
return valueA < valueB ? -1 : valueA > valueB ? 1 : 0;
}
}
}
});
return arr;
}
var TableDataStore = (function () {
function TableDataStore(data) {
_classCallCheck(this, TableDataStore);
this.data = data;
this.colInfos = null;
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
this.searchText = null;
this.sortObj = null;
this.pageObj = {};
this.selected = [];
this.multiColumnSearch = false;
this.showOnlySelected = false;
this.remote = false; // remote data
}
_createClass(TableDataStore, [{
key: 'setProps',
value: function setProps(props) {
this.keyField = props.keyField;
this.enablePagination = props.isPagination;
this.colInfos = props.colInfos;
this.remote = props.remote;
this.multiColumnSearch = props.multiColumnSearch;
}
}, {
key: 'setData',
value: function setData(data) {
this.data = data;
if (this.remote) {
return;
}
this._refresh(true);
}
}, {
key: 'getColInfos',
value: function getColInfos() {
return this.colInfos;
}
}, {
key: 'getSortInfo',
value: function getSortInfo() {
return this.sortObj;
}
}, {
key: 'setSortInfo',
value: function setSortInfo(order, sortField) {
this.sortObj = {
order: order,
sortField: sortField
};
}
}, {
key: 'setSelectedRowKey',
value: function setSelectedRowKey(selectedRowKeys) {
this.selected = selectedRowKeys;
}
}, {
key: 'getRowByKey',
value: function getRowByKey(keys) {
var _this = this;
return keys.map(function (key) {
var result = _this.data.filter(function (d) {
return d[_this.keyField] === key;
});
if (result.length !== 0) return result[0];
});
}
}, {
key: 'getSelectedRowKeys',
value: function getSelectedRowKeys() {
return this.selected;
}
}, {
key: 'getCurrentDisplayData',
value: function getCurrentDisplayData() {
if (this.isOnFilter) return this.filteredData;else return this.data;
}
}, {
key: '_refresh',
value: function _refresh(skipSorting) {
if (this.isOnFilter) {
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
if (!skipSorting && this.sortObj) {
this.sort(this.sortObj.order, this.sortObj.sortField);
}
}
}, {
key: 'ignoreNonSelected',
value: function ignoreNonSelected() {
var _this2 = this;
this.showOnlySelected = !this.showOnlySelected;
if (this.showOnlySelected) {
this.isOnFilter = true;
this.filteredData = this.data.filter(function (row) {
var result = _this2.selected.find(function (x) {
return row[_this2.keyField] === x;
});
return typeof result !== 'undefined' ? true : false;
});
} else {
this.isOnFilter = false;
}
}
}, {
key: 'sort',
value: function sort(order, sortField) {
this.setSortInfo(order, sortField);
var currentDisplayData = this.getCurrentDisplayData();
if (!this.colInfos[sortField]) return this;
var _colInfos$sortField = this.colInfos[sortField];
var sortFunc = _colInfos$sortField.sortFunc;
var sortFuncExtraData = _colInfos$sortField.sortFuncExtraData;
currentDisplayData = _sort(currentDisplayData, sortField, order, sortFunc, sortFuncExtraData);
return this;
}
}, {
key: 'page',
value: function page(_page, sizePerPage) {
this.pageObj.end = _page * sizePerPage - 1;
this.pageObj.start = this.pageObj.end - (sizePerPage - 1);
return this;
}
}, {
key: 'edit',
value: function edit(newVal, rowIndex, fieldName) {
var currentDisplayData = this.getCurrentDisplayData();
var rowKeyCache = undefined;
if (!this.enablePagination) {
currentDisplayData[rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[rowIndex][this.keyField];
} else {
currentDisplayData[this.pageObj.start + rowIndex][fieldName] = newVal;
rowKeyCache = currentDisplayData[this.pageObj.start + rowIndex][this.keyField];
}
if (this.isOnFilter) {
this.data.forEach(function (row) {
if (row[this.keyField] === rowKeyCache) {
row[fieldName] = newVal;
}
}, this);
if (this.filterObj !== null) this.filter(this.filterObj);
if (this.searchText !== null) this.search(this.searchText);
}
return this;
}
}, {
key: 'addAtBegin',
value: function addAtBegin(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw this.keyField + ' can\'t be empty value.';
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw this.keyField + ' ' + newObj[this.keyField] + ' already exists';
}
}, this);
currentDisplayData.unshift(newObj);
if (this.isOnFilter) {
this.data.unshift(newObj);
}
this._refresh(false);
}
}, {
key: 'add',
value: function add(newObj) {
if (!newObj[this.keyField] || newObj[this.keyField].toString() === '') {
throw this.keyField + ' can\'t be empty value.';
}
var currentDisplayData = this.getCurrentDisplayData();
currentDisplayData.forEach(function (row) {
if (row[this.keyField].toString() === newObj[this.keyField].toString()) {
throw this.keyField + ' ' + newObj[this.keyField] + ' already exists';
}
}, this);
currentDisplayData.push(newObj);
if (this.isOnFilter) {
this.data.push(newObj);
}
this._refresh(false);
}
}, {
key: 'remove',
value: function remove(rowKey) {
var _this3 = this;
var currentDisplayData = this.getCurrentDisplayData();
var result = currentDisplayData.filter(function (row) {
return rowKey.indexOf(row[_this3.keyField]) === -1;
});
if (this.isOnFilter) {
this.data = this.data.filter(function (row) {
return rowKey.indexOf(row[_this3.keyField]) === -1;
});
this.filteredData = result;
} else {
this.data = result;
}
}
}, {
key: 'filter',
value: function filter(filterObj) {
if (Object.keys(filterObj).length === 0) {
this.filteredData = null;
this.isOnFilter = false;
this.filterObj = null;
if (this.searchText) this._search(this.data);
} else {
var source = this.data;
this.filterObj = filterObj;
if (this.searchText) {
this._search(source);
source = this.filteredData;
}
this._filter(source);
}
}
}, {
key: 'filterNumber',
value: function filterNumber(targetVal, filterVal, comparator) {
var valid = true;
switch (comparator) {
case '=':
{
if (targetVal != filterVal) {
valid = false;
}
break;
}
case '>':
{
if (targetVal <= filterVal) {
valid = false;
}
break;
}
case '>=':
{
if (targetVal < filterVal) {
valid = false;
}
break;
}
case '<':
{
if (targetVal >= filterVal) {
valid = false;
}
break;
}
case '<=':
{
if (targetVal > filterVal) {
valid = false;
}
break;
}
case '!=':
{
if (targetVal == filterVal) {
valid = false;
}
break;
}
default:
{
console.error('Number comparator provided is not supported');
break;
}
}
return valid;
}
}, {
key: 'filterDate',
value: function filterDate(targetVal, filterVal, comparator) {
// if (!targetVal) {
// return false;
// }
// return (targetVal.getDate() === filterVal.getDate() &&
// targetVal.getMonth() === filterVal.getMonth() &&
// targetVal.getFullYear() === filterVal.getFullYear());
var valid = true;
switch (comparator) {
case '=':
{
if (targetVal != filterVal) {
valid = false;
}
break;
}
case '>':
{
if (targetVal <= filterVal) {
valid = false;
}
break;
}
case '>=':
{
// console.log(targetVal);
// console.log(filterVal);
// console.log(filterVal.getDate());
if (targetVal < filterVal) {
valid = false;
}
break;
}
case '<':
{
if (targetVal >= filterVal) {
valid = false;
}
break;
}
case '<=':
{
if (targetVal > filterVal) {
valid = false;
}
break;
}
case '!=':
{
if (targetVal == filterVal) {
valid = false;
}
break;
}
default:
{
console.error('Date comparator provided is not supported');
break;
}
}
return valid;
}
}, {
key: 'filterRegex',
value: function filterRegex(targetVal, filterVal) {
try {
return new RegExp(filterVal, 'i').test(targetVal);
} catch (e) {
console.error('Invalid regular expression');
return true;
}
}
}, {
key: 'filterCustom',
value: function filterCustom(targetVal, filterVal, callbackInfo) {
if (callbackInfo !== null && typeof callbackInfo === 'object') {
return callbackInfo.callback(targetVal, callbackInfo.callbackParameters);
}
return this.filterText(targetVal, filterVal);
}
}, {
key: 'filterText',
value: function filterText(targetVal, filterVal) {
if (targetVal.toString().toLowerCase().indexOf(filterVal) === -1) {
return false;
}
return true;
}
/* General search function
* It will search for the text if the input includes that text;
*/
}, {
key: 'search',
value: function search(searchText) {
if (searchText.trim() === '') {
this.filteredData = null;
this.isOnFilter = false;
this.searchText = null;
if (this.filterObj) this._filter(this.data);
} else {
var source = this.data;
this.searchText = searchText;
if (this.filterObj) {
this._filter(source);
source = this.filteredData;
}
this._search(source);
}
}
}, {
key: '_filter',
value: function _filter(source) {
var _this4 = this;
var filterObj = this.filterObj;
this.filteredData = source.filter(function (row) {
var valid = true;
var filterVal = undefined;
for (var key in filterObj) {
var targetVal = row[key];
if (targetVal === null || targetVal === undefined) {
targetVal = '';
}
switch (filterObj[key].type) {
case _Const2['default'].FILTER_TYPE.NUMBER:
{
filterVal = filterObj[key].value.number;
break;
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
filterVal = typeof filterObj[key].value === 'object' ? undefined : typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
break;
}
case _Const2['default'].FILTER_TYPE.DATE:
{
filterVal = filterObj[key].value.date;
break;
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
filterVal = filterObj[key].value;
break;
}
default:
{
filterVal = typeof filterObj[key].value === 'string' ? filterObj[key].value.toLowerCase() : filterObj[key].value;
if (filterVal === undefined) {
// Support old filter
filterVal = filterObj[key].toLowerCase();
}
break;
}
}
var format = undefined,
filterFormatted = undefined,
formatExtraData = undefined;
if (_this4.colInfos[key]) {
format = _this4.colInfos[key].format;
filterFormatted = _this4.colInfos[key].filterFormatted;
formatExtraData = _this4.colInfos[key].formatExtraData;
if (filterFormatted && format) {
targetVal = format(row[key], row, formatExtraData);
}
}
switch (filterObj[key].type) {
case _Const2['default'].FILTER_TYPE.NUMBER:
{
valid = _this4.filterNumber(targetVal, filterVal, filterObj[key].value.comparator);
break;
}
case _Const2['default'].FILTER_TYPE.DATE:
{
valid = _this4.filterDate(targetVal, filterVal, filterObj[key].value.comparator);
break;
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
valid = _this4.filterRegex(targetVal, filterVal);
break;
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
valid = _this4.filterCustom(targetVal, filterVal, filterObj[key].value);
break;
}
default:
{
if (filterObj[key].type === _Const2['default'].FILTER_TYPE.SELECT && filterFormatted && filterFormatted && format) {
filterVal = format(filterVal, row, formatExtraData);
}
valid = _this4.filterText(targetVal, filterVal);
break;
}
}
if (!valid) {
break;
}
}
return valid;
});
this.isOnFilter = true;
}
}, {
key: '_search',
value: function _search(source) {
var _this5 = this;
var searchTextArray = [];
if (this.multiColumnSearch) {
searchTextArray = this.searchText.split(' ');
} else {
searchTextArray.push(this.searchText);
}
this.filteredData = source.filter(function (row) {
var keys = Object.keys(row);
var valid = false;
// for loops are ugly, but performance matters here.
// And you cant break from a forEach.
// http://jsperf.com/for-vs-foreach/66
for (var i = 0, keysLength = keys.length; i < keysLength; i++) {
var key = keys[i];
if (_this5.colInfos[key] && row[key]) {
var _colInfos$key = _this5.colInfos[key];
var format = _colInfos$key.format;
var filterFormatted = _colInfos$key.filterFormatted;
var formatExtraData = _colInfos$key.formatExtraData;
var searchable = _colInfos$key.searchable;
var targetVal = row[key];
if (searchable) {
if (filterFormatted && format) {
targetVal = format(targetVal, row, formatExtraData);
}
for (var j = 0, textLength = searchTextArray.length; j < textLength; j++) {
var filterVal = searchTextArray[j].toLowerCase();
if (targetVal.toString().toLowerCase().indexOf(filterVal) !== -1) {
valid = true;
break;
}
}
}
}
}
return valid;
});
this.isOnFilter = true;
}
}, {
key: 'getDataIgnoringPagination',
value: function getDataIgnoringPagination() {
return this.getCurrentDisplayData();
}
}, {
key: 'get',
value: function get() {
var _data = this.getCurrentDisplayData();
if (_data.length === 0) return _data;
if (this.remote || !this.enablePagination) {
return _data;
} else {
var result = [];
for (var i = this.pageObj.start; i <= this.pageObj.end; i++) {
result.push(_data[i]);
if (i + 1 === _data.length) break;
}
return result;
}
}
}, {
key: 'getKeyField',
value: function getKeyField() {
return this.keyField;
}
}, {
key: 'getDataNum',
value: function getDataNum() {
return this.getCurrentDisplayData().length;
}
}, {
key: 'isChangedPage',
value: function isChangedPage() {
return this.pageObj.start && this.pageObj.end ? true : false;
}
}, {
key: 'isEmpty',
value: function isEmpty() {
return this.data.length === 0 || this.data === null || this.data === undefined;
}
}, {
key: 'getAllRowkey',
value: function getAllRowkey() {
var _this6 = this;
return this.data.map(function (row) {
return row[_this6.keyField];
});
}
}]);
return TableDataStore;
})();
exports.TableDataStore = TableDataStore;
/***/ },
/* 34 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
exports['default'] = {
renderReactSortCaret: function renderReactSortCaret(order) {
var orderClass = (0, _classnames2['default'])('order', {
'dropup': order === _Const2['default'].SORT_ASC
});
return _react2['default'].createElement(
'span',
{ className: orderClass },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 5px' } })
);
},
getScrollBarWidth: function getScrollBarWidth() {
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.appendChild(outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 === w2) w2 = outer.clientWidth;
document.body.removeChild(outer);
return w1 - w2;
},
canUseDOM: function canUseDOM() {
return typeof window !== 'undefined' && typeof window.document !== 'undefined';
}
};
module.exports = exports['default'];
/***/ },
/* 35 */
/***/ function(module, exports, __webpack_require__) {
/* eslint block-scoped-var: 0 */
/* eslint vars-on-top: 0 */
/* eslint no-var: 0 */
/* eslint no-unused-vars: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
if (_util2['default'].canUseDOM()) {
var filesaver = __webpack_require__(36);
var saveAs = filesaver.saveAs;
}
function toString(data, keys) {
var dataString = '';
if (data.length === 0) return dataString;
dataString += keys.map(function (x) {
return x.header;
}).join(',') + '\n';
data.map(function (row) {
keys.map(function (col, i) {
var field = col.field;
var format = col.format;
var value = typeof format !== 'undefined' ? format(row[field]) : row[field];
var cell = typeof value !== 'undefined' ? '"' + value + '"' : '';
dataString += cell;
if (i + 1 < keys.length) dataString += ',';
});
dataString += '\n';
});
return dataString;
}
var exportCSV = function exportCSV(data, keys, filename) {
var dataString = toString(data, keys);
if (typeof window !== 'undefined') {
saveAs(new Blob([dataString], { type: 'text/plain;charset=utf-8' }), filename);
}
};
exports['default'] = exportCSV;
module.exports = exports['default'];
/***/ },
/* 36 */
/***/ function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/* FileSaver.js
* A saveAs() FileSaver implementation.
* 1.1.20151003
*
* By Eli Grey, http://eligrey.com
* License: MIT
* See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
*/
/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */
/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */
"use strict";
var saveAs = saveAs || (function (view) {
"use strict";
// IE <10 is explicitly unsupported
if (typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
return;
}
var doc = view.document,
// only get URL when necessary in case Blob.js hasn't overridden it yet
get_URL = function get_URL() {
return view.URL || view.webkitURL || view;
},
save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a"),
can_use_save_link = ("download" in save_link),
click = function click(node) {
var event = new MouseEvent("click");
node.dispatchEvent(event);
},
is_safari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent),
webkit_req_fs = view.webkitRequestFileSystem,
req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem,
throw_outside = function throw_outside(ex) {
(view.setImmediate || view.setTimeout)(function () {
throw ex;
}, 0);
},
force_saveable_type = "application/octet-stream",
fs_min_size = 0,
// See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and
// https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047
// for the reasoning behind the timeout and revocation flow
arbitrary_revoke_timeout = 500,
// in ms
revoke = function revoke(file) {
var revoker = function revoker() {
if (typeof file === "string") {
// file is an object URL
get_URL().revokeObjectURL(file);
} else {
// file is a File
file.remove();
}
};
if (view.chrome) {
revoker();
} else {
setTimeout(revoker, arbitrary_revoke_timeout);
}
},
dispatch = function dispatch(filesaver, event_types, event) {
event_types = [].concat(event_types);
var i = event_types.length;
while (i--) {
var listener = filesaver["on" + event_types[i]];
if (typeof listener === "function") {
try {
listener.call(filesaver, event || filesaver);
} catch (ex) {
throw_outside(ex);
}
}
}
},
auto_bom = function auto_bom(blob) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob(["", blob], { type: blob.type });
}
return blob;
},
FileSaver = function FileSaver(blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
// First try a.download, then web filesystem, then object URLs
var filesaver = this,
type = blob.type,
blob_changed = false,
object_url,
target_view,
dispatch_all = function dispatch_all() {
dispatch(filesaver, "writestart progress write writeend".split(" "));
},
// on any filesys errors revert to saving with object URLs
fs_error = function fs_error() {
if (target_view && is_safari && typeof FileReader !== "undefined") {
// Safari doesn't allow downloading of blob urls
var reader = new FileReader();
reader.onloadend = function () {
var base64Data = reader.result;
target_view.location.href = "data:attachment/file" + base64Data.slice(base64Data.search(/[,;]/));
filesaver.readyState = filesaver.DONE;
dispatch_all();
};
reader.readAsDataURL(blob);
filesaver.readyState = filesaver.INIT;
return;
}
// don't create more object URLs than needed
if (blob_changed || !object_url) {
object_url = get_URL().createObjectURL(blob);
}
if (target_view) {
target_view.location.href = object_url;
} else {
var new_tab = view.open(object_url, "_blank");
if (new_tab == undefined && is_safari) {
//Apple do not allow window.open, see http://bit.ly/1kZffRI
view.location.href = object_url;
}
}
filesaver.readyState = filesaver.DONE;
dispatch_all();
revoke(object_url);
},
abortable = function abortable(func) {
return function () {
if (filesaver.readyState !== filesaver.DONE) {
return func.apply(this, arguments);
}
};
},
create_if_not_found = { create: true, exclusive: false },
slice;
filesaver.readyState = filesaver.INIT;
if (!name) {
name = "download";
}
if (can_use_save_link) {
object_url = get_URL().createObjectURL(blob);
save_link.href = object_url;
save_link.download = name;
setTimeout(function () {
click(save_link);
dispatch_all();
revoke(object_url);
filesaver.readyState = filesaver.DONE;
});
return;
}
// Object and web filesystem URLs have a problem saving in Google Chrome when
// viewed in a tab, so I force save with application/octet-stream
// http://code.google.com/p/chromium/issues/detail?id=91158
// Update: Google errantly closed 91158, I submitted it again:
// https://code.google.com/p/chromium/issues/detail?id=389642
if (view.chrome && type && type !== force_saveable_type) {
slice = blob.slice || blob.webkitSlice;
blob = slice.call(blob, 0, blob.size, force_saveable_type);
blob_changed = true;
}
// Since I can't be sure that the guessed media type will trigger a download
// in WebKit, I append .download to the filename.
// https://bugs.webkit.org/show_bug.cgi?id=65440
if (webkit_req_fs && name !== "download") {
name += ".download";
}
if (type === force_saveable_type || webkit_req_fs) {
target_view = view;
}
if (!req_fs) {
fs_error();
return;
}
fs_min_size += blob.size;
req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {
fs.root.getDirectory("saved", create_if_not_found, abortable(function (dir) {
var save = function save() {
dir.getFile(name, create_if_not_found, abortable(function (file) {
file.createWriter(abortable(function (writer) {
writer.onwriteend = function (event) {
target_view.location.href = file.toURL();
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "writeend", event);
revoke(file);
};
writer.onerror = function () {
var error = writer.error;
if (error.code !== error.ABORT_ERR) {
fs_error();
}
};
"writestart progress write abort".split(" ").forEach(function (event) {
writer["on" + event] = filesaver["on" + event];
});
writer.write(blob);
filesaver.abort = function () {
writer.abort();
filesaver.readyState = filesaver.DONE;
};
filesaver.readyState = filesaver.WRITING;
}), fs_error);
}), fs_error);
};
dir.getFile(name, { create: false }, abortable(function (file) {
// delete file if it already exists
file.remove();
save();
}), abortable(function (ex) {
if (ex.code === ex.NOT_FOUND_ERR) {
save();
} else {
fs_error();
}
}));
}), fs_error);
}), fs_error);
},
FS_proto = FileSaver.prototype,
saveAs = function saveAs(blob, name, no_auto_bom) {
return new FileSaver(blob, name, no_auto_bom);
};
// IE 10+ (native saveAs)
if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
return function (blob, name, no_auto_bom) {
if (!no_auto_bom) {
blob = auto_bom(blob);
}
return navigator.msSaveOrOpenBlob(blob, name || "download");
};
}
FS_proto.abort = function () {
var filesaver = this;
filesaver.readyState = filesaver.DONE;
dispatch(filesaver, "abort");
};
FS_proto.readyState = FS_proto.INIT = 0;
FS_proto.WRITING = 1;
FS_proto.DONE = 2;
FS_proto.error = FS_proto.onwritestart = FS_proto.onprogress = FS_proto.onwrite = FS_proto.onabort = FS_proto.onerror = FS_proto.onwriteend = null;
return saveAs;
})(typeof self !== "undefined" && self || typeof window !== "undefined" && window || undefined.content);
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window
if (typeof module !== "undefined" && module.exports) {
module.exports.saveAs = saveAs;
} else if ("function" !== "undefined" && __webpack_require__(37) !== null && __webpack_require__(38) != null) {
!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () {
return saveAs;
}.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
/***/ },
/* 37 */
/***/ function(module, exports) {
module.exports = function() { throw new Error("define cannot be used indirect"); };
/***/ },
/* 38 */
/***/ function(module, exports) {
/* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__;
/* WEBPACK VAR INJECTION */}.call(exports, {}))
/***/ },
/* 39 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _events = __webpack_require__(40);
var Filter = (function (_EventEmitter) {
_inherits(Filter, _EventEmitter);
function Filter(data) {
_classCallCheck(this, Filter);
_get(Object.getPrototypeOf(Filter.prototype), 'constructor', this).call(this, data);
this.currentFilter = {};
}
_createClass(Filter, [{
key: 'handleFilter',
value: function handleFilter(dataField, value, type) {
var filterType = type || _Const2['default'].FILTER_TYPE.CUSTOM;
if (value !== null && typeof value === 'object') {
// value of the filter is an object
var hasValue = true;
for (var prop in value) {
if (!value[prop] || value[prop] === '') {
hasValue = false;
break;
}
}
// if one of the object properties is undefined or empty, we remove the filter
if (hasValue) {
this.currentFilter[dataField] = { value: value, type: filterType };
} else {
delete this.currentFilter[dataField];
}
} else if (!value || value.trim() === '') {
delete this.currentFilter[dataField];
} else {
this.currentFilter[dataField] = { value: value.trim(), type: filterType };
}
this.emit('onFilterChange', this.currentFilter);
}
}]);
return Filter;
})(_events.EventEmitter);
exports.Filter = Filter;
/***/ },
/* 40 */
/***/ function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
}
throw TypeError('Uncaught, unspecified "error" event.');
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ },
/* 41 */
/***/ function(module, exports, __webpack_require__) {
/* eslint default-case: 0 */
/* eslint guard-for-in: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var _util = __webpack_require__(34);
var _util2 = _interopRequireDefault(_util);
var _filtersDate = __webpack_require__(42);
var _filtersDate2 = _interopRequireDefault(_filtersDate);
var _filtersText = __webpack_require__(43);
var _filtersText2 = _interopRequireDefault(_filtersText);
var _filtersRegex = __webpack_require__(44);
var _filtersRegex2 = _interopRequireDefault(_filtersRegex);
var _filtersSelect = __webpack_require__(45);
var _filtersSelect2 = _interopRequireDefault(_filtersSelect);
var _filtersNumber = __webpack_require__(46);
var _filtersNumber2 = _interopRequireDefault(_filtersNumber);
var TableHeaderColumn = (function (_Component) {
_inherits(TableHeaderColumn, _Component);
function TableHeaderColumn(props) {
var _this = this;
_classCallCheck(this, TableHeaderColumn);
_get(Object.getPrototypeOf(TableHeaderColumn.prototype), 'constructor', this).call(this, props);
this.handleColumnClick = function () {
if (!_this.props.dataSort) return;
var order = _this.props.sort === _Const2['default'].SORT_DESC ? _Const2['default'].SORT_ASC : _Const2['default'].SORT_DESC;
_this.props.onSort(order, _this.props.dataField);
};
this.handleFilter = this.handleFilter.bind(this);
}
_createClass(TableHeaderColumn, [{
key: 'handleFilter',
value: function handleFilter(value, type) {
this.props.filter.emitter.handleFilter(this.props.dataField, value, type);
}
}, {
key: 'getFilters',
value: function getFilters() {
switch (this.props.filter.type) {
case _Const2['default'].FILTER_TYPE.TEXT:
{
return _react2['default'].createElement(_filtersText2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.REGEX:
{
return _react2['default'].createElement(_filtersRegex2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.SELECT:
{
return _react2['default'].createElement(_filtersSelect2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.NUMBER:
{
return _react2['default'].createElement(_filtersNumber2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.DATE:
{
return _react2['default'].createElement(_filtersDate2['default'], _extends({}, this.props.filter, {
columnName: this.props.children, filterHandler: this.handleFilter }));
}
case _Const2['default'].FILTER_TYPE.CUSTOM:
{
return this.props.filter.getElement(this.handleFilter, this.props.filter.customFilterParameters);
}
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
this.refs['header-col'].setAttribute('data-field', this.props.dataField);
}
}, {
key: 'render',
value: function render() {
var defaultCaret = undefined;
var _props = this.props;
var dataAlign = _props.dataAlign;
var headerAlign = _props.headerAlign;
var hidden = _props.hidden;
var sort = _props.sort;
var dataSort = _props.dataSort;
var sortIndicator = _props.sortIndicator;
var children = _props.children;
var caretRender = _props.caretRender;
var thStyle = {
textAlign: headerAlign || dataAlign,
display: hidden ? 'none' : null
};
if (sortIndicator) {
defaultCaret = !dataSort ? null : _react2['default'].createElement(
'span',
{ className: 'order' },
_react2['default'].createElement(
'span',
{ className: 'dropdown' },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0 10px 5px', color: '#ccc' } })
),
_react2['default'].createElement(
'span',
{ className: 'dropup' },
_react2['default'].createElement('span', { className: 'caret', style: { margin: '10px 0', color: '#ccc' } })
)
);
}
var sortCaret = sort ? _util2['default'].renderReactSortCaret(sort) : defaultCaret;
if (caretRender) {
sortCaret = caretRender(sort);
}
var classes = this.props.className + ' ' + (dataSort ? 'sort-column' : '');
var title = typeof children === 'string' ? { title: children } : null;
return _react2['default'].createElement(
'th',
_extends({ ref: 'header-col',
className: classes,
style: thStyle,
onClick: this.handleColumnClick
}, title),
children,
sortCaret,
_react2['default'].createElement(
'div',
{ onClick: function (e) {
return e.stopPropagation();
} },
this.props.filter ? this.getFilters() : null
)
);
}
}]);
return TableHeaderColumn;
})(_react.Component);
var filterTypeArray = [];
for (var key in _Const2['default'].FILTER_TYPE) {
filterTypeArray.push(_Const2['default'].FILTER_TYPE[key]);
}
TableHeaderColumn.propTypes = {
dataField: _react.PropTypes.string,
dataAlign: _react.PropTypes.string,
headerAlign: _react.PropTypes.string,
dataSort: _react.PropTypes.bool,
onSort: _react.PropTypes.func,
dataFormat: _react.PropTypes.func,
csvFormat: _react.PropTypes.func,
csvHeader: _react.PropTypes.string,
isKey: _react.PropTypes.bool,
editable: _react.PropTypes.any,
hidden: _react.PropTypes.bool,
hiddenOnInsert: _react.PropTypes.bool,
searchable: _react.PropTypes.bool,
className: _react.PropTypes.string,
width: _react.PropTypes.string,
sortFunc: _react.PropTypes.func,
sortFuncExtraData: _react.PropTypes.any,
columnClassName: _react.PropTypes.any,
columnTitle: _react.PropTypes.bool,
filterFormatted: _react.PropTypes.bool,
sort: _react.PropTypes.string,
caretRender: _react.PropTypes.func,
formatExtraData: _react.PropTypes.any,
filter: _react.PropTypes.shape({
type: _react.PropTypes.oneOf(filterTypeArray),
delay: _react.PropTypes.number,
options: _react.PropTypes.oneOfType([_react.PropTypes.object, // for SelectFilter
_react.PropTypes.arrayOf(_react.PropTypes.number) // for NumberFilter
]),
numberComparators: _react.PropTypes.arrayOf(_react.PropTypes.string),
emitter: _react.PropTypes.object,
placeholder: _react.PropTypes.string,
getElement: _react.PropTypes.func,
customFilterParameters: _react.PropTypes.object
}),
sortIndicator: _react.PropTypes.bool,
'export': _react.PropTypes.bool
};
TableHeaderColumn.defaultProps = {
dataAlign: 'left',
headerAlign: undefined,
dataSort: false,
dataFormat: undefined,
csvFormat: undefined,
csvHeader: undefined,
isKey: false,
editable: true,
onSort: undefined,
hidden: false,
hiddenOnInsert: false,
searchable: true,
className: '',
columnTitle: false,
width: null,
sortFunc: undefined,
columnClassName: '',
filterFormatted: false,
sort: undefined,
formatExtraData: undefined,
sortFuncExtraData: undefined,
filter: undefined,
sortIndicator: true
};
exports['default'] = TableHeaderColumn;
module.exports = exports['default'];
/***/ },
/* 42 */
/***/ function(module, exports, __webpack_require__) {
/* eslint quotes: 0 */
/* eslint max-len: 0 */
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var legalComparators = ['=', '>', '>=', '<', '<=', '!='];
function dateParser(d) {
return d.getFullYear() + '-' + ("0" + (d.getMonth() + 1)).slice(-2) + '-' + ("0" + d.getDate()).slice(-2);
}
var DateFilter = (function (_Component) {
_inherits(DateFilter, _Component);
function DateFilter(props) {
_classCallCheck(this, DateFilter);
_get(Object.getPrototypeOf(DateFilter.prototype), 'constructor', this).call(this, props);
this.dateComparators = this.props.dateComparators || legalComparators;
this.filter = this.filter.bind(this);
this.onChangeComparator = this.onChangeComparator.bind(this);
}
_createClass(DateFilter, [{
key: 'setDefaultDate',
value: function setDefaultDate() {
var defaultDate = '';
var defaultValue = this.props.defaultValue;
if (defaultValue && defaultValue.date) {
// Set the appropriate format for the input type=date, i.e. "YYYY-MM-DD"
defaultDate = dateParser(new Date(defaultValue.date));
}
return defaultDate;
}
}, {
key: 'onChangeComparator',
value: function onChangeComparator(event) {
var date = this.refs.inputDate.value;
var comparator = event.target.value;
if (date === '') {
return;
}
date = new Date(date);
this.props.filterHandler({ date: date, comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE);
}
}, {
key: 'getComparatorOptions',
value: function getComparatorOptions() {
var optionTags = [];
optionTags.push(_react2['default'].createElement('option', { key: '-1' }));
for (var i = 0; i < this.dateComparators.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: this.dateComparators[i] },
this.dateComparators[i]
));
}
return optionTags;
}
}, {
key: 'filter',
value: function filter(event) {
var comparator = this.refs.dateFilterComparator.value;
var dateValue = event.target.value;
if (dateValue) {
this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE);
} else {
this.props.filterHandler(null, _Const2['default'].FILTER_TYPE.DATE);
}
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var comparator = this.refs.dateFilterComparator.value;
var dateValue = this.refs.inputDate.value;
if (comparator && dateValue) {
this.props.filterHandler({ date: new Date(dateValue), comparator: comparator }, _Const2['default'].FILTER_TYPE.DATE);
}
}
}, {
key: 'render',
value: function render() {
var defaultValue = this.props.defaultValue;
return _react2['default'].createElement(
'div',
{ className: 'filter date-filter' },
_react2['default'].createElement(
'select',
{ ref: 'dateFilterComparator',
className: 'date-filter-comparator form-control',
onChange: this.onChangeComparator,
defaultValue: defaultValue ? defaultValue.comparator : '' },
this.getComparatorOptions()
),
_react2['default'].createElement('input', { ref: 'inputDate',
className: 'filter date-filter-input form-control',
type: 'date',
onChange: this.filter,
defaultValue: this.setDefaultDate() })
);
}
}]);
return DateFilter;
})(_react.Component);
DateFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.shape({
date: _react.PropTypes.object,
comparator: _react.PropTypes.oneOf(legalComparators)
}),
/* eslint consistent-return: 0 */
dateComparators: function dateComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Date comparator provided is not supported.\n Use only ' + legalComparators);
}
}
},
columnName: _react.PropTypes.string
};
exports['default'] = DateFilter;
module.exports = exports['default'];
/***/ },
/* 43 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var TextFilter = (function (_Component) {
_inherits(TextFilter, _Component);
function TextFilter(props) {
_classCallCheck(this, TextFilter);
_get(Object.getPrototypeOf(TextFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.timeout = null;
}
_createClass(TextFilter, [{
key: 'filter',
value: function filter(event) {
var _this = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.TEXT);
}, this.props.delay);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var defaultValue = this.refs.inputText.value;
if (defaultValue) {
this.props.filterHandler(defaultValue, _Const2['default'].FILTER_TYPE.TEXT);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
var defaultValue = _props.defaultValue;
return _react2['default'].createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return TextFilter;
})(_react.Component);
TextFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
TextFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = TextFilter;
module.exports = exports['default'];
/***/ },
/* 44 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var RegexFilter = (function (_Component) {
_inherits(RegexFilter, _Component);
function RegexFilter(props) {
_classCallCheck(this, RegexFilter);
_get(Object.getPrototypeOf(RegexFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.timeout = null;
}
_createClass(RegexFilter, [{
key: 'filter',
value: function filter(event) {
var _this = this;
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler(filterValue, _Const2['default'].FILTER_TYPE.REGEX);
}, this.props.delay);
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.inputText.value;
if (value) {
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.REGEX);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var _props = this.props;
var defaultValue = _props.defaultValue;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
return _react2['default'].createElement('input', { ref: 'inputText',
className: 'filter text-filter form-control',
type: 'text',
onChange: this.filter,
placeholder: placeholder || 'Enter Regex for ' + columnName + '...',
defaultValue: defaultValue ? defaultValue : '' });
}
}]);
return RegexFilter;
})(_react.Component);
RegexFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
defaultValue: _react.PropTypes.string,
delay: _react.PropTypes.number,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
RegexFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = RegexFilter;
module.exports = exports['default'];
/***/ },
/* 45 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var SelectFilter = (function (_Component) {
_inherits(SelectFilter, _Component);
function SelectFilter(props) {
_classCallCheck(this, SelectFilter);
_get(Object.getPrototypeOf(SelectFilter.prototype), 'constructor', this).call(this, props);
this.filter = this.filter.bind(this);
this.state = {
isPlaceholderSelected: this.props.defaultValue === undefined || !this.props.options.hasOwnProperty(this.props.defaultValue)
};
}
_createClass(SelectFilter, [{
key: 'filter',
value: function filter(event) {
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT);
}
}, {
key: 'getOptions',
value: function getOptions() {
var optionTags = [];
var _props = this.props;
var options = _props.options;
var placeholder = _props.placeholder;
var columnName = _props.columnName;
optionTags.push(_react2['default'].createElement(
'option',
{ key: '-1', value: '' },
placeholder || 'Select ' + columnName + '...'
));
Object.keys(options).map(function (key) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: key, value: key },
options[key]
));
});
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var value = this.refs.selectInput.value;
if (value) {
this.props.filterHandler(value, _Const2['default'].FILTER_TYPE.SELECT);
}
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2['default'])('filter', 'select-filter', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2['default'].createElement(
'select',
{ ref: 'selectInput',
className: selectClass,
onChange: this.filter,
defaultValue: this.props.defaultValue !== undefined ? this.props.defaultValue : '' },
this.getOptions()
);
}
}]);
return SelectFilter;
})(_react.Component);
SelectFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.object.isRequired,
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
exports['default'] = SelectFilter;
module.exports = exports['default'];
/***/ },
/* 46 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
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 ('value' in descriptor) 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(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _classnames = __webpack_require__(6);
var _classnames2 = _interopRequireDefault(_classnames);
var _Const = __webpack_require__(3);
var _Const2 = _interopRequireDefault(_Const);
var legalComparators = ['=', '>', '>=', '<', '<=', '!='];
var NumberFilter = (function (_Component) {
_inherits(NumberFilter, _Component);
function NumberFilter(props) {
_classCallCheck(this, NumberFilter);
_get(Object.getPrototypeOf(NumberFilter.prototype), 'constructor', this).call(this, props);
this.numberComparators = this.props.numberComparators || legalComparators;
this.timeout = null;
this.state = {
isPlaceholderSelected: this.props.defaultValue === undefined || this.props.defaultValue.number === undefined || this.props.options && this.props.options.indexOf(this.props.defaultValue.number) === -1
};
this.onChangeNumber = this.onChangeNumber.bind(this);
this.onChangeNumberSet = this.onChangeNumberSet.bind(this);
this.onChangeComparator = this.onChangeComparator.bind(this);
}
_createClass(NumberFilter, [{
key: 'onChangeNumber',
value: function onChangeNumber(event) {
var _this = this;
var comparator = this.refs.numberFilterComparator.value;
if (comparator === '') {
return;
}
if (this.timeout) {
clearTimeout(this.timeout);
}
var filterValue = event.target.value;
this.timeout = setTimeout(function () {
_this.props.filterHandler({ number: filterValue, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}, this.props.delay);
}
}, {
key: 'onChangeNumberSet',
value: function onChangeNumberSet(event) {
var comparator = this.refs.numberFilterComparator.value;
var value = event.target.value;
this.setState({ isPlaceholderSelected: value === '' });
if (comparator === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}, {
key: 'onChangeComparator',
value: function onChangeComparator(event) {
var value = this.refs.numberFilter.value;
var comparator = event.target.value;
if (value === '') {
return;
}
this.props.filterHandler({ number: value, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}, {
key: 'getComparatorOptions',
value: function getComparatorOptions() {
var optionTags = [];
optionTags.push(_react2['default'].createElement('option', { key: '-1' }));
for (var i = 0; i < this.numberComparators.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: this.numberComparators[i] },
this.numberComparators[i]
));
}
return optionTags;
}
}, {
key: 'getNumberOptions',
value: function getNumberOptions() {
var optionTags = [];
var options = this.props.options;
optionTags.push(_react2['default'].createElement(
'option',
{ key: '-1', value: '' },
this.props.placeholder || 'Select ' + this.props.columnName + '...'
));
for (var i = 0; i < options.length; i++) {
optionTags.push(_react2['default'].createElement(
'option',
{ key: i, value: options[i] },
options[i]
));
}
return optionTags;
}
}, {
key: 'componentDidMount',
value: function componentDidMount() {
var comparator = this.refs.numberFilterComparator.value;
var number = this.refs.numberFilter.value;
if (comparator && number) {
this.props.filterHandler({ number: number, comparator: comparator }, _Const2['default'].FILTER_TYPE.NUMBER);
}
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timeout);
}
}, {
key: 'render',
value: function render() {
var selectClass = (0, _classnames2['default'])('select-filter', 'number-filter-input', 'form-control', { 'placeholder-selected': this.state.isPlaceholderSelected });
return _react2['default'].createElement(
'div',
{ className: 'filter number-filter' },
_react2['default'].createElement(
'select',
{ ref: 'numberFilterComparator',
className: 'number-filter-comparator form-control',
onChange: this.onChangeComparator,
defaultValue: this.props.defaultValue ? this.props.defaultValue.comparator : '' },
this.getComparatorOptions()
),
this.props.options ? _react2['default'].createElement(
'select',
{ ref: 'numberFilter',
className: selectClass,
onChange: this.onChangeNumberSet,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' },
this.getNumberOptions()
) : _react2['default'].createElement('input', { ref: 'numberFilter',
type: 'number',
className: 'number-filter-input form-control',
placeholder: this.props.placeholder || 'Enter ' + this.props.columnName + '...',
onChange: this.onChangeNumber,
defaultValue: this.props.defaultValue ? this.props.defaultValue.number : '' })
);
}
}]);
return NumberFilter;
})(_react.Component);
NumberFilter.propTypes = {
filterHandler: _react.PropTypes.func.isRequired,
options: _react.PropTypes.arrayOf(_react.PropTypes.number),
defaultValue: _react.PropTypes.shape({
number: _react.PropTypes.number,
comparator: _react.PropTypes.oneOf(legalComparators)
}),
delay: _react.PropTypes.number,
/* eslint consistent-return: 0 */
numberComparators: function numberComparators(props, propName) {
if (!props[propName]) {
return;
}
for (var i = 0; i < props[propName].length; i++) {
var comparatorIsValid = false;
for (var j = 0; j < legalComparators.length; j++) {
if (legalComparators[j] === props[propName][i]) {
comparatorIsValid = true;
break;
}
}
if (!comparatorIsValid) {
return new Error('Number comparator provided is not supported.\n Use only ' + legalComparators);
}
}
},
placeholder: _react.PropTypes.string,
columnName: _react.PropTypes.string
};
NumberFilter.defaultProps = {
delay: _Const2['default'].FILTER_DELAY
};
exports['default'] = NumberFilter;
module.exports = exports['default'];
/***/ }
/******/ ])
});
;
//# sourceMappingURL=react-bootstrap-table.js.map
|
ajax/libs/yui/3.17.0/datatable-body/datatable-body-debug.js
|
dlueth/cdnjs
|
/*
YUI 3.17.0 (build ce55cc9)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('datatable-body', function (Y, NAME) {
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
@module datatable
@submodule datatable-body
@since 3.5.0
**/
var Lang = Y.Lang,
isArray = Lang.isArray,
isNumber = Lang.isNumber,
isString = Lang.isString,
fromTemplate = Lang.sub,
htmlEscape = Y.Escape.html,
toArray = Y.Array,
bind = Y.bind,
YObject = Y.Object,
valueRegExp = /\{value\}/g,
EV_CONTENT_UPDATE = 'contentUpdate',
shiftMap = {
above: [-1, 0],
below: [1, 0],
next: [0, 1],
prev: [0, -1],
previous: [0, -1]
};
/**
View class responsible for rendering the `<tbody>` section of a table. Used as
the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes.
Translates the provided `modelList` into a rendered `<tbody>` based on the data
in the constituent Models, altered or amended by any special column
configurations.
The `columns` configuration, passed to the constructor, determines which
columns will be rendered.
The rendering process involves constructing an HTML template for a complete row
of data, built by concatenating a customized copy of the instance's
`CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is
then populated with values from each Model in the `modelList`, aggregating a
complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this
column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform any
custom modifications on the cell or row Node that could not be performed by
`formatter`s. Should be used sparingly for better performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a column.
A column `formatter` can be:
* a function, as described below.
* a string which can be:
* the name of a pre-defined formatter function
which can be located in the `Y.DataTable.BodyView.Formatters` hash using the
value of the `formatter` property as the index.
* A template that can use the `{value}` placeholder to include the value
for the current cell or the name of any field in the underlaying model
also enclosed in curly braces. Any number and type of these placeholders
can be used.
Column `formatter`s are passed an object (`o`) with the following properties:
* `value` - The current value of the column's associated attribute, if any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML content. A
returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`.
When adding content to the cell, prefer appending into this property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as
it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The DOM
elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@class BodyView
@namespace DataTable
@extends View
@since 3.5.0
**/
Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], {
// -- Instance properties -------------------------------------------------
/**
HTML template used to create table cells.
@property CELL_TEMPLATE
@type {String}
@default '<td {headers} class="{className}">{content}</td>'
@since 3.5.0
**/
CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>',
/**
CSS class applied to even rows. This is assigned at instantiation.
For DataTable, this will be `yui3-datatable-even`.
@property CLASS_EVEN
@type {String}
@default 'yui3-table-even'
@since 3.5.0
**/
//CLASS_EVEN: null
/**
CSS class applied to odd rows. This is assigned at instantiation.
When used by DataTable instances, this will be `yui3-datatable-odd`.
@property CLASS_ODD
@type {String}
@default 'yui3-table-odd'
@since 3.5.0
**/
//CLASS_ODD: null
/**
HTML template used to create table rows.
@property ROW_TEMPLATE
@type {String}
@default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>'
@since 3.5.0
**/
ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>',
/**
The object that serves as the source of truth for column and row data.
This property is assigned at instantiation from the `host` property of
the configuration object passed to the constructor.
@property host
@type {Object}
@default (initially unset)
@since 3.5.0
**/
//TODO: should this be protected?
//host: null,
/**
HTML templates used to create the `<tbody>` containing the table rows.
@property TBODY_TEMPLATE
@type {String}
@default '<tbody class="{className}">{content}</tbody>'
@since 3.6.0
**/
TBODY_TEMPLATE: '<tbody class="{className}"></tbody>',
// -- Public methods ------------------------------------------------------
/**
Returns the `<td>` Node from the given row and column index. Alternately,
the `seed` can be a Node. If so, the nearest ancestor cell is returned.
If the `seed` is a cell, it is returned. If there is no cell at the given
coordinates, `null` is returned.
Optionally, include an offset array or string to return a cell near the
cell identified by the `seed`. The offset can be an array containing the
number of rows to shift followed by the number of columns to shift, or one
of "above", "below", "next", or "previous".
<pre><code>// Previous cell in the previous row
var cell = table.getCell(e.target, [-1, -1]);
// Next cell
var cell = table.getCell(e.target, 'next');
var cell = table.getCell(e.target, [0, 1];</pre></code>
@method getCell
@param {Number[]|Node} seed Array of row and column indexes, or a Node that
is either the cell itself or a descendant of one.
@param {Number[]|String} [shift] Offset by which to identify the returned
cell Node
@return {Node}
@since 3.5.0
**/
getCell: function (seed, shift) {
var tbody = this.tbodyNode,
row, cell, index, rowIndexOffset;
if (seed && tbody) {
if (isArray(seed)) {
row = tbody.get('children').item(seed[0]);
cell = row && row.get('children').item(seed[1]);
} else if (seed._node) {
cell = seed.ancestor('.' + this.getClassName('cell'), true);
}
if (cell && shift) {
rowIndexOffset = tbody.get('firstChild.rowIndex');
if (isString(shift)) {
if (!shiftMap[shift]) {
Y.error('Unrecognized shift: ' + shift, null, 'datatable-body');
}
shift = shiftMap[shift];
}
if (isArray(shift)) {
index = cell.get('parentNode.rowIndex') +
shift[0] - rowIndexOffset;
row = tbody.get('children').item(index);
index = cell.get('cellIndex') + shift[1];
cell = row && row.get('children').item(index);
}
}
}
return cell || null;
},
/**
Returns the generated CSS classname based on the input. If the `host`
attribute is configured, it will attempt to relay to its `getClassName`
or use its static `NAME` property as a string base.
If `host` is absent or has neither method nor `NAME`, a CSS classname
will be generated using this class's `NAME`.
@method getClassName
@param {String} token* Any number of token strings to assemble the
classname from.
@return {String}
@protected
@since 3.5.0
**/
getClassName: function () {
var host = this.host,
args;
if (host && host.getClassName) {
return host.getClassName.apply(host, arguments);
} else {
args = toArray(arguments);
args.unshift(this.constructor.NAME);
return Y.ClassNameManager.getClassName
.apply(Y.ClassNameManager, args);
}
},
/**
Returns the Model associated to the row Node or id provided. Passing the
Node or id for a descendant of the row also works.
If no Model can be found, `null` is returned.
@method getRecord
@param {String|Node} seed Row Node or `id`, or one for a descendant of a row
@return {Model}
@since 3.5.0
**/
getRecord: function (seed) {
var modelList = this.get('modelList'),
tbody = this.tbodyNode,
row = null,
record;
if (tbody) {
if (isString(seed)) {
seed = tbody.one('#' + seed);
}
if (seed && seed._node) {
row = seed.ancestor(function (node) {
return node.get('parentNode').compareTo(tbody);
}, true);
record = row &&
modelList.getByClientId(row.getData('yui3-record'));
}
}
return record || null;
},
/**
Returns the `<tr>` Node from the given row index, Model, or Model's
`clientId`. If the rows haven't been rendered yet, or if the row can't be
found by the input, `null` is returned.
@method getRow
@param {Number|String|Model} id Row index, Model instance, or clientId
@return {Node}
@since 3.5.0
**/
getRow: function (id) {
var tbody = this.tbodyNode,
row = null;
if (tbody) {
if (id) {
id = this._idMap[id.get ? id.get('clientId') : id] || id;
}
row = isNumber(id) ?
tbody.get('children').item(id) :
tbody.one('#' + id);
}
return row;
},
/**
Creates the table's `<tbody>` content by assembling markup generated by
populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content
from the `columns` and `modelList` attributes.
The rendering process happens in three stages:
1. A row template is assembled from the `columns` attribute (see
`_createRowTemplate`)
2. An HTML string is built up by concatenating the application of the data in
each Model in the `modelList` to the row template. For cells with
`formatter`s, the function is called to generate cell content. Cells
with `nodeFormatter`s are ignored. For all other cells, the data value
from the Model attribute for the given column key is used. The
accumulated row markup is then inserted into the container.
3. If any column is configured with a `nodeFormatter`, the `modelList` is
iterated again to apply the `nodeFormatter`s.
Supported properties of the column objects include:
* `key` - Used to link a column to an attribute in a Model.
* `name` - Used for columns that don't relate to an attribute in the Model
(`formatter` or `nodeFormatter` only) if the implementer wants a
predictable name to refer to in their CSS.
* `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in
this column only.
* `formatter` - Used to customize or override the content value from the
Model. These do not have access to the cell or row Nodes and should
return string (HTML) content.
* `nodeFormatter` - Used to provide content for a cell as well as perform
any custom modifications on the cell or row Node that could not be
performed by `formatter`s. Should be used sparingly for better
performance.
* `emptyCellValue` - String (HTML) value to use if the Model data for a
column, or the content generated by a `formatter`, is the empty string,
`null`, or `undefined`.
* `allowHTML` - Set to `true` if a column value, `formatter`, or
`emptyCellValue` can contain HTML. This defaults to `false` to protect
against XSS.
* `className` - Space delimited CSS classes to add to all `<td>`s in a
column.
Column `formatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `className` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's `<td>`.
* `rowIndex` - The zero-based row number.
* `rowClass` - Initially empty string to allow `formatter`s to add CSS
classes to the cell's containing row `<tr>`.
They may return a value or update `o.value` to assign specific HTML
content. A returned value has higher precedence.
Column `nodeFormatter`s are passed an object (`o`) with the following
properties:
* `value` - The current value of the column's associated attribute, if
any.
* `td` - The `<td>` Node instance.
* `cell` - The `<div>` liner Node instance if present, otherwise, the
`<td>`. When adding content to the cell, prefer appending into this
property.
* `data` - An object map of Model keys to their current values.
* `record` - The Model instance.
* `column` - The column configuration object for the current column.
* `rowIndex` - The zero-based row number.
They are expected to inject content into the cell's Node directly, including
any "empty" cell content. Each `nodeFormatter` will have access through the
Node API to all cells and rows in the `<tbody>`, but not to the `<table>`,
as it will not be attached yet.
If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be
`destroy()`ed to remove them from the Node cache and free up memory. The
DOM elements will remain as will any content added to them. _It is highly
advisable to always return `false` from your `nodeFormatter`s_.
@method render
@chainable
@since 3.5.0
**/
render: function () {
var table = this.get('container'),
data = this.get('modelList'),
displayCols = this.get('columns'),
tbody = this.tbodyNode ||
(this.tbodyNode = this._createTBodyNode());
// Needed for mutation
this._createRowTemplate(displayCols);
if (data) {
tbody.setHTML(this._createDataHTML(displayCols));
this._applyNodeFormatters(tbody, displayCols);
}
if (tbody.get('parentNode') !== table) {
table.appendChild(tbody);
}
this.bindUI();
return this;
},
/**
Refreshes the provided row against the provided model and the Array of
columns to be updated.
@method refreshRow
@param {Node} row
@param {Model} model Y.Model representation of the row
@param {String[]} colKeys Array of column keys
@chainable
*/
refreshRow: function (row, model, colKeys) {
var col,
cell,
len = colKeys.length,
i;
for (i = 0; i < len; i++) {
col = this.getColumn(colKeys[i]);
if (col !== null) {
cell = row.one('.' + this.getClassName('col', col._id || col.key));
this.refreshCell(cell, model);
}
}
return this;
},
/**
Refreshes the given cell with the provided model data and the provided
column configuration.
Uses the provided column formatter if aviable.
@method refreshCell
@param {Node} cell Y.Node pointer to the cell element to be updated
@param {Model} [model] Y.Model representation of the row
@param {Object} [col] Column configuration object for the cell
@chainable
*/
refreshCell: function (cell, model, col) {
var content,
formatterFn,
formatterData,
data = model.toJSON();
cell = this.getCell(cell);
/* jshint -W030 */
model || (model = this.getRecord(cell));
col || (col = this.getColumn(cell));
/* jshint +W030 */
if (col.nodeFormatter) {
formatterData = {
cell: cell.one('.' + this.getClassName('liner')) || cell,
column: col,
data: data,
record: model,
rowIndex: this._getRowIndex(cell.ancestor('tr')),
td: cell,
value: data[col.key]
};
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
} else if (col.formatter) {
if (!col._formatterFn) {
col = this._setColumnsFormatterFn([col])[0];
}
formatterFn = col._formatterFn || null;
if (formatterFn) {
formatterData = {
value : data[col.key],
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : this._getRowIndex(cell.ancestor('tr'))
};
// Formatters can either return a value ...
content = formatterFn.call(this.get('host'), formatterData);
// ... or update the value property of the data obj passed
if (content === undefined) {
content = formatterData.value;
}
}
if (content === undefined || content === null || content === '') {
content = col.emptyCellValue || '';
}
} else {
content = data[col.key] || col.emptyCellValue || '';
}
cell.setHTML(col.allowHTML ? content : Y.Escape.html(content));
return this;
},
/**
Returns column data from this.get('columns'). If a Y.Node is provided as
the key, will try to determine the key from the classname
@method getColumn
@param {String|Node} name
@return {Object} Returns column configuration
*/
getColumn: function (name) {
if (name && name._node) {
// get column name from node
name = name.get('className').match(
new RegExp( this.getClassName('col') +'-([^ ]*)' )
)[1];
}
if (this.host) {
return this.host._columnMap[name] || null;
}
var displayCols = this.get('columns'),
col = null;
Y.Array.some(displayCols, function (_col) {
if ((_col._id || _col.key) === name) {
col = _col;
return true;
}
});
return col;
},
// -- Protected and private methods ---------------------------------------
/**
Handles changes in the source's columns attribute. Redraws the table data.
@method _afterColumnsChange
@param {EventFacade} e The `columnsChange` event object
@protected
@since 3.5.0
**/
// TODO: Preserve existing DOM
// This will involve parsing and comparing the old and new column configs
// and reacting to four types of changes:
// 1. formatter, nodeFormatter, emptyCellValue changes
// 2. column deletions
// 3. column additions
// 4. column moves (preserve cells)
_afterColumnsChange: function () {
this.render();
},
/**
Handles modelList changes, including additions, deletions, and updates.
Modifies the existing table DOM accordingly.
@method _afterDataChange
@param {EventFacade} e The `change` event from the ModelList
@protected
@since 3.5.0
**/
_afterDataChange: function (e) {
var type = (e.type.match(/:(add|change|remove)$/) || [])[1],
index = e.index,
displayCols = this.get('columns'),
col,
changed = e.changed && Y.Object.keys(e.changed),
key,
row,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++ ) {
col = displayCols[i];
// since nodeFormatters typcially make changes outside of it's
// cell, we need to see if there are any columns that have a
// nodeFormatter and if so, we need to do a full render() of the
// tbody
if (col.hasOwnProperty('nodeFormatter')) {
this.render();
this.fire(EV_CONTENT_UPDATE);
return;
}
}
// TODO: if multiple rows are being added/remove/swapped, can we avoid the restriping?
switch (type) {
case 'change':
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
key = col.key;
if (col.formatter && !e.changed[key]) {
changed.push(key);
}
}
this.refreshRow(this.getRow(e.target), e.target, changed);
break;
case 'add':
// we need to make sure we don't have an index larger than the data we have
index = Math.min(index, this.get('modelList').size() - 1);
// updates the columns with formatter functions
this._setColumnsFormatterFn(displayCols);
row = Y.Node.create(this._createRowHTML(e.model, index, displayCols));
this.tbodyNode.insert(row, index);
this._restripe(index);
break;
case 'remove':
this.getRow(index).remove(true);
// we removed a row, so we need to back up our index to stripe
this._restripe(index - 1);
break;
default:
this.render();
}
// Event fired to tell users when we are done updating after the data
// was changed
this.fire(EV_CONTENT_UPDATE);
},
/**
Toggles the odd/even classname of the row after the given index. This method
is used to update rows after a row is inserted into or removed from the table.
Note this event is delayed so the table is only restriped once when multiple
rows are updated at one time.
@protected
@method _restripe
@param {Number} [index] Index of row to start restriping after
@since 3.11.0
*/
_restripe: function (index) {
var task = this._restripeTask,
self;
// index|0 to force int, avoid NaN. Math.max() to avoid neg indexes.
index = Math.max((index|0), 0);
if (!task) {
self = this;
this._restripeTask = {
timer: setTimeout(function () {
// Check for self existence before continuing
if (!self || self.get('destroy') || !self.tbodyNode || !self.tbodyNode.inDoc()) {
self._restripeTask = null;
return;
}
var odd = [self.CLASS_ODD, self.CLASS_EVEN],
even = [self.CLASS_EVEN, self.CLASS_ODD],
index = self._restripeTask.index;
self.tbodyNode.get('childNodes')
.slice(index)
.each(function (row, i) { // TODO: each vs batch
row.replaceClass.apply(row, (index + i) % 2 ? even : odd);
});
self._restripeTask = null;
}, 0),
index: index
};
} else {
task.index = Math.min(task.index, index);
}
},
/**
Handles replacement of the modelList.
Rerenders the `<tbody>` contents.
@method _afterModelListChange
@param {EventFacade} e The `modelListChange` event
@protected
@since 3.6.0
**/
_afterModelListChange: function () {
var handles = this._eventHandles;
if (handles.dataChange) {
handles.dataChange.detach();
delete handles.dataChange;
this.bindUI();
}
if (this.tbodyNode) {
this.render();
}
},
/**
Iterates the `modelList`, and calls any `nodeFormatter`s found in the
`columns` param on the appropriate cell Nodes in the `tbody`.
@method _applyNodeFormatters
@param {Node} tbody The `<tbody>` Node whose columns to update
@param {Object[]} displayCols The column configurations
@protected
@since 3.5.0
**/
_applyNodeFormatters: function (tbody, displayCols) {
var host = this.host || this,
data = this.get('modelList'),
formatters = [],
linerQuery = '.' + this.getClassName('liner'),
rows, i, len;
// Only iterate the ModelList again if there are nodeFormatters
for (i = 0, len = displayCols.length; i < len; ++i) {
if (displayCols[i].nodeFormatter) {
formatters.push(i);
}
}
if (data && formatters.length) {
rows = tbody.get('childNodes');
data.each(function (record, index) {
var formatterData = {
data : record.toJSON(),
record : record,
rowIndex : index
},
row = rows.item(index),
i, len, col, key, cells, cell, keep;
if (row) {
cells = row.get('childNodes');
for (i = 0, len = formatters.length; i < len; ++i) {
cell = cells.item(formatters[i]);
if (cell) {
col = formatterData.column = displayCols[formatters[i]];
key = col.key || col.id;
formatterData.value = record.get(key);
formatterData.td = cell;
formatterData.cell = cell.one(linerQuery) || cell;
keep = col.nodeFormatter.call(host,formatterData);
if (keep === false) {
// Remove from the Node cache to reduce
// memory footprint. This also purges events,
// which you shouldn't be scoping to a cell
// anyway. You've been warned. Incidentally,
// you should always return false. Just sayin.
cell.destroy(true);
}
}
}
}
});
}
},
/**
Binds event subscriptions from the UI and the host (if assigned).
@method bindUI
@protected
@since 3.5.0
**/
bindUI: function () {
var handles = this._eventHandles,
modelList = this.get('modelList'),
changeEvent = modelList.model.NAME + ':change';
if (!handles.columnsChange) {
handles.columnsChange = this.after('columnsChange',
bind('_afterColumnsChange', this));
}
if (modelList && !handles.dataChange) {
handles.dataChange = modelList.after(
['add', 'remove', 'reset', changeEvent],
bind('_afterDataChange', this));
}
},
/**
Iterates the `modelList` and applies each Model to the `_rowTemplate`,
allowing any column `formatter` or `emptyCellValue` to override cell
content for the appropriate column. The aggregated HTML string is
returned.
@method _createDataHTML
@param {Object[]} displayCols The column configurations to customize the
generated cell content or class names
@return {String} The markup for all Models in the `modelList`, each applied
to the `_rowTemplate`
@protected
@since 3.5.0
**/
_createDataHTML: function (displayCols) {
var data = this.get('modelList'),
html = '';
if (data) {
data.each(function (model, index) {
html += this._createRowHTML(model, index, displayCols);
}, this);
}
return html;
},
/**
Applies the data of a given Model, modified by any column formatters and
supplemented by other template values to the instance's `_rowTemplate` (see
`_createRowTemplate`). The generated string is then returned.
The data from Model's attributes is fetched by `toJSON` and this data
object is appended with other properties to supply values to {placeholders}
in the template. For a template generated from a Model with 'foo' and 'bar'
attributes, the data object would end up with the following properties
before being used to populate the `_rowTemplate`:
* `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute.
* `foo` - The value to populate the 'foo' column cell content. This
value will be the value stored in the Model's `foo` attribute, or the
result of the column's `formatter` if assigned. If the value is '',
`null`, or `undefined`, and the column's `emptyCellValue` is assigned,
that value will be used.
* `bar` - Same for the 'bar' column cell content.
* `foo-className` - String of CSS classes to apply to the `<td>`.
* `bar-className` - Same.
* `rowClass` - String of CSS classes to apply to the `<tr>`. This
will be the odd/even class per the specified index plus any additional
classes assigned by column formatters (via `o.rowClass`).
Because this object is available to formatters, any additional properties
can be added to fill in custom {placeholders} in the `_rowTemplate`.
@method _createRowHTML
@param {Model} model The Model instance to apply to the row template
@param {Number} index The index the row will be appearing
@param {Object[]} displayCols The column configurations
@return {String} The markup for the provided Model, less any `nodeFormatter`s
@protected
@since 3.5.0
**/
_createRowHTML: function (model, index, displayCols) {
var data = model.toJSON(),
clientId = model.get('clientId'),
values = {
rowId : this._getRowId(clientId),
clientId: clientId,
rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN
},
host = this.host || this,
i, len, col, token, value, formatterData;
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
value = data[col.key];
token = col._id || col.key;
values[token + '-className'] = '';
if (col._formatterFn) {
formatterData = {
value : value,
data : data,
column : col,
record : model,
className: '',
rowClass : '',
rowIndex : index
};
// Formatters can either return a value
value = col._formatterFn.call(host, formatterData);
// or update the value property of the data obj passed
if (value === undefined) {
value = formatterData.value;
}
values[token + '-className'] = formatterData.className;
values.rowClass += ' ' + formatterData.rowClass;
}
// if the token missing OR is the value a legit value
if (!values.hasOwnProperty(token) || data.hasOwnProperty(col.key)) {
if (value === undefined || value === null || value === '') {
value = col.emptyCellValue || '';
}
values[token] = col.allowHTML ? value : htmlEscape(value);
}
}
// replace consecutive whitespace with a single space
values.rowClass = values.rowClass.replace(/\s+/g, ' ');
return fromTemplate(this._rowTemplate, values);
},
/**
Locates the row within the tbodyNode and returns the found index, or Null
if it is not found in the tbodyNode
@param {Node} row
@return {Number} Index of row in tbodyNode
*/
_getRowIndex: function (row) {
var tbody = this.tbodyNode,
index = 1;
if (tbody && row) {
//if row is not in the tbody, return
if (row.ancestor('tbody') !== tbody) {
return null;
}
// increment until we no longer have a previous node
/*jshint boss: true*/
while (row = row.previous()) { // NOTE: assignment
/*jshint boss: false*/
index++;
}
}
return index;
},
/**
Creates a custom HTML template string for use in generating the markup for
individual table rows with {placeholder}s to capture data from the Models
in the `modelList` attribute or from column `formatter`s.
Assigns the `_rowTemplate` property.
@method _createRowTemplate
@param {Object[]} displayCols Array of column configuration objects
@protected
@since 3.5.0
**/
_createRowTemplate: function (displayCols) {
var html = '',
cellTemplate = this.CELL_TEMPLATE,
i, len, col, key, token, headers, tokenValues, formatter;
this._setColumnsFormatterFn(displayCols);
for (i = 0, len = displayCols.length; i < len; ++i) {
col = displayCols[i];
key = col.key;
token = col._id || key;
formatter = col._formatterFn;
// Only include headers if there are more than one
headers = (col._headers || []).length > 1 ?
'headers="' + col._headers.join(' ') + '"' : '';
tokenValues = {
content : '{' + token + '}',
headers : headers,
className: this.getClassName('col', token) + ' ' +
(col.className || '') + ' ' +
this.getClassName('cell') +
' {' + token + '-className}'
};
if (!formatter && col.formatter) {
tokenValues.content = col.formatter.replace(valueRegExp, tokenValues.content);
}
if (col.nodeFormatter) {
// Defer all node decoration to the formatter
tokenValues.content = '';
}
html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues);
}
this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, {
content: html
});
},
/**
Parses the columns array and defines the column's _formatterFn if there
is a formatter available on the column
@protected
@method _setColumnsFormatterFn
@param {Object[]} displayCols Array of column configuration objects
@return {Object[]} Returns modified displayCols configuration Array
*/
_setColumnsFormatterFn: function (displayCols) {
var Formatters = Y.DataTable.BodyView.Formatters,
formatter,
col,
i,
len;
for (i = 0, len = displayCols.length; i < len; i++) {
col = displayCols[i];
formatter = col.formatter;
if (!col._formatterFn && formatter) {
if (Lang.isFunction(formatter)) {
col._formatterFn = formatter;
} else if (formatter in Formatters) {
col._formatterFn = Formatters[formatter].call(this.host || this, col);
}
}
}
return displayCols;
},
/**
Creates the `<tbody>` node that will store the data rows.
@method _createTBodyNode
@return {Node}
@protected
@since 3.6.0
**/
_createTBodyNode: function () {
return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, {
className: this.getClassName('data')
}));
},
/**
Destroys the instance.
@method destructor
@protected
@since 3.5.0
**/
destructor: function () {
(new Y.EventHandle(YObject.values(this._eventHandles))).detach();
},
/**
Holds the event subscriptions needing to be detached when the instance is
`destroy()`ed.
@property _eventHandles
@type {Object}
@default undefined (initially unset)
@protected
@since 3.5.0
**/
//_eventHandles: null,
/**
Returns the row ID associated with a Model's clientId.
@method _getRowId
@param {String} clientId The Model clientId
@return {String}
@protected
**/
_getRowId: function (clientId) {
return this._idMap[clientId] || (this._idMap[clientId] = Y.guid());
},
/**
Map of Model clientIds to row ids.
@property _idMap
@type {Object}
@protected
**/
//_idMap,
/**
Initializes the instance. Reads the following configuration properties in
addition to the instance attributes:
* `columns` - (REQUIRED) The initial column information
* `host` - The object to serve as source of truth for column info and
for generating class names
@method initializer
@param {Object} config Configuration data
@protected
@since 3.5.0
**/
initializer: function (config) {
this.host = config.host;
this._eventHandles = {
modelListChange: this.after('modelListChange',
bind('_afterModelListChange', this))
};
this._idMap = {};
this.CLASS_ODD = this.getClassName('odd');
this.CLASS_EVEN = this.getClassName('even');
}
/**
The HTML template used to create a full row of markup for a single Model in
the `modelList` plus any customizations defined in the column
configurations.
@property _rowTemplate
@type {String}
@default (initially unset)
@protected
@since 3.5.0
**/
//_rowTemplate: null
},{
/**
Hash of formatting functions for cell contents.
This property can be populated with a hash of formatting functions by the developer
or a set of pre-defined functions can be loaded via the `datatable-formatters` module.
See: [DataTable.BodyView.Formatters](./DataTable.BodyView.Formatters.html)
@property Formatters
@type Object
@since 3.8.0
@static
**/
Formatters: {}
});
}, '3.17.0', {"requires": ["datatable-core", "view", "classnamemanager"]});
|
ajax/libs/rxjs/2.3.24/rx.lite.js
|
cdnjs/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: {},
config: {
Promise: root.Promise,
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = Date.now,
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// 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); } }
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `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
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
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';
}
var isArguments = function(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;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// 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 == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// 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 || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
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 initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var 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) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// 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;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, 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;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
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));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
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) {
+index || (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();
}
}
};
/**
* 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 SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
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) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
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;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* 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 invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* 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 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);
};
/** 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) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
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 scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* 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 }, invokeRecImmediate);
};
/**
* 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, scheduleInnerRecursive);
};
/**
* 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, scheduleInnerRecursive);
};
/**
* 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');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* 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).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, 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).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
/** 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 = this.now() + normalizeTime(dueTime);
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 runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
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);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} 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; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { 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 scheduleMethod, clearMethod = noop;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
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;
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;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
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;
var onGlobalPostMessage = function (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 localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* 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 = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(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;
}
/**
* 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.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @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.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
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 (e) {
var notification = new Notification('E');
notification.exception = e;
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;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () { self(); })
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
lastException = exn;
self();
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
var exceptions = new Subject();
var handled = notificationHandler(exceptions);
var notifier = new Subject();
var notificationDisposable = handled.subscribe(notifier);
try {
e = sources[$iterator$]();
} catch (err) {
observer.onError(err);
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
observer.onNext.bind(observer),
function (exn) {
inner.setDisposable(notifier.subscribe(function(){
self();
}, function(ex) {
observer.onError(ex);
}, function() {
observer.onCompleted();
}));
exceptions.onNext(exn);
},
observer.onCompleted.bind(observer)));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @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);
};
/**
* 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.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @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.
* @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.
* @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.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @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} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
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();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () { self.observer.onNext(value); });
};
ScheduledObserver.prototype.error = function (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
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();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var source = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return source.subscribe(
function (x) { arr.push(x); },
function (e) { observer.onError(e); },
function () {
observer.onNext(arr);
observer.onCompleted();
});
}, source);
};
/**
* 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, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* 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 or Promise.
* @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);
}
isPromise(result) && (result = observableFromPromise(result));
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) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._s.charAt(this._i++);
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._a[this._i++];
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
var list = Object(iterable), it = getIterable(list);
return new AnonymousObservable(function (observer) {
var i = 0;
return scheduler.scheduleRecursive(function (self) {
var next;
try {
next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
});
});
};
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @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) {
//deprecate('fromArray', 'from');
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
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;
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
return observableOf(null, arguments);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
return observableOf(scheduler, slice.call(arguments, 1));
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var idx = 0, keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursive(function (self) {
if (idx < len) {
var key = keys[idx++];
observer.onNext([key, obj[key]]);
self();
} else {
observer.onCompleted();
}
});
});
};
/**
* 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) {
isScheduler(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) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
* @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.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
//deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* 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 'throwError' for browsers <IE9.
* @param {Mixed} error 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.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
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;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
}, source);
}
/**
* 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.catchError = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* @deprecated use #catch or #catchError instead.
*/
observableProto.catchException = function (handlerOrSecond) {
//deprecate('catchException', 'catch or catchError');
return this.catchError(handlerOrSecond);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = function () {
return enumerableOf(argsOrArray(arguments, 0)).catchError();
};
/**
* @deprecated use #catch or #catchError instead.
*/
Observable.catchException = function () {
//deprecate('catchException', 'catch or catchError');
return observableCatch.apply(null, arguments);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises 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 or Promises 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) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { observer.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @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.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
return enumerableOf(argsOrArray(arguments, 0)).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.concatAll = function () {
return this.merge(1);
};
/** @deprecated Use `concatAll` instead. */
observableProto.concatObservable = function () {
//deprecate('concatObservable', 'concatAll');
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 (o) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && o.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, function (e) { o.onError(e); }, function () {
isStopped = true;
activeCount === 0 && o.onCompleted();
}));
return group;
}, sources);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @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 (isScheduler(arguments[0])) {
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 observableOf(scheduler, sources).mergeAll();
};
/**
* 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.mergeAll = function () {
var sources = this;
return new AnonymousObservable(function (o) {
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);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && o.onCompleted();
}));
}, function (e) { o.onError(e); }, function () {
isStopped = true;
group.length === 1 && o.onCompleted();
}));
return group;
}, sources);
};
/**
* @deprecated use #mergeAll instead.
*/
observableProto.mergeObservable = function () {
//deprecate('mergeObservable', 'mergeAll');
return this.mergeAll.apply(this, arguments);
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise 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 (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* 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);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise 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 (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([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.withLatestFrom = function () {
var source = this;
var args = slice.call(arguments);
var resultSelector = args.pop();
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
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,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
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();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
/**
* 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; });
function next(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) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* 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);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* 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 (o) { return source.subscribe(o); }, this);
};
/**
* 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 (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* 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 (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var comparerEquals = false, key;
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
if (hasCurrentKey) {
try {
comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* 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.
* @param {Function | Observer} 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.tap = function (observerOrOnNext, onError, onCompleted) {
var source = this, onNextFunc;
if (typeof observerOrOnNext === 'function') {
onNextFunc = observerOrOnNext;
} else {
onNextFunc = function (x) { observerOrOnNext.onNext(x); };
onError = function (e) { observerOrOnNext.onError(e); };
onCompleted = function () { observerOrOnNext.onCompleted(); }
}
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
onNextFunc(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
if (onError) {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
}
observer.onError(err);
}, function () {
if (onCompleted) {
try {
onCompleted();
} catch (e) {
observer.onError(e);
}
}
observer.onCompleted();
});
}, this);
};
/** @deprecated use #do or #tap instead. */
observableProto.doAction = function () {
//deprecate('doAction', 'do or tap');
return this.tap.apply(this, arguments);
};
/**
* Invokes an action for each element in 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.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon 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.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful 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.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @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.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(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 (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* 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();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @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.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @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).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* 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 (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* 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 (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableOf([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @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.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* 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.concatMap(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.concatMap(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.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @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.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* 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 selectorFn = isFunction(selector) ? bindCallback(selector, thisArg, 3) : function () { return selector; },
source = this;
return new AnonymousObservable(function (o) {
var count = 0;
return source.subscribe(function (value) {
try {
var result = selectorFn(value, count++, source);
} catch (e) {
o.onError(e);
return;
}
o.onNext(result);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} prop The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (prop) {
return this.map(function (x) { return x[prop]; });
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* 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 {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @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, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(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 = observableProto.switchMap = 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 source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* 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,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* 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 RangeError(argumentOutOfRange); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* 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.
* @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 source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* 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 source = this;
predicate = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var count = 0;
return source.subscribe(function (value) {
try {
var shouldRun = predicate(value, count++, source);
} catch (e) {
o.onError(e);
return;
}
shouldRun && o.onNext(value);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* 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 {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, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler() {
var results = arguments;
if (selector) {
try {
results = selector(results);
} catch (err) {
observer.onError(err);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* 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 {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, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
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;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function createListener (element, name, handler) {
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
throw new Error('No listener found');
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* 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) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (!!root.Ember && typeof root.Ember.addListener === 'function') {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
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
*/
var fromEventPattern = 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} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
/**
* 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());
}, source) :
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 && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* 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.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().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 && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* 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.
* @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 && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* 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();
};
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
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) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or 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;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
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);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - 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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* 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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(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);
}
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)
);
}, source);
}
/**
* 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 = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @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) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
(!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted();
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
(!this.enableQueue || this.queue.length === 0) && this.subject.onError(error);
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(value);
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
return this.queue.length !== 0 ?
{ numberOfItems: numberOfItems, returnValue: true } :
{ numberOfItems: numberOfItems, returnValue: false };
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
return autoDetachObserver;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
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 {
!noError && this.dispose();
}
};
AutoDetachObserverPrototype.error = function (err) {
try {
this.observer.onError(err);
} 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 () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
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.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* 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.length = 0;
}
},
/**
* 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.error = error;
this.hasError = true;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* 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);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
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.hasValue = false;
this.observers = [];
this.hasError = false;
}
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 i, len;
checkDisposed.call(this);
if (!this.isStopped) {
this.isStopped = true;
var os = this.observers.slice(0), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (!this.isStopped) {
var os = this.observers.slice(0);
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* 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) { return; }
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));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
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);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* 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.hasError = false;
}
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) { return; }
this.isStopped = true;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* 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) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* 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) { return; }
this.value = value;
for (var i = 0, os = this.observers.slice(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 createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
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.prototype, {
/**
* 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;
},
_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) {
checkDisposed.call(this);
if (this.isStopped) { return; }
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++) {
var 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) {
checkDisposed.call(this);
if (this.isStopped) { return; }
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++) {
var observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
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++) {
var 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));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
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;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
frontend/teg-web-ui/src/common/Loading.js
|
tegh/tegh-daemon
|
import React from 'react'
import classNames from 'classnames'
import Typography from '@mui/material/Typography'
import Fade from '@mui/material/Fade'
import CircularProgress from '@mui/material/CircularProgress'
import LoadingStyles from './LoadingStyles'
const Loading = ({
transitionDelay = 800,
transitionDuration = 600,
className = null,
noText = false,
noSpinner = false,
children = 'Loading...',
fullScreen = false,
...props
}) => {
const classes = LoadingStyles()
return (
<Fade
style={{
transitionDelay: `${transitionDelay}ms`
}}
timeout={ transitionDuration }
in={props.in == null ? true : props.in}
>
<div className={classNames(
classes.root,
fullScreen && classes.fullScreen,
className,
)}>
<div className={classes.row}>
{ !noSpinner && (
<CircularProgress />
)}
{ !noText && (
<Typography variant="h5" className={classes.text}>
{children}
</Typography>
)}
</div>
</div>
</Fade>
)
}
export default Loading
|
node_modules/semantic-ui-react/src/collections/Form/FormDropdown.js
|
jessicaappelbaum/cljs-update
|
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import Dropdown from '../../modules/Dropdown'
import FormField from './FormField'
/**
* Sugar for <Form.Field control={Dropdown} />
* @see Dropdown
* @see Form
*/
function FormDropdown(props) {
const { control } = props
const rest = getUnhandledProps(FormDropdown, props)
const ElementType = getElementType(FormDropdown, props)
return <ElementType {...rest} control={control} />
}
FormDropdown._meta = {
name: 'FormDropdown',
parent: 'Form',
type: META.TYPES.COLLECTION,
}
FormDropdown.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop */
control: FormField.propTypes.control,
}
FormDropdown.defaultProps = {
as: FormField,
control: Dropdown,
}
export default FormDropdown
|
client/index.js
|
yanigisawa/voting-tornado
|
import 'babel-polyfill';
import React from 'react';
import {render} from 'react-dom';
import App from './App';
import {loadEvents} from './actions/eventActions';
// import {loadAuthors} from './actions/authorActions';
import './styles/styles.css';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
// import '../node_modules/bootstrap/dist/js/bootstrap.min.js';
import configureStore from './components/configureStore';
import {Provider} from 'react-redux';
import '../node_modules/toastr/build/toastr.min.css';
import initialState from './reducers/initialState';
const store = configureStore(initialState);
store.dispatch(loadEvents());
// store.dispatch(loadAuthors());
render (
<Provider store={store}>
<App loading={false} />
</Provider>,
document.getElementById('app')
);
|
src/CarouselItem.js
|
omerts/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const CarouselItem = React.createClass({
propTypes: {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
caption: React.PropTypes.node,
index: React.PropTypes.number
},
getInitialState() {
return {
direction: null
};
},
getDefaultProps() {
return {
animation: true
};
},
handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.handleAnimateOutEnd
);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ?
'right' : 'left'
});
},
render() {
let classes = {
item: true,
active: (this.props.active && !this.props.animateIn) || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
{this.props.caption ? this.renderCaption() : null}
</div>
);
},
renderCaption() {
return (
<div className="carousel-caption">
{this.props.caption}
</div>
);
}
});
export default CarouselItem;
|
ajax/libs/rxjs/2.3.7/rx.all.compat.js
|
calvinf/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: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; };
// 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); } }
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = { done: true, value: undefined };
/** `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,
errorProto = Error.prototype,
objectProto = Object.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch(e) {
suportNodeClass = true;
}
var shadowedProps = [
'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf'
];
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
function isObject(value) {
// check if the value is the ECMAScript language type of Object
// http://es5.github.io/#x8
// and avoid a V8 bug
// https://code.google.com/p/v8/issues/detail?id=2291
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
}
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = shadowedProps.length;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = shadowedProps[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
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' || false;
}
// 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) {
// 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 == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// 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 || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
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 initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
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) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// 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;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, 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;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
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 {}.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;
}
old && old.dispose();
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;
}
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;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
ScheduledDisposable.prototype.dispose = function () {
var parent = this;
this.scheduler.schedule(function () {
if (!parent.isDisposed) {
parent.isDisposed = true;
parent.disposable.dispose();
}
});
};
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 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 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);
};
/** 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) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
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 scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* 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 }, invokeRecImmediate);
};
/**
* 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, scheduleInnerRecursive);
};
/**
* 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, scheduleInnerRecursive);
};
/**
* 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');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* 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).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, 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).
*/
Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var s = state;
var id = setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
clearInterval(id);
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions.
* @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.catchError = schedulerProto['catch'] = function (handler) {
return new CatchScheduler(this, handler);
};
}(Scheduler.prototype));
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;
}());
/**
* 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 runTrampoline (q) {
var item;
while (q.length > 0) {
item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
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);
if (!queue) {
queue = new PriorityQueue(4);
queue.enqueue(si);
try {
runTrampoline(queue);
} catch (e) {
throw e;
} finally {
queue = null;
}
} 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; };
currentScheduler.ensureTrampoline = function (action) {
if (!queue) { this.schedule(action); } else { action(); }
};
return currentScheduler;
}());
var scheduleMethod, clearMethod = noop;
(function () {
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;
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;
}
// Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = 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 (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);
})();
/** @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;
}
/**
* 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.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @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.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
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;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var e;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
var currentItem;
if (isDisposed) { return; }
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
observer.onCompleted();
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.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;
try {
e = sources[$iterator$]();
} catch(err) {
observer.onError();
return;
}
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
var currentItem;
try {
currentItem = e.next();
} catch (ex) {
observer.onError(ex);
return;
}
if (currentItem.done) {
if (lastException) {
observer.onError(lastException);
} else {
observer.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.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 (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) {
selector || (selector = identity);
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: selector.call(thisArg, source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* 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());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
/**
* 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.
* @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.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (exception) {
this._onError(exception);
};
/**
* Calls the onCompleted action.
*/
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));
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();
}
ScheduledObserver.prototype.next = function (value) {
var self = this;
this.queue.push(function () {
self.observer.onNext(value);
});
};
ScheduledObserver.prototype.error = function (exception) {
var self = this;
this.queue.push(function () {
self.observer.onError(exception);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
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();
}));
}
};
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 () {
function Observable(subscribe) {
this._subscribe = subscribe;
}
observableProto = Observable.prototype;
/**
* 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 = typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted);
return this._subscribe(subscriber);
};
return Observable;
})();
/**
* 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;
});
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return new AnonymousObservable(function (observer) {
promise.then(
function (value) {
observer.onNext(value);
observer.onCompleted();
},
function (reason) {
observer.onError(reason);
});
return function () {
if (promise && promise.abort) {
promise.abort();
}
}
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) {
throw new Error('Promise type not provided nor in Rx.config.Promise');
}
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, function (err) {
reject(err);
}, function () {
if (hasValue) {
resolve(value);
}
});
});
};
/**
* Creates a list from an observable sequence.
* @returns An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var self = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return self.subscribe(
arr.push.bind(arr),
observer.onError.bind(observer),
function () {
observer.onNext(arr);
observer.onCompleted();
});
});
};
/**
* 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 or Promise.
* @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);
}
isPromise(result) && (result = observableFromPromise(result));
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) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function isIterable(o) {
return o[$iterator$] !== undefined;
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
function isCallable(f) {
return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function';
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isCallable(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var list = Object(iterable),
objIsIterable = isIterable(list),
len = objIsIterable ? 0 : toLength(list),
it = objIsIterable ? list[$iterator$]() : null,
i = 0;
return scheduler.scheduleRecursive(function (self) {
if (i < len || objIsIterable) {
var result;
if (objIsIterable) {
var next = it.next();
if (next.done) {
observer.onCompleted();
return;
}
result = next.value;
} else {
result = list[i];
}
if (mapFn && isCallable(mapFn)) {
try {
result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
i++;
self();
} else {
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) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
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) {
isScheduler(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();
}
});
});
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
var len = arguments.length, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i]; }
return observableFromArray(args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @example
* var res = Rx.Observable.of(1,2,3);
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
var observableOf = Observable.ofWithScheduler = function (scheduler) {
var len = arguments.length - 1, args = new Array(len);
for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; }
return observableFromArray(args, scheduler);
};
/**
* 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) {
isScheduler(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) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and '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 = Observable.just = function (value, scheduler) {
isScheduler(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.throw(new Error('Error'));
* var res = Rx.Observable.throw(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) {
isScheduler(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
* var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; });
* @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 or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @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();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
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 or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @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;
}
isPromise(result) && (result = observableFromPromise(result));
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) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
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 or Promises 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 or Promises 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) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(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);
// Check for promises support
if (isPromise(xs)) { xs = observableFromPromise(xs); }
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);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
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.
* @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]);
* @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++];
isPromise(current) && (current = observableFromPromise(current));
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.
* @param {Observable | Promise} other The observable sequence or Promise 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) {
isOpen && observer.onNext(left);
}, observer.onError.bind(observer), function () {
isOpen && observer.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
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);
// Check if Promise or Observable
if (isPromise(innerSource)) {
innerSource = observableFromPromise(innerSource);
}
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 | Promise} other Observable sequence or Promise 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) {
isPromise(other) && (other = observableFromPromise(other));
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; });
function next(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) {
var source = sources[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
})(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);
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @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 (typeof skip !== 'number') {
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.
* @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.do(observer);
* var res = observable.do(onNext);
* var res = observable.do(onNext, onError);
* var res = observable.do(onNext, onError, onCompleted);
* @param {Function | Observer} 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 = observableProto.tap = 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 (err) {
if (!onError) {
observer.onError(err);
} else {
try {
onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}
}, 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;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
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.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @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.
*
* @example
* var res = source.takeLast(5);
*
* @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.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (observer) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, observer.onError.bind(observer), function () {
while(q.length > 0) { observer.onNext(q.shift()); }
observer.onCompleted();
});
});
};
/**
* 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);
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.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @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 (arguments.length === 1) {
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;
});
};
function concatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).concatAll();
}
/**
* 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.concatMap(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.concatMap(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.concatMap(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 which could be either an observable or Promise.
* @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.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (resultSelector) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
});
}
return typeof selector === 'function' ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = 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();
});
});
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* 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
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
hashSet.push(key) && 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
* var res = 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(); });
* @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} [comparer] Used to determine whether the objects are equal.
* @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, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* 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
* var res = 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(); });
* @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} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @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, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* 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));
});
};
/**
* Retrieves the value of a specified property from all elements in the Observable sequence.
* @param {String} property The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (property) {
return this.select(function (x) { return x[property]; });
};
function flatMap(source, selector, thisArg) {
return source.map(function (x, i) {
var result = selector.call(thisArg, x, i);
return isPromise(result) ? observableFromPromise(result) : result;
}).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 which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @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, thisArg) {
if (resultSelector) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i),
result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult;
return result.map(function (y) {
return resultSelector(x, y, i);
});
}, thisArg);
}
return typeof selector === 'function' ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}).mergeAll();
};
/**
* 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 = observableProto.switchMap = 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));
});
};
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();
}
});
});
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (observer) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
observer.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
observer.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) {
list.push(x);
}
}, observer.onError.bind(observer), function () {
observer.onNext(list);
observer.onCompleted();
});
});
}
function firstOnly(x) {
if (x.length === 0) {
throw new Error(sequenceContainsNoElements);
}
return x[0];
}
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.aggregate(function (acc, x) { return acc + x; });
* 2 - res = source.aggregate(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 a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
var seed, hasSeed, accumulator;
if (arguments.length === 2) {
seed = arguments[0];
hasSeed = true;
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @example
* 1 - res = source.reduce(function (acc, x) { return acc + x; });
* 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0);
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var seed, hasSeed;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue();
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @example
* var result = source.any();
* var result = source.any(function (x) { return x > 3; });
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = observableProto.any = function (predicate, thisArg) {
var source = this;
return predicate ?
source.where(predicate, thisArg).any() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
observer.onNext(false);
observer.onCompleted();
});
});
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
*
* 1 - res = source.all(function (value) { return value.length > 3; });
* @memberOf Observable#
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = observableProto.all = function (predicate, thisArg) {
return this.where(function (v) {
return !predicate(v);
}, thisArg).any().select(function (b) {
return !b;
});
};
/**
* Determines whether an observable sequence contains a specified element with an optional equality comparer.
* @example
* 1 - res = source.contains(42);
* 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; });
* @param value The value to locate in the source sequence.
* @param {Function} [comparer] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value.
*/
observableProto.contains = function (value, comparer) {
comparer || (comparer = defaultComparer);
return this.where(function (v) {
return comparer(v, value);
}).any();
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).count() :
this.aggregate(0, function (count) {
return count + 1;
});
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @example
* var res = source.sum();
* var res = source.sum(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).sum() :
this.aggregate(0, function (prev, curr) {
return prev + curr;
});
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) {
return comparer(x, y) * -1;
});
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).select(function (x) {
return firstOnly(x);
});
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @example
* var res = res = source.average();
* var res = res = source.average(function (x) { return x.value; });
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector ?
this.select(keySelector, thisArg).average() :
this.scan({
sum: 0,
count: 0
}, function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}).finalValue().select(function (s) {
if (s.count === 0) {
throw new Error('The input sequence was empty');
}
return s.sum / s.count;
});
};
function sequenceEqualArray(first, second, comparer) {
return new AnonymousObservable(function (observer) {
var count = 0, len = second.length;
return first.subscribe(function (value) {
var equal = false;
try {
if (count < len) {
equal = comparer(value, second[count++]);
}
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
}, observer.onError.bind(observer), function () {
observer.onNext(count === len);
observer.onCompleted();
});
});
}
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
if (Array.isArray(second)) {
return sequenceEqualArray(first, second, comparer);
}
return new AnonymousObservable(function (observer) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
observer.onError(e);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (doner) {
observer.onNext(false);
observer.onCompleted();
} else {
ql.push(x);
}
}, observer.onError.bind(observer), function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (doner) {
observer.onNext(true);
observer.onCompleted();
}
}
});
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal, v;
if (ql.length > 0) {
v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
observer.onError(exception);
return;
}
if (!equal) {
observer.onNext(false);
observer.onCompleted();
}
} else if (donel) {
observer.onNext(false);
observer.onCompleted();
} else {
qr.push(x);
}
}, observer.onError.bind(observer), function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
observer.onNext(false);
observer.onCompleted();
} else if (donel) {
observer.onNext(true);
observer.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
});
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) {
throw new Error(argumentOutOfRange);
}
return new AnonymousObservable(function (observer) {
var i = index;
return source.subscribe(function (x) {
if (i === 0) {
observer.onNext(x);
observer.onCompleted();
}
i--;
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(argumentOutOfRange));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
observer.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @example
* var res = res = source.single();
* var res = res = source.single(function (x) { return x === 42; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate?
this.where(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue)
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
observer.onNext(x);
observer.onCompleted();
}, observer.onError.bind(observer), function () {
if (!hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(defaultValue);
observer.onCompleted();
}
});
});
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = res = source.firstOrDefault();
* var res = res = source.firstOrDefault(function (x) { return x > 3; });
* var res = source.firstOrDefault(function (x) { return x > 3; }, 0);
* var res = source.firstOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (observer) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, observer.onError.bind(observer), function () {
if (!seenValue && !hasDefault) {
observer.onError(new Error(sequenceContainsNoElements));
} else {
observer.onNext(value);
observer.onCompleted();
}
});
});
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @example
* var res = source.last();
* var res = source.last(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @example
* var res = source.lastOrDefault();
* var res = source.lastOrDefault(function (x) { return x > 3; });
* var res = source.lastOrDefault(function (x) { return x > 3; }, 0);
* var res = source.lastOrDefault(null, 0);
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
return new AnonymousObservable(function (observer) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = predicate.call(thisArg, x, i, source);
} catch(e) {
observer.onError(e);
return;
}
if (shouldRun) {
observer.onNext(yieldIndex ? i : x);
observer.onCompleted();
} else {
i++;
}
}, observer.onError.bind(observer), function () {
observer.onNext(yieldIndex ? -1 : undefined);
observer.onCompleted();
});
});
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var 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, context, scheduler) {
return observableToAsync(func, context, 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
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3);
* var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3);
* var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello');
*
* @param {Function} 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, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
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();
};
};
/**
* 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 {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, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
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 {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, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
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;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
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 = root.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) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
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);
});
}
// 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 (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* 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) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
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
*/
var fromEventPattern = 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();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.subject.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (observer) {
var n = 2,
hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(n);
function next(x, i) {
values[i] = x
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) {
observer.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
observer.onError.bind(observer),
function () {
isDone = true;
observer.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
observer.onError.bind(observer))
);
});
}
var PausableBufferedObservable = (function (_super) {
inherits(PausableBufferedObservable, _super);
function subscribe(observer) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.subject.distinctUntilChanged(),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
observer.onNext(q.shift());
}
}
} else {
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
previousShouldFire = results.shouldFire;
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
observer.onNext(q.shift());
}
observer.onCompleted();
}
);
this.subject.onNext(false);
return subscription;
}
function PausableBufferedObservable(source, subject) {
this.source = source;
this.subject = subject || new Subject();
this.isPaused = true;
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
if (this.isPaused === true){
return;
}
this.isPaused = true;
this.subject.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
if (this.isPaused === false){
return;
}
this.isPaused = false;
this.subject.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var ControlledObservable = (function (_super) {
inherits(ControlledObservable, _super);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
_super.call(this, subscribe);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = Rx.ControlledSubject = (function (_super) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, _super);
function ControlledSubject(enableQueue) {
if (enableQueue == null) {
enableQueue = true;
}
_super.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
checkDisposed.call(this);
this.hasCompleted = true;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onCompleted();
}
},
onError: function (error) {
checkDisposed.call(this);
this.hasFailed = true;
this.error = error;
if (!this.enableQueue || this.queue.length === 0) {
this.subject.onError(error);
}
},
onNext: function (value) {
checkDisposed.call(this);
var hasRequested = false;
if (this.requestedCount === 0) {
if (this.enableQueue) {
this.queue.push(value);
}
} else {
if (this.requestedCount !== -1) {
if (this.requestedCount-- === 0) {
this.disposeCurrentRequest();
}
}
hasRequested = true;
}
if (hasRequested) {
this.subject.onNext(value);
}
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
//console.log('queue length', this.queue.length);
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
//console.log('number of items', numberOfItems);
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
if (this.queue.length !== 0) {
return { numberOfItems: numberOfItems, returnValue: true };
} else {
return { numberOfItems: numberOfItems, returnValue: false };
}
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
checkDisposed.call(this);
this.disposeCurrentRequest();
var self = this,
r = this._processRequest(number);
number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
},
dispose: function () {
this.isDisposed = true;
this.error = null;
this.subject.dispose();
this.requestedDisposable.dispose();
}
});
return ControlledSubject;
}(Observable));
/**
* 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 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 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));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, subject.subscribe.bind(subject));
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if (candidate & 1 === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof obj === 'string') { return stringHashFn(valueOf); }
}
if (obj.getHashCode) { return obj.getHashCode(); }
var id = 17 * uniqueIdCounter++;
obj.getHashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new Error('out of range'); }
if (capacity > 0) { this._initialize(capacity); }
this.comparer = comparer || defaultComparer;
this.freeCount = 0;
this.size = 0;
this.freeList = -1;
}
var dictionaryProto = Dictionary.prototype;
dictionaryProto._initialize = function (capacity) {
var prime = getPrime(capacity), i;
this.buckets = new Array(prime);
this.entries = new Array(prime);
for (i = 0; i < prime; i++) {
this.buckets[i] = -1;
this.entries[i] = newEntry();
}
this.freeList = -1;
};
dictionaryProto.add = function (key, value) {
return this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch(exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
});
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, function () {
return observableEmpty();
}, function (_, window) {
return window;
});
}
function observableWindowWithBounaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var window = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
d.add(windowBoundaries.subscribe(function (w) {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
}, function (err) {
window.onError(err);
observer.onError(err);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
return r;
});
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var createWindowClose,
m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
window = new Subject();
observer.onNext(addRef(window, r));
d.add(source.subscribe(function (x) {
window.onNext(x);
}, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
observer.onCompleted();
}));
createWindowClose = function () {
var m1, windowClose;
try {
windowClose = windowClosingSelector();
} catch (exception) {
observer.onError(exception);
return;
}
m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) {
window.onError(ex);
observer.onError(ex);
}, function () {
window.onCompleted();
window = new Subject();
observer.onNext(addRef(window, r));
createWindowClose();
}));
};
createWindowClose();
return r;
});
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
});
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
var published = this.publish().refCount();
return [
published.filter(predicate, thisArg),
published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector) {
return enumerableFor(sources, resultSelector).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
});
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = argsOrArray(arguments, 0);
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
});
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeObservable().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwException(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = (function () {
/**
* @constructor
* @private
*/
function Map() {
this.keys = [];
this.values = [];
}
/**
* @private
* @memberOf Map#
*/
Map.prototype['delete'] = function (key) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.keys.splice(i, 1);
this.values.splice(i, 1);
}
return i !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.get = function (key, fallback) {
var i = this.keys.indexOf(key);
return i !== -1 ? this.values[i] : fallback;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.set = function (key, value) {
var i = this.keys.indexOf(key);
if (i !== -1) {
this.values[i] = value;
}
this.values[this.keys.push(key) - 1] = value;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.size = function () { return this.keys.length; };
/**
* @private
* @memberOf Map#
*/
Map.prototype.has = function (key) {
return this.keys.indexOf(key) !== -1;
};
/**
* @private
* @memberOf Map#
*/
Map.prototype.getKeys = function () { return this.keys.slice(0); };
/**
* @private
* @memberOf Map#
*/
Map.prototype.getValues = function () { return this.values.slice(0); };
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
*
* @param other Observable sequence to match in addition to the current pattern.
* @return Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
var patterns = this.patterns.slice(0);
patterns.push(other);
return new Pattern(patterns);
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
*
* @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (exception) {
observer.onError(exception);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
// Active Plan
function ActivePlan(joinObserverArray, onNext, onCompleted) {
var i, joinObserver;
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (i = 0; i < this.joinObserverArray.length; i++) {
joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
var values = this.joinObservers.getValues();
for (var i = 0, len = values.length; i < len; i++) {
values[i].queue.shift();
}
};
ActivePlan.prototype.match = function () {
var firstValues, i, len, isCompleted, values, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
firstValues = [];
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
if (this.joinObserverArray[i].queue[0].kind === 'C') {
isCompleted = true;
}
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
values = [];
for (i = 0; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
/** @private */
var JoinObserver = (function (_super) {
inherits(JoinObserver, _super);
/**
* @constructor
* @private
*/
function JoinObserver(source, onError) {
_super.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
this.onError(notification.exception);
return;
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.error = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.completed = noop;
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.removeActivePlan = function (activePlan) {
var idx = this.activePlans.indexOf(activePlan);
this.activePlans.splice(idx, 1);
if (this.activePlans.length === 0) {
this.dispose();
}
};
/**
* @memberOf JoinObserver#
* @private
*/
JoinObserverPrototype.dispose = function () {
_super.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var plans = argsOrArray(arguments, 0);
return new AnonymousObservable(function (observer) {
var activePlans = [],
externalSubscriptions = new Map(),
group,
i, len,
joinObserver,
joinValues,
outObserver;
outObserver = observerCreate(observer.onNext.bind(observer), function (exception) {
var values = externalSubscriptions.getValues();
for (var j = 0, jlen = values.length; j < jlen; j++) {
values[j].onError(exception);
}
observer.onError(exception);
}, observer.onCompleted.bind(observer));
try {
for (i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
if (activePlans.length === 0) {
outObserver.onCompleted();
}
}));
}
} catch (e) {
observableThrow(e).subscribe(observer);
}
group = new CompositeDisposable();
joinValues = externalSubscriptions.getValues();
for (i = 0, len = joinValues.length; i < len; i++) {
joinObserver = joinValues[i];
joinObserver.subscribe();
group.add(joinObserver);
}
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var count = 0, d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsolute(d, function (self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count++);
self(d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
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) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
*
* @example
* 1 - res = Rx.Observable.timer(new Date());
* 2 - res = Rx.Observable.timer(new Date(), 1000);
* 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout);
*
* 5 - res = Rx.Observable.timer(5000);
* 6 - res = Rx.Observable.timer(5000, 1000);
* 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout);
* 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout);
*
* @param {Number} dueTime Absolute (specified as a Date object) or 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;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
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);
});
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - 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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* 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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); })
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
*
* @example
* 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (typeof timeShiftOrScheduler === 'object') {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(function (x) {
var i, len;
for (i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
}, function (e) {
var i, len;
for (i = 0, len = q.length; i < len; i++) {
q[i].onError(e);
}
observer.onError(e);
}, function () {
var i, len;
for (i = 0, len = q.length; i < len; i++) {
q[i].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
function createTimer () {
var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
isSpan && (nextSpan += timeShift);
isShift && (nextShift += timeShift);
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
var s;
if (isShift) {
s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
if (isSpan) {
s = q.shift();
s.onCompleted();
}
createTimer();
}));
}
});
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @example
* 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items
* 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items
*
* @memberOf Observable#
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var createTimer,
groupDisposable,
n = 0,
refCountDisposable,
s = new Subject()
timerD = new SerialDisposable(),
windowId = 0;
groupDisposable = new CompositeDisposable(timerD);
refCountDisposable = new RefCountDisposable(groupDisposable);
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
n++;
if (n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
}, function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}));
return refCountDisposable;
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
var newId;
if (id !== windowId) { return; }
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* 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;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(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);
}
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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
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) {
other || (other = observableThrow(new Error('Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
var createTimer = function () {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
};
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
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.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @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 Date values.
* @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.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
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();
}
});
});
};
/**
* 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.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
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) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), 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) {
isScheduler(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} [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 end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(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();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) {
observer.onNext(next.value);
}
}
observer.onCompleted();
});
});
};
/**
* 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;
isScheduler(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;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), 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;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
});
};
/**
* 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]);
* 2 - res = source.skipUntilWithTime(5000, [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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && observer.onNext(x); },
observer.onError.bind(observer),
observer.onCompleted.bind(observer)));
});
};
/**
* 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]);
* 2 - res = source.takeUntilWithTime(5000, [optional scheduler]);
* @param {Number | Date} 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) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () {
observer.onCompleted();
}), source.subscribe(observer));
});
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
});
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this;
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selector.call(thisArg, x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
});
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function notImplemented() {
throw new Error('Not implemented');
}
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;
/**
* Adds a relative time value to an absolute time value.
* @param {Number} absolute Absolute virtual time value.
* @param {Number} relative Relative virtual time value to add.
* @return {Number} Resulting absolute virtual time sum value.
*/
VirtualTimeSchedulerPrototype.add = notImplemented;
/**
* Converts an absolute time to a number
* @param {Any} The absolute time.
* @returns {Number} The absolute time in ms
*/
VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented;
/**
* Converts the TimeSpan value to a relative virtual time value.
* @param {Number} timeSpan TimeSpan value to convert.
* @return {Number} Corresponding relative virtual time value.
*/
VirtualTimeSchedulerPrototype.toRelative = notImplemented;
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling.
* @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.
* @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.
* @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.
*/
VirtualTimeSchedulerPrototype.start = function () {
if (!this.isEnabled) {
this.isEnabled = true;
do {
var next = this.getNext();
if (next !== null) {
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.
*/
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 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 {
var next = this.getNext();
if (next !== null && this.comparer(next.dueTime, time) <= 0) {
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.
* @param {Number} time Relative time to advance the scheduler's clock by.
*/
VirtualTimeSchedulerPrototype.advanceBy = function (time) {
var dt = this.add(this.clock, time),
dueToClock = this.comparer(this.clock, dt);
if (dueToClock > 0) { throw new Error(argumentOutOfRange); }
if (dueToClock === 0) { return; }
this.advanceTo(dt);
};
/**
* Advances the scheduler's clock by the specified relative time.
* @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.
* @returns {ScheduledItem} The next scheduled item.
*/
VirtualTimeSchedulerPrototype.getNext = function () {
while (this.queue.length > 0) {
var next = this.queue.peek();
if (next.isCancelled()) {
this.queue.dequeue();
} else {
return next;
}
}
return null;
};
/**
* Schedules an action to be executed at dueTime.
* @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.
* @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;
function run(scheduler, state1) {
self.queue.remove(si);
return action(scheduler, state1);
}
var si = new ScheduledItem(this, state, run, dueTime, this.comparer);
this.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.
* @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;
};
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 AnonymousObservable = Rx.AnonymousObservable = (function (__super__) {
inherits(AnonymousObservable, __super__);
// Fix subscriber to check for undefined or function returned to decorate as Disposable
function fixSubscriber(subscriber) {
if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; }
return typeof subscriber === 'function' ?
disposableCreate(subscriber) :
disposableEmpty;
}
function AnonymousObservable(subscribe) {
if (!(this instanceof AnonymousObservable)) {
return new AnonymousObservable(subscribe);
}
function s(observer) {
var setDisposable = function () {
try {
autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver)));
} catch (e) {
if (!autoDetachObserver.fail(e)) {
throw e;
}
}
};
var autoDetachObserver = new AutoDetachObserver(observer);
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.schedule(setDisposable);
} else {
setDisposable();
}
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 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));
/**
* 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) {
this.isStopped = true;
var os = this.observers.slice(0),
v = this.value,
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));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, this.observable.subscribe.bind(this.observable));
}
addProperties(AnonymousSubject.prototype, Observer, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (exception) {
this.observer.onError(exception);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(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));
|
docs/tutorial/DO_NOT_TOUCH/01/src/components/App/index.js
|
FWeinb/cerebral
|
import React from 'react'
export default function App (props) {
return (
<div className='o-container o-container--medium'>
<h1>Welcome to the tutorial!</h1>
</div>
)
}
|
src/components/common/NoNavBarSpacer.js
|
bitmoremedia/mygi-app
|
import React from 'react';
import {
View,
StyleSheet,
Platform,
} from 'react-native';
import * as colors from '../../config/colors';
const NoNavBarSpacer = ({ children }) => {
if (Platform.OS === 'ios') {
return (
<View style={styles.container}>
<View style={styles.header} />
{children}
</View>
);
}
return (
<View style={styles.container}>
{ children }
</View>
);
};
export default NoNavBarSpacer;
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 22,
backgroundColor: colors.main,
}
});
|
examples/04 Sortable/Cancel on Drop Outside/index.js
|
hiddentao/react-dnd
|
import React from 'react';
import Container from './Container';
export default class SortableCancelOnDropOutside {
render() {
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/04%20Sortable/Cancel%20on%20Drop%20Outside'>Browse the Source</a></b>
</p>
<p>
Because you write the logic instead of using the readymade components, you can tweak the behavior to the one your app needs.
In this example, instead of moving the card inside the drop target's <code>drop()</code> handler, we do it inside the drag source's <code>endDrag()</code> handler. This let us check <code>monitor.didDrop()</code> and revert the drag operation if the card was dropped outside its container.
</p>
<Container />
</div>
);
}
}
|
gatsby-ssr.js
|
eventjuicer/homepage
|
import React from 'react';
import { renderToString } from 'react-dom/server';
import { JssProvider } from 'react-jss';
import createContext from "./src/styles/createContext";
import { MuiThemeProvider } from 'material-ui/styles';
exports.replaceRenderer = ({
bodyComponent,
replaceBodyHTMLString,
setHeadComponents,
}) => {
const context = createContext();
const bodyHTML = renderToString(
<JssProvider registry={context.sheetsRegistry} jss={context.jss}>
<MuiThemeProvider sheetsManager={ context.sheetsManager }>
{bodyComponent}
</MuiThemeProvider>
</JssProvider>
);
replaceBodyHTMLString(bodyHTML);
const css = context.sheetsRegistry.toString();
setHeadComponents([
<style
type="text/css"
id="server-side-jss"
key="server-side-jss"
dangerouslySetInnerHTML={{ __html: css }}
/>,
]);
};
|
src/icons/IosVolumeLow.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosVolumeLow extends React.Component {
render() {
if(this.props.bare) {
return <g>
<polygon points="249.9,216 192,216 192,296 249.9,296 320,352 320,160 "></polygon>
</g>;
} return <IconBase>
<polygon points="249.9,216 192,216 192,296 249.9,296 320,352 320,160 "></polygon>
</IconBase>;
}
};IosVolumeLow.defaultProps = {bare: false}
|
app/javascript/mastodon/components/collapsable.js
|
h-izumi/mastodon
|
import React from 'react';
import Motion from 'react-motion/lib/Motion';
import spring from 'react-motion/lib/spring';
import PropTypes from 'prop-types';
const Collapsable = ({ fullHeight, isVisible, children }) => (
<Motion defaultStyle={{ opacity: !isVisible ? 0 : 100, height: isVisible ? fullHeight : 0 }} style={{ opacity: spring(!isVisible ? 0 : 100), height: spring(!isVisible ? 0 : fullHeight) }}>
{({ opacity, height }) =>
<div style={{ height: `${height}px`, overflow: 'hidden', opacity: opacity / 100, display: Math.floor(opacity) === 0 ? 'none' : 'block' }}>
{children}
</div>
}
</Motion>
);
Collapsable.propTypes = {
fullHeight: PropTypes.number.isRequired,
isVisible: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
};
export default Collapsable;
|
examples/src/components/ValuesAsNumbersField.js
|
aldeka/react-select
|
import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var ValuesAsNumbersField = React.createClass({
displayName: 'ValuesAsNumbersField',
propTypes: {
label: React.PropTypes.string
},
getInitialState () {
return {
options: [
{ value: 10, label: 'Ten' },
{ value: 11, label: 'Eleven' },
{ value: 12, label: 'Twelve' },
{ value: 23, label: 'Twenty-three' },
{ value: 24, label: 'Twenty-four' }
],
matchPos: 'any',
matchValue: true,
matchLabel: true,
value: null,
multi: false
};
},
onChangeMatchStart(event) {
this.setState({
matchPos: event.target.checked ? 'start' : 'any'
});
},
onChangeMatchValue(event) {
this.setState({
matchValue: event.target.checked
});
},
onChangeMatchLabel(event) {
this.setState({
matchLabel: event.target.checked
});
},
onChange(value, values) {
this.setState({
value: value
});
logChange(value, values);
},
onChangeMulti(event) {
this.setState({
multi: event.target.checked
});
},
render () {
var matchProp = 'any';
if (this.state.matchLabel && !this.state.matchValue) {
matchProp = 'label';
}
if (!this.state.matchLabel && this.state.matchValue) {
matchProp = 'value';
}
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
searchable={true}
matchProp={matchProp}
matchPos={this.state.matchPos}
options={this.state.options}
onChange={this.onChange}
value={this.state.value}
multi={this.state.multi}
/>
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} />
<span className="checkbox-label">Multi-Select</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchValue} onChange={this.onChangeMatchValue} />
<span className="checkbox-label">Match value only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchLabel} onChange={this.onChangeMatchLabel} />
<span className="checkbox-label">Match label only</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchPos === 'start'} onChange={this.onChangeMatchStart} />
<span className="checkbox-label">Only include matches from the start of the string</span>
</label>
</div>
</div>
);
}
});
module.exports = ValuesAsNumbersField;
|
src/svg-icons/image/photo-size-select-actual.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoSizeSelectActual = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3C2 3 1 4 1 5v14c0 1.1.9 2 2 2h18c1 0 2-1 2-2V5c0-1-1-2-2-2zM5 17l3.5-4.5 2.5 3.01L14.5 11l4.5 6H5z"/>
</SvgIcon>
);
ImagePhotoSizeSelectActual = pure(ImagePhotoSizeSelectActual);
ImagePhotoSizeSelectActual.displayName = 'ImagePhotoSizeSelectActual';
ImagePhotoSizeSelectActual.muiName = 'SvgIcon';
export default ImagePhotoSizeSelectActual;
|
ajax/libs/F2/1.3.3/f2.js
|
Rbeuque74/cdnjs
|
;(function(exports) {
if (exports.F2 && !exports.F2_TESTING_MODE) {
return;
}
/*!
JSON.org requires the following notice to accompany json2:
Copyright (c) 2002 JSON.org
http://json.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 shall be used for Good, not Evil.
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.
*/
/*
This code should be minified before deployment.
See http://javascript.crockford.com/jsmin.html
USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO
NOT CONTROL.
This file creates a global JSON object containing two methods: stringify
and parse.
JSON.stringify(value, replacer, space)
value any JavaScript value, usually an object or array.
replacer an optional parameter that determines how object
values are stringified for objects. It can be a
function or an array of strings.
space an optional parameter that specifies the indentation
of nested structures. If it is omitted, the text will
be packed without extra whitespace. If it is a number,
it will specify the number of spaces to indent at each
level. If it is a string (such as '\t' or ' '),
it contains the characters used to indent at each level.
This method produces a JSON text from a JavaScript value.
When an object value is found, if the object contains a toJSON
method, its toJSON method will be called and the result will be
stringified. A toJSON method does not serialize: it returns the
value represented by the name/value pair that should be serialized,
or undefined if nothing should be serialized. The toJSON method
will be passed the key associated with the value, and this will be
bound to the value
For example, this would serialize Dates as ISO strings.
Date.prototype.toJSON = function (key) {
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
return this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z';
};
You can provide an optional replacer method. It will be passed the
key and value of each member, with this bound to the containing
object. The value that is returned from your method will be
serialized. If your method returns undefined, then the member will
be excluded from the serialization.
If the replacer parameter is an array of strings, then it will be
used to select the members to be serialized. It filters the results
such that only members with keys listed in the replacer array are
stringified.
Values that do not have JSON representations, such as undefined or
functions, will not be serialized. Such values in objects will be
dropped; in arrays they will be replaced with null. You can use
a replacer function to replace those with JSON values.
JSON.stringify(undefined) returns undefined.
The optional space parameter produces a stringification of the
value that is filled with line breaks and indentation to make it
easier to read.
If the space parameter is a non-empty string, then that string will
be used for indentation. If the space parameter is a number, then
the indentation will be that many spaces.
Example:
text = JSON.stringify(['e', {pluribus: 'unum'}]);
// text is '["e",{"pluribus":"unum"}]'
text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t');
// text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]'
text = JSON.stringify([new Date()], function (key, value) {
return this[key] instanceof Date ?
'Date(' + this[key] + ')' : value;
});
// text is '["Date(---current time---)"]'
JSON.parse(text, reviver)
This method parses a JSON text to produce an object or array.
It can throw a SyntaxError exception.
The optional reviver parameter is a function that can filter and
transform the results. It receives each of the keys and values,
and its return value is used instead of the original value.
If it returns what it received, then the structure is not modified.
If it returns undefined then the member is deleted.
Example:
// Parse the text. Values that look like ISO date strings will
// be converted to Date objects.
myData = JSON.parse(text, function (key, value) {
var a;
if (typeof value === 'string') {
a =
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);
if (a) {
return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4],
+a[5], +a[6]));
}
}
return value;
});
myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) {
var d;
if (typeof value === 'string' &&
value.slice(0, 5) === 'Date(' &&
value.slice(-1) === ')') {
d = new Date(value.slice(5, -1));
if (d) {
return d;
}
}
return value;
});
This is a reference implementation. You are free to copy, modify, or
redistribute.
*/
/*jslint evil: true, regexp: true */
/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply,
call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours,
getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join,
lastIndex, length, parse, prototype, push, replace, slice, stringify,
test, toJSON, toString, valueOf
*/
// Create a JSON object only if one does not already exist. We create the
// methods in a closure to avoid creating global variables.
if (typeof JSON !== 'object') {
JSON = {};
}
(function () {
'use strict';
function f(n) {
// Format integers to have at least two digits.
return n < 10 ? '0' + n : n;
}
if (typeof Date.prototype.toJSON !== 'function') {
Date.prototype.toJSON = function (key) {
return isFinite(this.valueOf())
? this.getUTCFullYear() + '-' +
f(this.getUTCMonth() + 1) + '-' +
f(this.getUTCDate()) + 'T' +
f(this.getUTCHours()) + ':' +
f(this.getUTCMinutes()) + ':' +
f(this.getUTCSeconds()) + 'Z'
: null;
};
String.prototype.toJSON =
Number.prototype.toJSON =
Boolean.prototype.toJSON = function (key) {
return this.valueOf();
};
}
var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
gap,
indent,
meta = { // table of character substitutions
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
},
rep;
function quote(string) {
// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can safely slap some quotes around it.
// Otherwise we must also replace the offending characters with safe escape
// sequences.
escapable.lastIndex = 0;
return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
var c = meta[a];
return typeof c === 'string'
? c
: '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"' : '"' + string + '"';
}
function str(key, holder) {
// Produce a string from holder[key].
var i, // The loop counter.
k, // The member key.
v, // The member value.
length,
mind = gap,
partial,
value = holder[key];
// If the value has a toJSON method, call it to obtain a replacement value.
if (value && typeof value === 'object' &&
typeof value.toJSON === 'function') {
value = value.toJSON(key);
}
// If we were called with a replacer function, then call the replacer to
// obtain a replacement value.
if (typeof rep === 'function') {
value = rep.call(holder, key, value);
}
// What happens next depends on the value's type.
switch (typeof value) {
case 'string':
return quote(value);
case 'number':
// JSON numbers must be finite. Encode non-finite numbers as null.
return isFinite(value) ? String(value) : 'null';
case 'boolean':
case 'null':
// If the value is a boolean or null, convert it to a string. Note:
// typeof null does not produce 'null'. The case is included here in
// the remote chance that this gets fixed someday.
return String(value);
// If the type is 'object', we might be dealing with an object or an array or
// null.
case 'object':
// Due to a specification blunder in ECMAScript, typeof null is 'object',
// so watch out for that case.
if (!value) {
return 'null';
}
// Make an array to hold the partial results of stringifying this object value.
gap += indent;
partial = [];
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
// The value is an array. Stringify every element. Use null as a placeholder
// for non-JSON values.
length = value.length;
for (i = 0; i < length; i += 1) {
partial[i] = str(i, value) || 'null';
}
// Join all of the elements together, separated with commas, and wrap them in
// brackets.
v = partial.length === 0
? '[]'
: gap
? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']'
: '[' + partial.join(',') + ']';
gap = mind;
return v;
}
// If the replacer is an array, use it to select the members to be stringified.
if (rep && typeof rep === 'object') {
length = rep.length;
for (i = 0; i < length; i += 1) {
if (typeof rep[i] === 'string') {
k = rep[i];
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
} else {
// Otherwise, iterate through all of the keys in the object.
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = str(k, value);
if (v) {
partial.push(quote(k) + (gap ? ': ' : ':') + v);
}
}
}
}
// Join all of the member texts together, separated with commas,
// and wrap them in braces.
v = partial.length === 0
? '{}'
: gap
? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}'
: '{' + partial.join(',') + '}';
gap = mind;
return v;
}
}
// If the JSON object does not yet have a stringify method, give it one.
if (typeof JSON.stringify !== 'function') {
JSON.stringify = function (value, replacer, space) {
// The stringify method takes a value and an optional replacer, and an optional
// space parameter, and returns a JSON text. The replacer can be a function
// that can replace values, or an array of strings that will select the keys.
// A default replacer method can be provided. Use of the space parameter can
// produce text that is more easily readable.
var i;
gap = '';
indent = '';
// If the space parameter is a number, make an indent string containing that
// many spaces.
if (typeof space === 'number') {
for (i = 0; i < space; i += 1) {
indent += ' ';
}
// If the space parameter is a string, it will be used as the indent string.
} else if (typeof space === 'string') {
indent = space;
}
// If there is a replacer, it must be a function or an array.
// Otherwise, throw an error.
rep = replacer;
if (replacer && typeof replacer !== 'function' &&
(typeof replacer !== 'object' ||
typeof replacer.length !== 'number')) {
throw new Error('JSON.stringify');
}
// Make a fake root object containing our value under the key of ''.
// Return the result of stringifying the value.
return str('', {'': value});
};
}
// If the JSON object does not yet have a parse method, give it one.
if (typeof JSON.parse !== 'function') {
JSON.parse = function (text, reviver) {
// The parse method takes a text and an optional reviver function, and returns
// a JavaScript value if the text is a valid JSON text.
var j;
function walk(holder, key) {
// The walk method is used to recursively walk the resulting structure so
// that modifications can be made.
var k, v, value = holder[key];
if (value && typeof value === 'object') {
for (k in value) {
if (Object.prototype.hasOwnProperty.call(value, k)) {
v = walk(value, k);
if (v !== undefined) {
value[k] = v;
} else {
delete value[k];
}
}
}
}
return reviver.call(holder, key, value);
}
// Parsing happens in four stages. In the first stage, we replace certain
// Unicode characters with escape sequences. JavaScript handles many characters
// incorrectly, either silently deleting them, or treating them as line endings.
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.
// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.
j = eval('(' + text + ')');
// In the optional fourth stage, we recursively walk the new structure, passing
// each name/value pair to a reviver function for possible transformation.
return typeof reviver === 'function'
? walk({'': j}, '')
: j;
}
// If the text is not JSON parseable, then a SyntaxError is thrown.
throw new SyntaxError('JSON.parse');
};
}
}());
/*!
* jQuery JavaScript Library v1.8.3
* The jQuery Foundation and other contributors require the following notice to accompany jQuery:
*
* Copyright (c) 2013 jQuery Foundation and other contributors
*
* http://jquery.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
* is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.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%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
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( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
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( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.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( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var cachedruns,
assertGetIdNotName,
Expr,
getText,
isXML,
contains,
compile,
sortOrder,
hasDuplicate,
outermostContext,
baseHasDuplicate = true,
strundefined = "undefined",
expando = ( "sizcache" + Math.random() ).replace( ".", "" ),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
// Use a stripped-down indexOf if a native one is unavailable
indexOf = [].indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Augment a function for special use by Sizzle
markFunction = function( fn, value ) {
fn[ expando ] = value == null || value;
return fn;
},
createCache = function() {
var cache = {},
keys = [];
return markFunction(function( key, value ) {
// Only keep the most recent entries
if ( keys.push( key ) > Expr.cacheLength ) {
delete cache[ keys.shift() ];
}
// Retrieve with (key + " ") to avoid collision with native Object.prototype properties (see Issue #157)
return (cache[ key + " " ] = value);
}, cache );
},
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// Regex
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier (http://www.w3.org/TR/css3-selectors/#attribute-selectors)
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments not in parens/brackets,
// then attribute selectors and non-pseudos (denoted by :),
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
// For matchExpr.POS and matchExpr.needsContext
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace +
"*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"POS": new RegExp( pos, "i" ),
"CHILD": new RegExp( "^:(only|nth|first|last)-child(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|" + pos, "i" )
},
// Support
// Used for testing something on an element
assert = function( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
},
// Check if getElementsByTagName("*") returns only elements
assertTagNameNoComments = assert(function( div ) {
div.appendChild( document.createComment("") );
return !div.getElementsByTagName("*").length;
}),
// Check if getAttribute returns normalized href attributes
assertHrefNotNormalized = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}),
// Check if attributes should be retrieved by attribute nodes
assertAttributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
}),
// Check if getElementsByClassName can be trusted
assertUsableClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
}),
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
assertUsableName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = document.getElementsByName &&
// buggy browsers will return fewer than the correct 2
document.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
document.getElementsByName( expando + 0 ).length;
assertGetIdNotName = !document.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// If slice is not available, provide a backup
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
function Sizzle( selector, context, results, seed ) {
results = results || [];
context = context || document;
var match, elem, xml, m,
nodeType = context.nodeType;
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( nodeType !== 1 && nodeType !== 9 ) {
return [];
}
xml = isXML( context );
if ( !xml && !seed ) {
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && assertUsableClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed, xml );
}
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
} else {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
}
return ret;
};
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Element contains another
contains = Sizzle.contains = docElem.contains ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && adown.contains && adown.contains(bup) );
} :
docElem.compareDocumentPosition ?
function( a, b ) {
return b && !!( a.compareDocumentPosition( b ) & 16 );
} :
function( a, b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
return false;
};
Sizzle.attr = function( elem, name ) {
var val,
xml = isXML( elem );
if ( !xml ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( xml || assertAttributes ) {
return elem.getAttribute( name );
}
val = elem.getAttributeNode( name );
return val ?
typeof elem[ name ] === "boolean" ?
elem[ name ] ? name : null :
val.specified ? val.value : null :
null;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
// IE6/7 return a modified href
attrHandle: assertHrefNotNormalized ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ?
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
} :
function( id, context, xml ) {
if ( typeof context.getElementById !== strundefined && !xml ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
},
"TAG": assertTagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
var elem,
tmp = [],
i = 0;
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
},
"CLASS": assertUsableClassName && function( className, context, xml ) {
if ( typeof context.getElementsByClassName !== strundefined && !xml ) {
return context.getElementsByClassName( className );
}
}
},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( rbackslash, "" );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( rbackslash, "" );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
3 xn-component of xn+y argument ([+-]?\d*n|)
4 sign of xn-component
5 x of xn-component
6 sign of y-component
7 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1] === "nth" ) {
// nth-child requires argument
if ( !match[2] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[3] = +( match[3] ? match[4] + (match[5] || 1) : 2 * ( match[2] === "even" || match[2] === "odd" ) );
match[4] = +( ( match[6] + match[7] ) || match[2] === "odd" );
// other types prohibit arguments
} else if ( match[2] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var unquoted, excess;
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
if ( match[3] ) {
match[2] = match[3];
} else if ( (unquoted = match[4]) ) {
// Only check arguments that contain a pseudo
if ( rpseudo.test(unquoted) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
unquoted = unquoted.slice( 0, excess );
match[0] = match[0].slice( 0, excess );
}
match[2] = unquoted;
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"ID": assertGetIdNotName ?
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
return elem.getAttribute("id") === id;
};
} :
function( id ) {
id = id.replace( rbackslash, "" );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( rbackslash, "" ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ expando ][ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem, context ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, argument, first, last ) {
if ( type === "nth" ) {
return function( elem ) {
var node, diff,
parent = elem.parentNode;
if ( first === 1 && last === 0 ) {
return true;
}
if ( parent ) {
diff = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
diff++;
if ( elem === node ) {
break;
}
}
}
}
// Incorporate the offset (or cast to NaN), then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
};
}
return function( elem ) {
var node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
var nodeType;
elem = elem.firstChild;
while ( elem ) {
if ( elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4 ) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"text": function( elem ) {
var type, attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
(type = elem.type) === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type );
},
// Input types
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"focus": function( elem ) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
"active": function( elem ) {
return elem === elem.ownerDocument.activeElement;
},
// Positional types
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 0; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
for ( var i = 1; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
for ( var i = argument < 0 ? argument + length : argument; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
function siblingCheck( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
return ( !a.compareDocumentPosition || !b.compareDocumentPosition ?
a.compareDocumentPosition :
a.compareDocumentPosition(b) & 4
) ? -1 : 1;
} :
function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
[0, 0].sort( sortOrder );
baseHasDuplicate = !hasDuplicate;
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ expando ][ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
// Cast descendant combinators to space
matched.type = match[0].replace( rtrim, " " );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
tokens.push( matched = new Token( match.shift() ) );
soFar = soFar.slice( matched.length );
matched.type = type;
matched.matches = match;
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( !xml ) {
var cache,
dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( (cache = elem[ expando ]) === cachedkey ) {
return elem.sizset;
} else if ( typeof cache === "string" && cache.indexOf(dirkey) === 0 ) {
if ( elem.sizset ) {
return elem;
}
} else {
elem[ expando ] = cachedkey;
if ( matcher( elem, context, xml ) ) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( checkNonElements || elem.nodeType === 1 ) {
if ( matcher( elem, context, xml ) ) {
return elem;
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && tokens.slice( 0, i - 1 ).join("").replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && tokens.join("")
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ expando ][ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed, xml ) {
var i, tokens, token, type, find,
match = tokenize( selector ),
j = match.length;
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !xml &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( rbackslash, "" ), context, xml )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["POS"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( rbackslash, "" ),
rsibling.test( tokens[0].type ) && context.parentNode || context,
xml
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && tokens.join("");
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
xml,
results,
rsibling.test( selector )
);
return results;
}
if ( document.querySelectorAll ) {
(function() {
var disconnectedMatch,
oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// qSa(:focus) reports false when true (Chrome 21), no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ],
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
// A support test would require too much code (would include document ready)
// just skip matchesSelector for :active
rbuggyMatches = [ ":active" ],
matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector;
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here (do not put tests after this one)
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE9 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<p test=''></p>";
if ( div.querySelectorAll("[test^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here (do not put tests after this one)
div.innerHTML = "<input type='hidden'/>";
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
// rbuggyQSA always contains :focus, so no need for a length check
rbuggyQSA = /* rbuggyQSA.length && */ new RegExp( rbuggyQSA.join("|") );
select = function( selector, context, results, seed, xml ) {
// Only use querySelectorAll when not filtering,
// when this is not xml,
// and when no QSA bugs apply
if ( !seed && !xml && !rbuggyQSA.test( selector ) ) {
var groups, i,
old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + groups[i].join("");
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
return oldSelect( selector, context, results, seed, xml );
};
if ( matches ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
try {
matches.call( div, "[test!='']:sizzle" );
rbuggyMatches.push( "!=", pseudos );
} catch ( e ) {}
});
// rbuggyMatches always contains :active and :focus, so no need for a length check
rbuggyMatches = /* rbuggyMatches.length && */ new RegExp( rbuggyMatches.join("|") );
Sizzle.matchesSelector = function( elem, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyMatches always contains :active, so no need for an existence check
if ( !isXML( elem ) && !rbuggyMatches.test( expr ) && !rbuggyQSA.test( expr ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, null, null, [ elem ] ).length > 0;
};
}
})();
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Back-compat
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
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, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, numeric, extra ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore,
dataTypes = dataTypeExpression.toLowerCase().split( core_rspace ),
i = 0,
length = dataTypes.length;
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var selection,
list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters );
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
// Don't do a request if no elements are being requested
if ( !this.length ) {
return this;
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// Request the remote document
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params,
complete: function( jqXHR, status ) {
if ( callback ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
}
}
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append( responseText.replace( rscript, "" ) )
// Locate the specified elements
.find( selector ) :
// If not, just inject the full result
responseText );
});
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // ifModified key
ifModifiedKey,
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || strAbort;
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ ifModifiedKey ] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if ( modified ) {
jQuery.etag[ ifModifiedKey ] = modified;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
isSuccess = ajaxConvert( s, response );
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.always( tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( core_rspace );
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
var conv, conv2, current, tmp,
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice(),
prev = dataTypes[ 0 ],
converters = {},
i = 0;
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
// Convert to each sequential dataType, tolerating list modification
for ( ; (current = dataTypes[++i]); ) {
// There's only work to do if current dataType is non-auto
if ( current !== "*" ) {
// Convert response if prev dataType is non-auto and differs from current
if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split(" ");
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.splice( i--, 0, current );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s["throws"] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
// Update prev for next iteration
prev = current;
}
}
return { state: "success", data: response };
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test( url ),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" &&
!( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") &&
rjsonp.test( data );
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( s.dataTypes[ 0 ] === "jsonp" || replaceInUrl || replaceInData ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
overwritten = window[ callbackName ];
// Insert callback into url or form data
if ( replaceInUrl ) {
s.url = url.replace( rjsonp, "$1" + callbackName );
} else if ( replaceInData ) {
s.data = data.replace( rjsonp, "$1" + callbackName );
} else if ( hasCallback ) {
s.url += ( rquestion.test( url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var xhrCallbacks,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( e ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback, 0 );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var end, unit,
tween = this.createTween( prop, value ),
parts = rfxnum.exec( value ),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if ( parts ) {
end = +parts[2];
unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" && start ) {
// Iteratively approximate from a nonzero starting point
// Prefer the current property, because this process will be trivial if it uses the same units
// Fallback to end or a simple constant
start = jQuery.css( tween.elem, prop, true ) || end || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
tween.unit = unit;
tween.start = start;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end;
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0 );
return ( fxNow = jQuery.now() );
}
function createTweens( animation, props ) {
jQuery.each( props, function( prop, value ) {
var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( collection[ index ].call( animation, prop, value ) ) {
// we're done with this property
return;
}
}
});
}
function Animation( elem, properties, options ) {
var result,
index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end, easing ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
createTweens( animation, props );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
var index, prop, value, length, dataShow, toggle, tween, hooks, oldfire,
anim = this,
style = elem.style,
orig = {},
handled = [],
hidden = elem.nodeType && isHidden( elem );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.done(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( index in props ) {
value = props[ index ];
if ( rfxtypes.exec( value ) ) {
delete props[ index ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
handled.push( index );
}
}
length = handled.length;
if ( length ) {
dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} );
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData( elem, "fxshow", true );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( index = 0 ; index < length ; index++ ) {
prop = handled[ index ];
tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 );
orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing any value as a 4th parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, false, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Remove in 2.0 - this supports IE8's panic based approach
// to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ||
// special check for .toggle( handler, handler, ... )
( !i && jQuery.isFunction( speed ) && jQuery.isFunction( easing ) ) ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations resolve immediately
if ( empty ) {
anim.stop( true );
}
};
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) && !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, value, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/*! =========================================================
* bootstrap-modal.js v2.2.2
* http://twitter.github.com/bootstrap/javascript.html#modals
* =========================================================
* Twitter, Inc. require the following notice to accompany Bootstrap:
*
* Copyright (c) 2012 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this work
* except in compliance with the License. You may obtain a copy of the License in the LICENSE file, or 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 ($) {
"use strict"; // jshint ;_;
/* MODAL CLASS DEFINITION
* ====================== */
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
this.options.remote && this.$element.find('.modal-body').load(this.options.remote)
}
Modal.prototype = {
constructor: Modal
, toggle: function () {
return this[!this.isShown ? 'show' : 'hide']()
}
, show: function () {
var that = this
, e = $.Event('show')
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) //don't move modals dom position
}
that.$element
.show()
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
transition ?
that.$element.one($.support.transition.end, function () { that.$element.focus().trigger('shown') }) :
that.$element.focus().trigger('shown')
})
}
, hide: function (e) {
e && e.preventDefault()
var that = this
e = $.Event('hide')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
$.support.transition && this.$element.hasClass('fade') ?
this.hideWithTransition() :
this.hideModal()
}
, enforceFocus: function () {
var that = this
$(document).on('focusin.modal', function (e) {
if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
that.$element.focus()
}
})
}
, escape: function () {
var that = this
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.modal', function ( e ) {
e.which == 27 && that.hide()
})
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
}
, hideWithTransition: function () {
var that = this
, timeout = setTimeout(function () {
that.$element.off($.support.transition.end)
that.hideModal()
}, 500)
this.$element.one($.support.transition.end, function () {
clearTimeout(timeout)
that.hideModal()
})
}
, hideModal: function (that) {
this.$element
.hide()
.trigger('hidden')
this.backdrop()
}
, removeBackdrop: function () {
this.$backdrop.remove()
this.$backdrop = null
}
, backdrop: function (callback) {
var that = this
, animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$backdrop.click(
this.options.backdrop == 'static' ?
$.proxy(this.$element[0].focus, this.$element[0])
: $.proxy(this.hide, this)
)
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
doAnimate ?
this.$backdrop.one($.support.transition.end, callback) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade')?
this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) :
this.removeBackdrop()
} else if (callback) {
callback()
}
}
}
/* MODAL PLUGIN DEFINITION
* ======================= */
var old = $.fn.modal
$.fn.modal = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('modal')
, options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.modal.defaults = {
backdrop: true
, keyboard: true
, show: true
}
$.fn.modal.Constructor = Modal
/* MODAL NO CONFLICT
* ================= */
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
/* MODAL DATA-API
* ============== */
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
, href = $this.attr('href')
, $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option)
.one('hide', function () {
$this.focus()
})
})
}(window.jQuery);
/*!
* This file creates $ and jQuery variables within the F2 closure scope
*/
var $, jQuery = $ = window.jQuery.noConflict(true);
/*!
* Hij1nx requires the following notice to accompany EventEmitter:
*
* Copyright (c) 2011 hij1nx
*
* http://www.twitter.com/hij1nx
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the 'Software'), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
!function(exports, undefined) {
var isArray = Array.isArray ? Array.isArray : function _isArray(obj) {
return Object.prototype.toString.call(obj) === "[object Array]";
};
var defaultMaxListeners = 10;
function init() {
this._events = new Object;
}
function configure(conf) {
if (conf) {
conf.delimiter && (this.delimiter = conf.delimiter);
conf.wildcard && (this.wildcard = conf.wildcard);
if (this.wildcard) {
this.listenerTree = new Object;
}
}
}
function EventEmitter(conf) {
this._events = new Object;
configure.call(this, conf);
}
//
// Attention, function return type now is array, always !
// It has zero elements if no any matches found and one or more
// elements (leafs) if there are matches
//
function searchListenerTree(handlers, type, tree, i) {
if (!tree) {
return [];
}
var listeners=[], leaf, len, branch, xTree, xxTree, isolatedBranch, endReached,
typeLength = type.length, currentType = type[i], nextType = type[i+1];
if (i === typeLength && tree._listeners) {
//
// If at the end of the event(s) list and the tree has listeners
// invoke those listeners.
//
if (typeof tree._listeners === 'function') {
handlers && handlers.push(tree._listeners);
return [tree];
} else {
for (leaf = 0, len = tree._listeners.length; leaf < len; leaf++) {
handlers && handlers.push(tree._listeners[leaf]);
}
return [tree];
}
}
if ((currentType === '*' || currentType === '**') || tree[currentType]) {
//
// If the event emitted is '*' at this part
// or there is a concrete match at this patch
//
if (currentType === '*') {
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+1));
}
}
return listeners;
} else if(currentType === '**') {
endReached = (i+1 === typeLength || (i+2 === typeLength && nextType === '*'));
if(endReached && tree._listeners) {
// The next element has a _listeners, add it to the handlers.
listeners = listeners.concat(searchListenerTree(handlers, type, tree, typeLength));
}
for (branch in tree) {
if (branch !== '_listeners' && tree.hasOwnProperty(branch)) {
if(branch === '*' || branch === '**') {
if(tree[branch]._listeners && !endReached) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], typeLength));
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
} else if(branch === nextType) {
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i+2));
} else {
// No match on this one, shift into the tree but not in the type array.
listeners = listeners.concat(searchListenerTree(handlers, type, tree[branch], i));
}
}
}
return listeners;
}
listeners = listeners.concat(searchListenerTree(handlers, type, tree[currentType], i+1));
}
xTree = tree['*'];
if (xTree) {
//
// If the listener tree will allow any match for this part,
// then recursively explore all branches of the tree
//
searchListenerTree(handlers, type, xTree, i+1);
}
xxTree = tree['**'];
if(xxTree) {
if(i < typeLength) {
if(xxTree._listeners) {
// If we have a listener on a '**', it will catch all, so add its handler.
searchListenerTree(handlers, type, xxTree, typeLength);
}
// Build arrays of matching next branches and others.
for(branch in xxTree) {
if(branch !== '_listeners' && xxTree.hasOwnProperty(branch)) {
if(branch === nextType) {
// We know the next element will match, so jump twice.
searchListenerTree(handlers, type, xxTree[branch], i+2);
} else if(branch === currentType) {
// Current node matches, move into the tree.
searchListenerTree(handlers, type, xxTree[branch], i+1);
} else {
isolatedBranch = {};
isolatedBranch[branch] = xxTree[branch];
searchListenerTree(handlers, type, { '**': isolatedBranch }, i+1);
}
}
}
} else if(xxTree._listeners) {
// We have reached the end and still on a '**'
searchListenerTree(handlers, type, xxTree, typeLength);
} else if(xxTree['*'] && xxTree['*']._listeners) {
searchListenerTree(handlers, type, xxTree['*'], typeLength);
}
}
return listeners;
}
function growListenerTree(type, listener) {
type = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
//
// Looks for two consecutive '**', if so, don't add the event at all.
//
for(var i = 0, len = type.length; i+1 < len; i++) {
if(type[i] === '**' && type[i+1] === '**') {
return;
}
}
var tree = this.listenerTree;
var name = type.shift();
while (name) {
if (!tree[name]) {
tree[name] = new Object;
}
tree = tree[name];
if (type.length === 0) {
if (!tree._listeners) {
tree._listeners = listener;
}
else if(typeof tree._listeners === 'function') {
tree._listeners = [tree._listeners, listener];
}
else if (isArray(tree._listeners)) {
tree._listeners.push(listener);
if (!tree._listeners.warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && tree._listeners.length > m) {
tree._listeners.warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
tree._listeners.length);
console.trace();
}
}
}
return true;
}
name = type.shift();
}
return true;
};
// By default EventEmitters will print a warning if more than
// 10 listeners are added to it. This is a useful default which
// helps finding memory leaks.
//
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.delimiter = '.';
EventEmitter.prototype.setMaxListeners = function(n) {
this._events || init.call(this);
this._events.maxListeners = n;
};
EventEmitter.prototype.event = '';
EventEmitter.prototype.once = function(event, fn) {
this.many(event, 1, fn);
return this;
};
EventEmitter.prototype.many = function(event, ttl, fn) {
var self = this;
if (typeof fn !== 'function') {
throw new Error('many only accepts instances of Function');
}
function listener() {
if (--ttl === 0) {
self.off(event, listener);
}
fn.apply(this, arguments);
};
listener._origin = fn;
this.on(event, listener);
return self;
};
EventEmitter.prototype.emit = function() {
this._events || init.call(this);
var type = arguments[0];
if (type === 'newListener') {
if (!this._events.newListener) { return false; }
}
// Loop through the *_all* functions and invoke them.
if (this._all) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
for (i = 0, l = this._all.length; i < l; i++) {
this.event = type;
this._all[i].apply(this, args);
}
}
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._all &&
!this._events.error &&
!(this.wildcard && this.listenerTree.error)) {
if (arguments[1] instanceof Error) {
throw arguments[1]; // Unhandled 'error' event
} else {
throw new Error("Uncaught, unspecified 'error' event.");
}
return false;
}
}
var handler;
if(this.wildcard) {
handler = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handler, ns, this.listenerTree, 0);
}
else {
handler = this._events[type];
}
if (typeof handler === 'function') {
this.event = type;
if (arguments.length === 1) {
handler.call(this);
}
else if (arguments.length > 1)
switch (arguments.length) {
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
handler.apply(this, args);
}
return true;
}
else if (handler) {
var l = arguments.length;
var args = new Array(l - 1);
for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
this.event = type;
listeners[i].apply(this, args);
}
return (listeners.length > 0) || this._all;
}
else {
return this._all;
}
};
EventEmitter.prototype.on = function(type, listener) {
if (typeof type === 'function') {
this.onAny(type);
return this;
}
if (typeof listener !== 'function') {
throw new Error('on only accepts instances of Function');
}
this._events || init.call(this);
// To avoid recursion in the case that type == "newListeners"! Before
// adding it to the listeners, first emit "newListeners".
this.emit('newListener', type, listener);
if(this.wildcard) {
growListenerTree.call(this, type, listener);
return this;
}
if (!this._events[type]) {
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
}
else if(typeof this._events[type] === 'function') {
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
}
else if (isArray(this._events[type])) {
// If we've already got an array, just append.
this._events[type].push(listener);
// Check for listener leak
if (!this._events[type].warned) {
var m = defaultMaxListeners;
if (typeof this._events.maxListeners !== 'undefined') {
m = this._events.maxListeners;
}
if (m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.onAny = function(fn) {
if(!this._all) {
this._all = [];
}
if (typeof fn !== 'function') {
throw new Error('onAny only accepts instances of Function');
}
// Add the function to the event listener collection.
this._all.push(fn);
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
EventEmitter.prototype.off = function(type, listener) {
if (typeof listener !== 'function') {
throw new Error('removeListener only takes instances of Function');
}
var handlers,leafs=[];
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
}
else {
// does not use listeners(), so no side effect of creating _events[type]
if (!this._events[type]) return this;
handlers = this._events[type];
leafs.push({_listeners:handlers});
}
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
handlers = leaf._listeners;
if (isArray(handlers)) {
var position = -1;
for (var i = 0, length = handlers.length; i < length; i++) {
if (handlers[i] === listener ||
(handlers[i].listener && handlers[i].listener === listener) ||
(handlers[i]._origin && handlers[i]._origin === listener)) {
position = i;
break;
}
}
if (position < 0) {
return this;
}
if(this.wildcard) {
leaf._listeners.splice(position, 1)
}
else {
this._events[type].splice(position, 1);
}
if (handlers.length === 0) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
else if (handlers === listener ||
(handlers.listener && handlers.listener === listener) ||
(handlers._origin && handlers._origin === listener)) {
if(this.wildcard) {
delete leaf._listeners;
}
else {
delete this._events[type];
}
}
}
return this;
};
EventEmitter.prototype.offAny = function(fn) {
var i = 0, l = 0, fns;
if (fn && this._all && this._all.length > 0) {
fns = this._all;
for(i = 0, l = fns.length; i < l; i++) {
if(fn === fns[i]) {
fns.splice(i, 1);
return this;
}
}
} else {
this._all = [];
}
return this;
};
EventEmitter.prototype.removeListener = EventEmitter.prototype.off;
EventEmitter.prototype.removeAllListeners = function(type) {
if (arguments.length === 0) {
!this._events || init.call(this);
return this;
}
if(this.wildcard) {
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
var leafs = searchListenerTree.call(this, null, ns, this.listenerTree, 0);
for (var iLeaf=0; iLeaf<leafs.length; iLeaf++) {
var leaf = leafs[iLeaf];
leaf._listeners = null;
}
}
else {
if (!this._events[type]) return this;
this._events[type] = null;
}
return this;
};
EventEmitter.prototype.listeners = function(type) {
if(this.wildcard) {
var handlers = [];
var ns = typeof type === 'string' ? type.split(this.delimiter) : type.slice();
searchListenerTree.call(this, handlers, ns, this.listenerTree, 0);
return handlers;
}
this._events || init.call(this);
if (!this._events[type]) this._events[type] = [];
if (!isArray(this._events[type])) {
this._events[type] = [this._events[type]];
}
return this._events[type];
};
EventEmitter.prototype.listenersAny = function() {
if(this._all) {
return this._all;
}
else {
return [];
}
};
// if (typeof define === 'function' && define.amd) {
// define('EventEmitter2', [], function() {
// return EventEmitter;
// });
// } else {
exports.EventEmitter2 = EventEmitter;
// }
}(typeof process !== 'undefined' && typeof process.title !== 'undefined' && typeof exports !== 'undefined' ? exports : window);
/*!
* Øyvind Sean Kinsey and others require the following notice to accompany easyXDM:
*
* http://easyxdm.net/
* Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
(function (window, document, location, setTimeout, decodeURIComponent, encodeURIComponent) {
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global JSON, XMLHttpRequest, window, escape, unescape, ActiveXObject */
var global = this;
var channelId = Math.floor(Math.random() * 10000); // randomize the initial id in case of multiple closures loaded
var emptyFn = Function.prototype;
var reURI = /^((http.?:)\/\/([^:\/\s]+)(:\d+)*)/; // returns groups for protocol (2), domain (3) and port (4)
var reParent = /[\-\w]+\/\.\.\//; // matches a foo/../ expression
var reDoubleSlash = /([^:])\/\//g; // matches // anywhere but in the protocol
var namespace = ""; // stores namespace under which easyXDM object is stored on the page (empty if object is global)
var easyXDM = {};
var _easyXDM = window.easyXDM; // map over global easyXDM in case of overwrite
var IFRAME_PREFIX = "easyXDM_";
var HAS_NAME_PROPERTY_BUG;
var useHash = false; // whether to use the hash over the query
var flashVersion; // will be set if using flash
var HAS_FLASH_THROTTLED_BUG;
// http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting
function isHostMethod(object, property){
var t = typeof object[property];
return t == 'function' ||
(!!(t == 'object' && object[property])) ||
t == 'unknown';
}
function isHostObject(object, property){
return !!(typeof(object[property]) == 'object' && object[property]);
}
// end
// http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
function isArray(o){
return Object.prototype.toString.call(o) === '[object Array]';
}
// end
function hasFlash(){
try {
var activeX = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
flashVersion = Array.prototype.slice.call(activeX.GetVariable("$version").match(/(\d+),(\d+),(\d+),(\d+)/), 1);
HAS_FLASH_THROTTLED_BUG = parseInt(flashVersion[0], 10) > 9 && parseInt(flashVersion[1], 10) > 0;
activeX = null;
return true;
}
catch (notSupportedException) {
return false;
}
}
/*
* Cross Browser implementation for adding and removing event listeners.
*/
var on, un;
if (isHostMethod(window, "addEventListener")) {
on = function(target, type, listener){
target.addEventListener(type, listener, false);
};
un = function(target, type, listener){
target.removeEventListener(type, listener, false);
};
}
else if (isHostMethod(window, "attachEvent")) {
on = function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
un = function(object, sEvent, fpNotify){
object.detachEvent("on" + sEvent, fpNotify);
};
}
else {
throw new Error("Browser not supported");
}
/*
* Cross Browser implementation of DOMContentLoaded.
*/
var domIsReady = false, domReadyQueue = [], readyState;
if ("readyState" in document) {
// If browser is WebKit-powered, check for both 'loaded' (legacy browsers) and
// 'interactive' (HTML5 specs, recent WebKit builds) states.
// https://bugs.webkit.org/show_bug.cgi?id=45119
readyState = document.readyState;
domIsReady = readyState == "complete" || (~ navigator.userAgent.indexOf('AppleWebKit/') && (readyState == "loaded" || readyState == "interactive"));
}
else {
// If readyState is not supported in the browser, then in order to be able to fire whenReady functions apropriately
// when added dynamically _after_ DOM load, we have to deduce wether the DOM is ready or not.
// We only need a body to add elements to, so the existence of document.body is enough for us.
domIsReady = !!document.body;
}
function dom_onReady(){
if (domIsReady) {
return;
}
domIsReady = true;
for (var i = 0; i < domReadyQueue.length; i++) {
domReadyQueue[i]();
}
domReadyQueue.length = 0;
}
if (!domIsReady) {
if (isHostMethod(window, "addEventListener")) {
on(document, "DOMContentLoaded", dom_onReady);
}
else {
on(document, "readystatechange", function(){
if (document.readyState == "complete") {
dom_onReady();
}
});
if (document.documentElement.doScroll && window === top) {
var doScrollCheck = function(){
if (domIsReady) {
return;
}
// http://javascript.nwbox.com/IEContentLoaded/
try {
document.documentElement.doScroll("left");
}
catch (e) {
setTimeout(doScrollCheck, 1);
return;
}
dom_onReady();
};
doScrollCheck();
}
}
// A fallback to window.onload, that will always work
on(window, "load", dom_onReady);
}
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {Object} scope An optional scope for the function to be called with.
*/
function whenReady(fn, scope){
if (domIsReady) {
fn.call(scope);
return;
}
domReadyQueue.push(function(){
fn.call(scope);
});
}
/**
* Returns an instance of easyXDM from the parent window with
* respect to the namespace.
*
* @return An instance of easyXDM (in the parent window)
*/
function getParentObject(){
var obj = parent;
if (namespace !== "") {
for (var i = 0, ii = namespace.split("."); i < ii.length; i++) {
obj = obj[ii[i]];
}
}
return obj.easyXDM;
}
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
function noConflict(ns){
window.easyXDM = _easyXDM;
namespace = ns;
if (namespace) {
IFRAME_PREFIX = "easyXDM_" + namespace.replace(".", "_") + "_";
}
return easyXDM;
}
/*
* Methods for working with URLs
*/
/**
* Get the domain name from a url.
* @param {String} url The url to extract the domain from.
* @return The domain part of the url.
* @type {String}
*/
function getDomainName(url){
return url.match(reURI)[3];
}
/**
* Get the port for a given URL, or "" if none
* @param {String} url The url to extract the port from.
* @return The port part of the url.
* @type {String}
*/
function getPort(url){
return url.match(reURI)[4] || "";
}
/**
* Returns a string containing the schema, domain and if present the port
* @param {String} url The url to extract the location from
* @return {String} The location part of the url
*/
function getLocation(url){
var m = url.toLowerCase().match(reURI);
var proto = m[2], domain = m[3], port = m[4] || "";
if ((proto == "http:" && port == ":80") || (proto == "https:" && port == ":443")) {
port = "";
}
return proto + "//" + domain + port;
}
/**
* Resolves a relative url into an absolute one.
* @param {String} url The path to resolve.
* @return {String} The resolved url.
*/
function resolveUrl(url){
// replace all // except the one in proto with /
url = url.replace(reDoubleSlash, "$1/");
// If the url is a valid url we do nothing
if (!url.match(/^(http||https):\/\//)) {
// If this is a relative path
var path = (url.substring(0, 1) === "/") ? "" : location.pathname;
if (path.substring(path.length - 1) !== "/") {
path = path.substring(0, path.lastIndexOf("/") + 1);
}
url = location.protocol + "//" + location.host + path + url;
}
// reduce all 'xyz/../' to just ''
while (reParent.test(url)) {
url = url.replace(reParent, "");
}
return url;
}
/**
* Appends the parameters to the given url.<br/>
* The base url can contain existing query parameters.
* @param {String} url The base url.
* @param {Object} parameters The parameters to add.
* @return {String} A new valid url with the parameters appended.
*/
function appendQueryParameters(url, parameters){
var hash = "", indexOf = url.indexOf("#");
if (indexOf !== -1) {
hash = url.substring(indexOf);
url = url.substring(0, indexOf);
}
var q = [];
for (var key in parameters) {
if (parameters.hasOwnProperty(key)) {
q.push(key + "=" + encodeURIComponent(parameters[key]));
}
}
return url + (useHash ? "#" : (url.indexOf("?") == -1 ? "?" : "&")) + q.join("&") + hash;
}
// build the query object either from location.query, if it contains the xdm_e argument, or from location.hash
var query = (function(input){
input = input.substring(1).split("&");
var data = {}, pair, i = input.length;
while (i--) {
pair = input[i].split("=");
data[pair[0]] = decodeURIComponent(pair[1]);
}
return data;
}(/xdm_e=/.test(location.search) ? location.search : location.hash));
/*
* Helper methods
*/
/**
* Helper for checking if a variable/property is undefined
* @param {Object} v The variable to test
* @return {Boolean} True if the passed variable is undefined
*/
function undef(v){
return typeof v === "undefined";
}
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
var getJSON = function(){
var cached = {};
var obj = {
a: [1, 2, 3]
}, json = "{\"a\":[1,2,3]}";
if (typeof JSON != "undefined" && typeof JSON.stringify === "function" && JSON.stringify(obj).replace((/\s/g), "") === json) {
// this is a working JSON instance
return JSON;
}
if (Object.toJSON) {
if (Object.toJSON(obj).replace((/\s/g), "") === json) {
// this is a working stringify method
cached.stringify = Object.toJSON;
}
}
if (typeof String.prototype.evalJSON === "function") {
obj = json.evalJSON();
if (obj.a && obj.a.length === 3 && obj.a[2] === 3) {
// this is a working parse method
cached.parse = function(str){
return str.evalJSON();
};
}
}
if (cached.stringify && cached.parse) {
// Only memoize the result if we have valid instance
getJSON = function(){
return cached;
};
return cached;
}
return null;
};
/**
* Applies properties from the source object to the target object.<br/>
* @param {Object} target The target of the properties.
* @param {Object} source The source of the properties.
* @param {Boolean} noOverwrite Set to True to only set non-existing properties.
*/
function apply(destination, source, noOverwrite){
var member;
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
if (prop in destination) {
member = source[prop];
if (typeof member === "object") {
apply(destination[prop], member, noOverwrite);
}
else if (!noOverwrite) {
destination[prop] = source[prop];
}
}
else {
destination[prop] = source[prop];
}
}
}
return destination;
}
// This tests for the bug in IE where setting the [name] property using javascript causes the value to be redirected into [submitName].
function testForNamePropertyBug(){
var form = document.body.appendChild(document.createElement("form")), input = form.appendChild(document.createElement("input"));
input.name = IFRAME_PREFIX + "TEST" + channelId; // append channelId in order to avoid caching issues
HAS_NAME_PROPERTY_BUG = input !== form.elements[input.name];
document.body.removeChild(form);
}
/**
* Creates a frame and appends it to the DOM.
* @param config {object} This object can have the following properties
* <ul>
* <li> {object} prop The properties that should be set on the frame. This should include the 'src' property.</li>
* <li> {object} attr The attributes that should be set on the frame.</li>
* <li> {DOMElement} container Its parent element (Optional).</li>
* <li> {function} onLoad A method that should be called with the frames contentWindow as argument when the frame is fully loaded. (Optional)</li>
* </ul>
* @return The frames DOMElement
* @type DOMElement
*/
function createFrame(config){
if (undef(HAS_NAME_PROPERTY_BUG)) {
testForNamePropertyBug();
}
var frame;
// This is to work around the problems in IE6/7 with setting the name property.
// Internally this is set as 'submitName' instead when using 'iframe.name = ...'
// This is not required by easyXDM itself, but is to facilitate other use cases
if (HAS_NAME_PROPERTY_BUG) {
frame = document.createElement("<iframe name=\"" + config.props.name + "\"/>");
}
else {
frame = document.createElement("IFRAME");
frame.name = config.props.name;
}
frame.id = frame.name = config.props.name;
delete config.props.name;
if (config.onLoad) {
on(frame, "load", config.onLoad);
}
if (typeof config.container == "string") {
config.container = document.getElementById(config.container);
}
if (!config.container) {
// This needs to be hidden like this, simply setting display:none and the like will cause failures in some browsers.
apply(frame.style, {
position: "absolute",
top: "-2000px"
});
config.container = document.body;
}
// HACK for some reason, IE needs the source set
// after the frame has been appended into the DOM
// so remove the src, and set it afterwards
var src = config.props.src;
delete config.props.src;
// transfer properties to the frame
apply(frame, config.props);
frame.border = frame.frameBorder = 0;
frame.allowTransparency = true;
config.container.appendChild(frame);
// HACK see above
frame.src = src;
config.props.src = src;
return frame;
}
/**
* Check whether a domain is allowed using an Access Control List.
* The ACL can contain * and ? as wildcards, or can be regular expressions.
* If regular expressions they need to begin with ^ and end with $.
* @param {Array/String} acl The list of allowed domains
* @param {String} domain The domain to test.
* @return {Boolean} True if the domain is allowed, false if not.
*/
function checkAcl(acl, domain){
// normalize into an array
if (typeof acl == "string") {
acl = [acl];
}
var re, i = acl.length;
while (i--) {
re = acl[i];
re = new RegExp(re.substr(0, 1) == "^" ? re : ("^" + re.replace(/(\*)/g, ".$1").replace(/\?/g, ".") + "$"));
if (re.test(domain)) {
return true;
}
}
return false;
}
/*
* Functions related to stacks
*/
/**
* Prepares an array of stack-elements suitable for the current configuration
* @param {Object} config The Transports configuration. See easyXDM.Socket for more.
* @return {Array} An array of stack-elements with the TransportElement at index 0.
*/
function prepareTransportStack(config){
var protocol = config.protocol, stackEls;
config.isHost = config.isHost || undef(query.xdm_p);
useHash = config.hash || false;
if (!config.props) {
config.props = {};
}
if (!config.isHost) {
config.channel = query.xdm_c;
config.secret = query.xdm_s;
config.remote = query.xdm_e;
protocol = query.xdm_p;
if (config.acl && !checkAcl(config.acl, config.remote)) {
throw new Error("Access denied for " + config.remote);
}
}
else {
config.remote = resolveUrl(config.remote);
config.channel = config.channel || "default" + channelId++;
config.secret = Math.random().toString(16).substring(2);
if (undef(protocol)) {
if (getLocation(location.href) == getLocation(config.remote)) {
/*
* Both documents has the same origin, lets use direct access.
*/
protocol = "4";
}
else if (isHostMethod(window, "postMessage") || isHostMethod(document, "postMessage")) {
/*
* This is supported in IE8+, Firefox 3+, Opera 9+, Chrome 2+ and Safari 4+
*/
protocol = "1";
}
else if (config.swf && isHostMethod(window, "ActiveXObject") && hasFlash()) {
/*
* The Flash transport superseedes the NixTransport as the NixTransport has been blocked by MS
*/
protocol = "6";
}
else if (navigator.product === "Gecko" && "frameElement" in window && navigator.userAgent.indexOf('WebKit') == -1) {
/*
* This is supported in Gecko (Firefox 1+)
*/
protocol = "5";
}
else if (config.remoteHelper) {
/*
* This is supported in all browsers that retains the value of window.name when
* navigating from one domain to another, and where parent.frames[foo] can be used
* to get access to a frame from the same domain
*/
config.remoteHelper = resolveUrl(config.remoteHelper);
protocol = "2";
}
else {
/*
* This is supported in all browsers where [window].location is writable for all
* The resize event will be used if resize is supported and the iframe is not put
* into a container, else polling will be used.
*/
protocol = "0";
}
}
}
config.protocol = protocol; // for conditional branching
switch (protocol) {
case "0":// 0 = HashTransport
apply(config, {
interval: 100,
delay: 2000,
useResize: true,
useParent: false,
usePolling: false
}, true);
if (config.isHost) {
if (!config.local) {
// If no local is set then we need to find an image hosted on the current domain
var domain = location.protocol + "//" + location.host, images = document.body.getElementsByTagName("img"), image;
var i = images.length;
while (i--) {
image = images[i];
if (image.src.substring(0, domain.length) === domain) {
config.local = image.src;
break;
}
}
if (!config.local) {
// If no local was set, and we are unable to find a suitable file, then we resort to using the current window
config.local = window;
}
}
var parameters = {
xdm_c: config.channel,
xdm_p: 0
};
if (config.local === window) {
// We are using the current window to listen to
config.usePolling = true;
config.useParent = true;
config.local = location.protocol + "//" + location.host + location.pathname + location.search;
parameters.xdm_e = config.local;
parameters.xdm_pa = 1; // use parent
}
else {
parameters.xdm_e = resolveUrl(config.local);
}
if (config.container) {
config.useResize = false;
parameters.xdm_po = 1; // use polling
}
config.remote = appendQueryParameters(config.remote, parameters);
}
else {
apply(config, {
channel: query.xdm_c,
remote: query.xdm_e,
useParent: !undef(query.xdm_pa),
usePolling: !undef(query.xdm_po),
useResize: config.useParent ? false : config.useResize
});
}
stackEls = [new easyXDM.stack.HashTransport(config), new easyXDM.stack.ReliableBehavior({}), new easyXDM.stack.QueueBehavior({
encode: true,
maxLength: 4000 - config.remote.length
}), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "1":
stackEls = [new easyXDM.stack.PostMessageTransport(config)];
break;
case "2":
stackEls = [new easyXDM.stack.NameTransport(config), new easyXDM.stack.QueueBehavior(), new easyXDM.stack.VerifyBehavior({
initiate: config.isHost
})];
break;
case "3":
stackEls = [new easyXDM.stack.NixTransport(config)];
break;
case "4":
stackEls = [new easyXDM.stack.SameOriginTransport(config)];
break;
case "5":
stackEls = [new easyXDM.stack.FrameElementTransport(config)];
break;
case "6":
if (!flashVersion) {
hasFlash();
}
stackEls = [new easyXDM.stack.FlashTransport(config)];
break;
}
// this behavior is responsible for buffering outgoing messages, and for performing lazy initialization
stackEls.push(new easyXDM.stack.QueueBehavior({
lazy: config.lazy,
remove: true
}));
return stackEls;
}
/**
* Chains all the separate stack elements into a single usable stack.<br/>
* If an element is missing a necessary method then it will have a pass-through method applied.
* @param {Array} stackElements An array of stack elements to be linked.
* @return {easyXDM.stack.StackElement} The last element in the chain.
*/
function chainStack(stackElements){
var stackEl, defaults = {
incoming: function(message, origin){
this.up.incoming(message, origin);
},
outgoing: function(message, recipient){
this.down.outgoing(message, recipient);
},
callback: function(success){
this.up.callback(success);
},
init: function(){
this.down.init();
},
destroy: function(){
this.down.destroy();
}
};
for (var i = 0, len = stackElements.length; i < len; i++) {
stackEl = stackElements[i];
apply(stackEl, defaults, true);
if (i !== 0) {
stackEl.down = stackElements[i - 1];
}
if (i !== len - 1) {
stackEl.up = stackElements[i + 1];
}
}
return stackEl;
}
/**
* This will remove a stackelement from its stack while leaving the stack functional.
* @param {Object} element The elment to remove from the stack.
*/
function removeFromStack(element){
element.up.down = element.down;
element.down.up = element.up;
element.up = element.down = null;
}
/*
* Export the main object and any other methods applicable
*/
/**
* @class easyXDM
* A javascript library providing cross-browser, cross-domain messaging/RPC.
* @version 2.4.15.118
* @singleton
*/
apply(easyXDM, {
/**
* The version of the library
* @type {string}
*/
version: "2.4.15.118",
/**
* This is a map containing all the query parameters passed to the document.
* All the values has been decoded using decodeURIComponent.
* @type {object}
*/
query: query,
/**
* @private
*/
stack: {},
/**
* Applies properties from the source object to the target object.<br/>
* @param {object} target The target of the properties.
* @param {object} source The source of the properties.
* @param {boolean} noOverwrite Set to True to only set non-existing properties.
*/
apply: apply,
/**
* A safe implementation of HTML5 JSON. Feature testing is used to make sure the implementation works.
* @return {JSON} A valid JSON conforming object, or null if not found.
*/
getJSONObject: getJSON,
/**
* This will add a function to the queue of functions to be run once the DOM reaches a ready state.
* If functions are added after this event then they will be executed immediately.
* @param {function} fn The function to add
* @param {object} scope An optional scope for the function to be called with.
*/
whenReady: whenReady,
/**
* Removes easyXDM variable from the global scope. It also returns control
* of the easyXDM variable to whatever code used it before.
*
* @param {String} ns A string representation of an object that will hold
* an instance of easyXDM.
* @return An instance of easyXDM
*/
noConflict: noConflict
});
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global console, _FirebugCommandLine, easyXDM, window, escape, unescape, isHostObject, undef, _trace, domIsReady, emptyFn, namespace */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, isHostObject, isHostMethod, un, on, createFrame, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.DomHelper
* Contains methods for dealing with the DOM
* @singleton
*/
easyXDM.DomHelper = {
/**
* Provides a consistent interface for adding eventhandlers
* @param {Object} target The target to add the event to
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
on: on,
/**
* Provides a consistent interface for removing eventhandlers
* @param {Object} target The target to remove the event from
* @param {String} type The name of the event
* @param {Function} listener The listener
*/
un: un,
/**
* Checks for the presence of the JSON object.
* If it is not present it will use the supplied path to load the JSON2 library.
* This should be called in the documents head right after the easyXDM script tag.
* http://json.org/json2.js
* @param {String} path A valid path to json2.js
*/
requiresJSON: function(path){
if (!isHostObject(window, "JSON")) {
// we need to encode the < in order to avoid an illegal token error
// when the script is inlined in a document.
document.write('<' + 'script type="text/javascript" src="' + path + '"><' + '/script>');
}
}
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
(function(){
// The map containing the stored functions
var _map = {};
/**
* @class easyXDM.Fn
* This contains methods related to function handling, such as storing callbacks.
* @singleton
* @namespace easyXDM
*/
easyXDM.Fn = {
/**
* Stores a function using the given name for reference
* @param {String} name The name that the function should be referred by
* @param {Function} fn The function to store
* @namespace easyXDM.fn
*/
set: function(name, fn){
_map[name] = fn;
},
/**
* Retrieves the function referred to by the given name
* @param {String} name The name of the function to retrieve
* @param {Boolean} del If the function should be deleted after retrieval
* @return {Function} The stored function
* @namespace easyXDM.fn
*/
get: function(name, del){
var fn = _map[name];
if (del) {
delete _map[name];
}
return fn;
}
};
}());
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, chainStack, prepareTransportStack, getLocation, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Socket
* This class creates a transport channel between two domains that is usable for sending and receiving string-based messages.<br/>
* The channel is reliable, supports queueing, and ensures that the message originates from the expected domain.<br/>
* Internally different stacks will be used depending on the browsers features and the available parameters.
* <h2>How to set up</h2>
* Setting up the provider:
* <pre><code>
* var socket = new easyXDM.Socket({
* local: "name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* Setting up the consumer:
* <pre><code>
* var socket = new easyXDM.Socket({
* remote: "http://remotedomain/page.html",
* remoteHelper: "http://remotedomain/name.html",
* onReady: function(){
* // you need to wait for the onReady callback before using the socket
* socket.postMessage("foo-message");
* },
* onMessage: function(message, origin) {
* alert("received " + message + " from " + origin);
* }
* });
* </code></pre>
* If you are unable to upload the <code>name.html</code> file to the consumers domain then remove the <code>remoteHelper</code> property
* and easyXDM will fall back to using the HashTransport instead of the NameTransport when not able to use any of the primary transports.
* @namespace easyXDM
* @constructor
* @cfg {String/Window} local The url to the local name.html document, a local static file, or a reference to the local window.
* @cfg {Boolean} lazy (Consumer only) Set this to true if you want easyXDM to defer creating the transport until really needed.
* @cfg {String} remote (Consumer only) The url to the providers document.
* @cfg {String} remoteHelper (Consumer only) The url to the remote name.html file. This is to support NameTransport as a fallback. Optional.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window. Optional, defaults to 2000.
* @cfg {Number} interval The interval used when polling for messages. Optional, defaults to 300.
* @cfg {String} channel (Consumer only) The name of the channel to use. Can be used to set consistent iframe names. Must be unique. Optional.
* @cfg {Function} onMessage The method that should handle incoming messages.<br/> This method should accept two arguments, the message as a string, and the origin as a string. Optional.
* @cfg {Function} onReady A method that should be called when the transport is ready. Optional.
* @cfg {DOMElement|String} container (Consumer only) The element, or the id of the element that the primary iframe should be inserted into. If not set then the iframe will be positioned off-screen. Optional.
* @cfg {Array/String} acl (Provider only) Here you can specify which '[protocol]://[domain]' patterns that should be allowed to act as the consumer towards this provider.<br/>
* This can contain the wildcards ? and *. Examples are 'http://example.com', '*.foo.com' and '*dom?.com'. If you want to use reqular expressions then you pattern needs to start with ^ and end with $.
* If none of the patterns match an Error will be thrown.
* @cfg {Object} props (Consumer only) Additional properties that should be applied to the iframe. This can also contain nested objects e.g: <code>{style:{width:"100px", height:"100px"}}</code>.
* Properties such as 'name' and 'src' will be overrided. Optional.
*/
easyXDM.Socket = function(config){
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([{
incoming: function(message, origin){
config.onMessage(message, origin);
},
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}])), recipient = getLocation(config.remote);
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
/**
* Posts a message to the remote end of the channel
* @param {String} message The message to send
*/
this.postMessage = function(message){
stack.outgoing(message, recipient);
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef,, chainStack, prepareTransportStack, debug, getLocation */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.Rpc
* Creates a proxy object that can be used to call methods implemented on the remote end of the channel, and also to provide the implementation
* of methods to be called from the remote end.<br/>
* The instantiated object will have methods matching those specified in <code>config.remote</code>.<br/>
* This requires the JSON object present in the document, either natively, using json.org's json2 or as a wrapper around library spesific methods.
* <h2>How to set up</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* // this configuration is equal to that used by the Socket.
* remote: "http://remotedomain/...",
* onReady: function(){
* // you need to wait for the onReady callback before using the proxy
* rpc.foo(...
* }
* },{
* local: {..},
* remote: {..}
* });
* </code></pre>
*
* <h2>Exposing functions (procedures)</h2>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {
* nameOfMethod: {
* method: function(arg1, arg2, success, error){
* ...
* }
* },
* // with shorthand notation
* nameOfAnotherMethod: function(arg1, arg2, success, error){
* }
* },
* remote: {...}
* });
* </code></pre>
* The function referenced by [method] will receive the passed arguments followed by the callback functions <code>success</code> and <code>error</code>.<br/>
* To send a successfull result back you can use
* <pre><code>
* return foo;
* </pre></code>
* or
* <pre><code>
* success(foo);
* </pre></code>
* To return an error you can use
* <pre><code>
* throw new Error("foo error");
* </code></pre>
* or
* <pre><code>
* error("foo error");
* </code></pre>
*
* <h2>Defining remotely exposed methods (procedures/notifications)</h2>
* The definition of the remote end is quite similar:
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {
* nameOfMethod: {}
* }
* });
* </code></pre>
* To call a remote method use
* <pre><code>
* rpc.nameOfMethod("arg1", "arg2", function(value) {
* alert("success: " + value);
* }, function(message) {
* alert("error: " + message + );
* });
* </code></pre>
* Both the <code>success</code> and <code>errror</code> callbacks are optional.<br/>
* When called with no callback a JSON-RPC 2.0 notification will be executed.
* Be aware that you will not be notified of any errors with this method.
* <br/>
* <h2>Specifying a custom serializer</h2>
* If you do not want to use the JSON2 library for non-native JSON support, but instead capabilities provided by some other library
* then you can specify a custom serializer using <code>serializer: foo</code>
* <pre><code>
* var rpc = new easyXDM.Rpc({
* ...
* },{
* local: {...},
* remote: {...},
* serializer : {
* parse: function(string){ ... },
* stringify: function(object) {...}
* }
* });
* </code></pre>
* If <code>serializer</code> is set then the class will not attempt to use the native implementation.
* @namespace easyXDM
* @constructor
* @param {Object} config The underlying transports configuration. See easyXDM.Socket for available parameters.
* @param {Object} jsonRpcConfig The description of the interface to implement.
*/
easyXDM.Rpc = function(config, jsonRpcConfig){
// expand shorthand notation
if (jsonRpcConfig.local) {
for (var method in jsonRpcConfig.local) {
if (jsonRpcConfig.local.hasOwnProperty(method)) {
var member = jsonRpcConfig.local[method];
if (typeof member === "function") {
jsonRpcConfig.local[method] = {
method: member
};
}
}
}
}
// create the stack
var stack = chainStack(prepareTransportStack(config).concat([new easyXDM.stack.RpcBehavior(this, jsonRpcConfig), {
callback: function(success){
if (config.onReady) {
config.onReady(success);
}
}
}]));
// set the origin
this.origin = getLocation(config.remote);
/**
* Initiates the destruction of the stack.
*/
this.destroy = function(){
stack.destroy();
};
stack.init();
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, getParentObject, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.SameOriginTransport
* SameOriginTransport is a transport class that can be used when both domains have the same origin.<br/>
* This can be useful for testing and for when the main application supports both internal and external sources.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.SameOriginTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send(message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: location.protocol + "//" + location.host + location.pathname,
xdm_c: config.channel,
xdm_p: 4 // 4 = SameOriginTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
easyXDM.Fn.set(config.channel, function(sendFn){
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
});
}
else {
send = getParentObject().Fn.get(config.channel, true)(function(msg){
pub.up.incoming(msg, targetOrigin);
});
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global global, easyXDM, window, getLocation, appendQueryParameters, createFrame, debug, apply, whenReady, IFRAME_PREFIX, namespace, resolveUrl, getDomainName, HAS_FLASH_THROTTLED_BUG, getPort, query*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FlashTransport
* FlashTransport is a transport class that uses an SWF with LocalConnection to pass messages back and forth.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
* @cfg {String} secret the pre-shared secret used to secure the communication.
* @cfg {String} swf The path to the swf file
* @cfg {Boolean} swfNoThrottle Set this to true if you want to take steps to avoid beeing throttled when hidden.
* @cfg {String || DOMElement} swfContainer Set this if you want to control where the swf is placed
*/
easyXDM.stack.FlashTransport = function(config){
var pub, // the public interface
frame, send, targetOrigin, swf, swfContainer;
function onMessage(message, origin){
setTimeout(function(){
pub.up.incoming(message, targetOrigin);
}, 0);
}
/**
* This method adds the SWF to the DOM and prepares the initialization of the channel
*/
function addSwf(domain){
// the differentiating query argument is needed in Flash9 to avoid a caching issue where LocalConnection would throw an error.
var url = config.swf + "?host=" + config.isHost;
var id = "easyXDM_swf_" + Math.floor(Math.random() * 10000);
// prepare the init function that will fire once the swf is ready
easyXDM.Fn.set("flash_loaded" + domain.replace(/[\-.]/g, "_"), function(){
easyXDM.stack.FlashTransport[domain].swf = swf = swfContainer.firstChild;
var queue = easyXDM.stack.FlashTransport[domain].queue;
for (var i = 0; i < queue.length; i++) {
queue[i]();
}
queue.length = 0;
});
if (config.swfContainer) {
swfContainer = (typeof config.swfContainer == "string") ? document.getElementById(config.swfContainer) : config.swfContainer;
}
else {
// create the container that will hold the swf
swfContainer = document.createElement('div');
// http://bugs.adobe.com/jira/browse/FP-4796
// http://tech.groups.yahoo.com/group/flexcoders/message/162365
// https://groups.google.com/forum/#!topic/easyxdm/mJZJhWagoLc
apply(swfContainer.style, HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle ? {
height: "20px",
width: "20px",
position: "fixed",
right: 0,
top: 0
} : {
height: "1px",
width: "1px",
position: "absolute",
overflow: "hidden",
right: 0,
top: 0
});
document.body.appendChild(swfContainer);
}
// create the object/embed
var flashVars = "callback=flash_loaded" + domain.replace(/[\-.]/g, "_") + "&proto=" + global.location.protocol + "&domain=" + getDomainName(global.location.href) + "&port=" + getPort(global.location.href) + "&ns=" + namespace;
swfContainer.innerHTML = "<object height='20' width='20' type='application/x-shockwave-flash' id='" + id + "' data='" + url + "'>" +
"<param name='allowScriptAccess' value='always'></param>" +
"<param name='wmode' value='transparent'>" +
"<param name='movie' value='" +
url +
"'></param>" +
"<param name='flashvars' value='" +
flashVars +
"'></param>" +
"<embed type='application/x-shockwave-flash' FlashVars='" +
flashVars +
"' allowScriptAccess='always' wmode='transparent' src='" +
url +
"' height='1' width='1'></embed>" +
"</object>";
}
return (pub = {
outgoing: function(message, domain, fn){
swf.postMessage(config.channel, message.toString());
if (fn) {
fn();
}
},
destroy: function(){
try {
swf.destroyChannel(config.channel);
}
catch (e) {
}
swf = null;
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = config.remote;
// Prepare the code that will be run after the swf has been intialized
easyXDM.Fn.set("flash_" + config.channel + "_init", function(){
setTimeout(function(){
pub.up.callback(true);
});
});
// set up the omMessage handler
easyXDM.Fn.set("flash_" + config.channel + "_onMessage", onMessage);
config.swf = resolveUrl(config.swf); // reports have been made of requests gone rogue when using relative paths
var swfdomain = getDomainName(config.swf);
var fn = function(){
// set init to true in case the fn was called was invoked from a separate instance
easyXDM.stack.FlashTransport[swfdomain].init = true;
swf = easyXDM.stack.FlashTransport[swfdomain].swf;
// create the channel
swf.createChannel(config.channel, config.secret, getLocation(config.remote), config.isHost);
if (config.isHost) {
// if Flash is going to be throttled and we want to avoid this
if (HAS_FLASH_THROTTLED_BUG && config.swfNoThrottle) {
apply(config.props, {
position: "fixed",
right: 0,
top: 0,
height: "20px",
width: "20px"
});
}
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 6, // 6 = FlashTransport
xdm_s: config.secret
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
};
if (easyXDM.stack.FlashTransport[swfdomain] && easyXDM.stack.FlashTransport[swfdomain].init) {
// if the swf is in place and we are the consumer
fn();
}
else {
// if the swf does not yet exist
if (!easyXDM.stack.FlashTransport[swfdomain]) {
// add the queue to hold the init fn's
easyXDM.stack.FlashTransport[swfdomain] = {
queue: [fn]
};
addSwf(swfdomain);
}
else {
easyXDM.stack.FlashTransport[swfdomain].queue.push(fn);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.PostMessageTransport
* PostMessageTransport is a transport class that uses HTML5 postMessage for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx">http://msdn.microsoft.com/en-us/library/ms644944(VS.85).aspx</a><br/>
* <a href="https://developer.mozilla.org/en/DOM/window.postMessage">https://developer.mozilla.org/en/DOM/window.postMessage</a>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote domain to communicate with.
*/
easyXDM.stack.PostMessageTransport = function(config){
var pub, // the public interface
frame, // the remote frame, if any
callerWindow, // the window that we will call with
targetOrigin; // the domain to communicate with
/**
* Resolves the origin from the event object
* @private
* @param {Object} event The messageevent
* @return {String} The scheme, host and port of the origin
*/
function _getOrigin(event){
if (event.origin) {
// This is the HTML5 property
return getLocation(event.origin);
}
if (event.uri) {
// From earlier implementations
return getLocation(event.uri);
}
if (event.domain) {
// This is the last option and will fail if the
// origin is not using the same schema as we are
return location.protocol + "//" + event.domain;
}
throw "Unable to retrieve the origin of the event";
}
/**
* This is the main implementation for the onMessage event.<br/>
* It checks the validity of the origin and passes the message on if appropriate.
* @private
* @param {Object} event The messageevent
*/
function _window_onMessage(event){
var origin = _getOrigin(event);
if (origin == targetOrigin && event.data.substring(0, config.channel.length + 1) == config.channel + " ") {
pub.up.incoming(event.data.substring(config.channel.length + 1), origin);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callerWindow.postMessage(config.channel + " " + message, domain || targetOrigin);
if (fn) {
fn();
}
},
destroy: function(){
un(window, "message", _window_onMessage);
if (frame) {
callerWindow = null;
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// add the event handler for listening
var waitForReady = function(event){
if (event.data == config.channel + "-ready") {
// replace the eventlistener
callerWindow = ("postMessage" in frame.contentWindow) ? frame.contentWindow : frame.contentWindow.document;
un(window, "message", waitForReady);
on(window, "message", _window_onMessage);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
};
on(window, "message", waitForReady);
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 1 // 1 = PostMessage
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
}
else {
// add the event handler for listening
on(window, "message", _window_onMessage);
callerWindow = ("postMessage" in window.parent) ? window.parent : window.parent.document;
callerWindow.postMessage(config.channel + "-ready", targetOrigin);
setTimeout(function(){
pub.up.callback(true);
}, 0);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, appendQueryParameters, createFrame, debug, apply, query, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.FrameElementTransport
* FrameElementTransport is a transport class that can be used with Gecko-browser as these allow passing variables using the frameElement property.<br/>
* Security is maintained as Gecho uses Lexical Authorization to determine under which scope a function is running.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remote The remote document to communicate with.
*/
easyXDM.stack.FrameElementTransport = function(config){
var pub, frame, send, targetOrigin;
return (pub = {
outgoing: function(message, domain, fn){
send.call(this, message);
if (fn) {
fn();
}
},
destroy: function(){
if (frame) {
frame.parentNode.removeChild(frame);
frame = null;
}
},
onDOMReady: function(){
targetOrigin = getLocation(config.remote);
if (config.isHost) {
// set up the iframe
apply(config.props, {
src: appendQueryParameters(config.remote, {
xdm_e: getLocation(location.href),
xdm_c: config.channel,
xdm_p: 5 // 5 = FrameElementTransport
}),
name: IFRAME_PREFIX + config.channel + "_provider"
});
frame = createFrame(config);
frame.fn = function(sendFn){
delete frame.fn;
send = sendFn;
setTimeout(function(){
pub.up.callback(true);
}, 0);
// remove the function so that it cannot be used to overwrite the send function later on
return function(msg){
pub.up.incoming(msg, targetOrigin);
};
};
}
else {
// This is to mitigate origin-spoofing
if (document.referrer && getLocation(document.referrer) != query.xdm_e) {
window.top.location = query.xdm_e;
}
send = window.frameElement.fn(function(msg){
pub.up.incoming(msg, targetOrigin);
});
pub.up.callback(true);
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getLocation, appendQueryParameters, resolveUrl, createFrame, debug, un, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.NameTransport
* NameTransport uses the window.name property to relay data.
* The <code>local</code> parameter needs to be set on both the consumer and provider,<br/>
* and the <code>remoteHelper</code> parameter needs to be set on the consumer.
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String} remoteHelper The url to the remote instance of hash.html - this is only needed for the host.
* @namespace easyXDM.stack
*/
easyXDM.stack.NameTransport = function(config){
var pub; // the public interface
var isHost, callerWindow, remoteWindow, readyCount, callback, remoteOrigin, remoteUrl;
function _sendMessage(message){
var url = config.remoteHelper + (isHost ? "#_3" : "#_2") + config.channel;
callerWindow.contentWindow.sendMessage(message, url);
}
function _onReady(){
if (isHost) {
if (++readyCount === 2 || !isHost) {
pub.up.callback(true);
}
}
else {
_sendMessage("ready");
pub.up.callback(true);
}
}
function _onMessage(message){
pub.up.incoming(message, remoteOrigin);
}
function _onLoad(){
if (callback) {
setTimeout(function(){
callback(true);
}, 0);
}
}
return (pub = {
outgoing: function(message, domain, fn){
callback = fn;
_sendMessage(message);
},
destroy: function(){
callerWindow.parentNode.removeChild(callerWindow);
callerWindow = null;
if (isHost) {
remoteWindow.parentNode.removeChild(remoteWindow);
remoteWindow = null;
}
},
onDOMReady: function(){
isHost = config.isHost;
readyCount = 0;
remoteOrigin = getLocation(config.remote);
config.local = resolveUrl(config.local);
if (isHost) {
// Register the callback
easyXDM.Fn.set(config.channel, function(message){
if (isHost && message === "ready") {
// Replace the handler
easyXDM.Fn.set(config.channel, _onMessage);
_onReady();
}
});
// Set up the frame that points to the remote instance
remoteUrl = appendQueryParameters(config.remote, {
xdm_e: config.local,
xdm_c: config.channel,
xdm_p: 2
});
apply(config.props, {
src: remoteUrl + '#' + config.channel,
name: IFRAME_PREFIX + config.channel + "_provider"
});
remoteWindow = createFrame(config);
}
else {
config.remoteHelper = config.remote;
easyXDM.Fn.set(config.channel, _onMessage);
}
// Set up the iframe that will be used for the transport
callerWindow = createFrame({
props: {
src: config.local + "#_4" + config.channel
},
onLoad: function onLoad(){
// Remove the handler
var w = callerWindow || this;
un(w, "load", onLoad);
easyXDM.Fn.set(config.channel + "_load", _onLoad);
(function test(){
if (typeof w.contentWindow.sendMessage == "function") {
_onReady();
}
else {
setTimeout(test, 50);
}
}());
}
});
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, getLocation, createFrame, debug, un, on, apply, whenReady, IFRAME_PREFIX*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.HashTransport
* HashTransport is a transport class that uses the IFrame URL Technique for communication.<br/>
* <a href="http://msdn.microsoft.com/en-us/library/bb735305.aspx">http://msdn.microsoft.com/en-us/library/bb735305.aspx</a><br/>
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The transports configuration.
* @cfg {String/Window} local The url to the local file used for proxying messages, or the local window.
* @cfg {Number} delay The number of milliseconds easyXDM should try to get a reference to the local window.
* @cfg {Number} interval The interval used when polling for messages.
*/
easyXDM.stack.HashTransport = function(config){
var pub;
var me = this, isHost, _timer, pollInterval, _lastMsg, _msgNr, _listenerWindow, _callerWindow;
var useParent, _remoteOrigin;
function _sendMessage(message){
if (!_callerWindow) {
return;
}
var url = config.remote + "#" + (_msgNr++) + "_" + message;
((isHost || !useParent) ? _callerWindow.contentWindow : _callerWindow).location = url;
}
function _handleHash(hash){
_lastMsg = hash;
pub.up.incoming(_lastMsg.substring(_lastMsg.indexOf("_") + 1), _remoteOrigin);
}
/**
* Checks location.hash for a new message and relays this to the receiver.
* @private
*/
function _pollHash(){
if (!_listenerWindow) {
return;
}
var href = _listenerWindow.location.href, hash = "", indexOf = href.indexOf("#");
if (indexOf != -1) {
hash = href.substring(indexOf);
}
if (hash && hash != _lastMsg) {
_handleHash(hash);
}
}
function _attachListeners(){
_timer = setInterval(_pollHash, pollInterval);
}
return (pub = {
outgoing: function(message, domain){
_sendMessage(message);
},
destroy: function(){
window.clearInterval(_timer);
if (isHost || !useParent) {
_callerWindow.parentNode.removeChild(_callerWindow);
}
_callerWindow = null;
},
onDOMReady: function(){
isHost = config.isHost;
pollInterval = config.interval;
_lastMsg = "#" + config.channel;
_msgNr = 0;
useParent = config.useParent;
_remoteOrigin = getLocation(config.remote);
if (isHost) {
config.props = {
src: config.remote,
name: IFRAME_PREFIX + config.channel + "_provider"
};
if (useParent) {
config.onLoad = function(){
_listenerWindow = window;
_attachListeners();
pub.up.callback(true);
};
}
else {
var tries = 0, max = config.delay / 50;
(function getRef(){
if (++tries > max) {
throw new Error("Unable to reference listenerwindow");
}
try {
_listenerWindow = _callerWindow.contentWindow.frames[IFRAME_PREFIX + config.channel + "_consumer"];
}
catch (ex) {
}
if (_listenerWindow) {
_attachListeners();
pub.up.callback(true);
}
else {
setTimeout(getRef, 50);
}
}());
}
_callerWindow = createFrame(config);
}
else {
_listenerWindow = window;
_attachListeners();
if (useParent) {
_callerWindow = parent;
pub.up.callback(true);
}
else {
apply(config, {
props: {
src: config.remote + "#" + config.channel + new Date(),
name: IFRAME_PREFIX + config.channel + "_consumer"
},
onLoad: function(){
pub.up.callback(true);
}
});
_callerWindow = createFrame(config);
}
}
},
init: function(){
whenReady(pub.onDOMReady, pub);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.ReliableBehavior
* This is a behavior that tries to make the underlying transport reliable by using acknowledgements.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
*/
easyXDM.stack.ReliableBehavior = function(config){
var pub, // the public interface
callback; // the callback to execute when we have a confirmed success/failure
var idOut = 0, idIn = 0, currentMessage = "";
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_"), ack = message.substring(0, indexOf).split(",");
message = message.substring(indexOf + 1);
if (ack[0] == idOut) {
currentMessage = "";
if (callback) {
callback(true);
}
}
if (message.length > 0) {
pub.down.outgoing(ack[1] + "," + idOut + "_" + currentMessage, origin);
if (idIn != ack[1]) {
idIn = ack[1];
pub.up.incoming(message, origin);
}
}
},
outgoing: function(message, origin, fn){
currentMessage = message;
callback = fn;
pub.down.outgoing(idIn + "," + (++idOut) + "_" + message, origin);
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, debug, undef, removeFromStack*/
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.QueueBehavior
* This is a behavior that enables queueing of messages. <br/>
* It will buffer incoming messages and dispach these as fast as the underlying transport allows.
* This will also fragment/defragment messages so that the outgoing message is never bigger than the
* set length.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration. Optional.
* @cfg {Number} maxLength The maximum length of each outgoing message. Set this to enable fragmentation.
*/
easyXDM.stack.QueueBehavior = function(config){
var pub, queue = [], waiting = true, incoming = "", destroying, maxLength = 0, lazy = false, doFragment = false;
function dispatch(){
if (config.remove && queue.length === 0) {
removeFromStack(pub);
return;
}
if (waiting || queue.length === 0 || destroying) {
return;
}
waiting = true;
var message = queue.shift();
pub.down.outgoing(message.data, message.origin, function(success){
waiting = false;
if (message.callback) {
setTimeout(function(){
message.callback(success);
}, 0);
}
dispatch();
});
}
return (pub = {
init: function(){
if (undef(config)) {
config = {};
}
if (config.maxLength) {
maxLength = config.maxLength;
doFragment = true;
}
if (config.lazy) {
lazy = true;
}
else {
pub.down.init();
}
},
callback: function(success){
waiting = false;
var up = pub.up; // in case dispatch calls removeFromStack
dispatch();
up.callback(success);
},
incoming: function(message, origin){
if (doFragment) {
var indexOf = message.indexOf("_"), seq = parseInt(message.substring(0, indexOf), 10);
incoming += message.substring(indexOf + 1);
if (seq === 0) {
if (config.encode) {
incoming = decodeURIComponent(incoming);
}
pub.up.incoming(incoming, origin);
incoming = "";
}
}
else {
pub.up.incoming(message, origin);
}
},
outgoing: function(message, origin, fn){
if (config.encode) {
message = encodeURIComponent(message);
}
var fragments = [], fragment;
if (doFragment) {
// fragment into chunks
while (message.length !== 0) {
fragment = message.substring(0, maxLength);
message = message.substring(fragment.length);
fragments.push(fragment);
}
// enqueue the chunks
while ((fragment = fragments.shift())) {
queue.push({
data: fragments.length + "_" + fragment,
origin: origin,
callback: fragments.length === 0 ? fn : null
});
}
}
else {
queue.push({
data: message,
origin: origin,
callback: fn
});
}
if (lazy) {
pub.down.init();
}
else {
dispatch();
}
},
destroy: function(){
destroying = true;
pub.down.destroy();
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, debug */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.VerifyBehavior
* This behavior will verify that communication with the remote end is possible, and will also sign all outgoing,
* and verify all incoming messages. This removes the risk of someone hijacking the iframe to send malicious messages.
* @namespace easyXDM.stack
* @constructor
* @param {Object} config The behaviors configuration.
* @cfg {Boolean} initiate If the verification should be initiated from this end.
*/
easyXDM.stack.VerifyBehavior = function(config){
var pub, mySecret, theirSecret, verified = false;
function startVerification(){
mySecret = Math.random().toString(16).substring(2);
pub.down.outgoing(mySecret);
}
return (pub = {
incoming: function(message, origin){
var indexOf = message.indexOf("_");
if (indexOf === -1) {
if (message === mySecret) {
pub.up.callback(true);
}
else if (!theirSecret) {
theirSecret = message;
if (!config.initiate) {
startVerification();
}
pub.down.outgoing(message);
}
}
else {
if (message.substring(0, indexOf) === theirSecret) {
pub.up.incoming(message.substring(indexOf + 1), origin);
}
}
},
outgoing: function(message, origin, fn){
pub.down.outgoing(mySecret + "_" + message, origin, fn);
},
callback: function(success){
if (config.initiate) {
startVerification();
}
}
});
};
/*jslint evil: true, browser: true, immed: true, passfail: true, undef: true, newcap: true*/
/*global easyXDM, window, escape, unescape, undef, getJSON, debug, emptyFn, isArray */
//
// easyXDM
// http://easyxdm.net/
// Copyright(c) 2009-2011, Øyvind Sean Kinsey, oyvind@kinsey.no.
//
// 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.
//
/**
* @class easyXDM.stack.RpcBehavior
* This uses JSON-RPC 2.0 to expose local methods and to invoke remote methods and have responses returned over the the string based transport stack.<br/>
* Exposed methods can return values synchronous, asyncronous, or bet set up to not return anything.
* @namespace easyXDM.stack
* @constructor
* @param {Object} proxy The object to apply the methods to.
* @param {Object} config The definition of the local and remote interface to implement.
* @cfg {Object} local The local interface to expose.
* @cfg {Object} remote The remote methods to expose through the proxy.
* @cfg {Object} serializer The serializer to use for serializing and deserializing the JSON. Should be compatible with the HTML5 JSON object. Optional, will default to JSON.
*/
easyXDM.stack.RpcBehavior = function(proxy, config){
var pub, serializer = config.serializer || getJSON();
var _callbackCounter = 0, _callbacks = {};
/**
* Serializes and sends the message
* @private
* @param {Object} data The JSON-RPC message to be sent. The jsonrpc property will be added.
*/
function _send(data){
data.jsonrpc = "2.0";
pub.down.outgoing(serializer.stringify(data));
}
/**
* Creates a method that implements the given definition
* @private
* @param {Object} The method configuration
* @param {String} method The name of the method
* @return {Function} A stub capable of proxying the requested method call
*/
function _createMethod(definition, method){
var slice = Array.prototype.slice;
return function(){
var l = arguments.length, callback, message = {
method: method
};
if (l > 0 && typeof arguments[l - 1] === "function") {
//with callback, procedure
if (l > 1 && typeof arguments[l - 2] === "function") {
// two callbacks, success and error
callback = {
success: arguments[l - 2],
error: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 2);
}
else {
// single callback, success
callback = {
success: arguments[l - 1]
};
message.params = slice.call(arguments, 0, l - 1);
}
_callbacks["" + (++_callbackCounter)] = callback;
message.id = _callbackCounter;
}
else {
// no callbacks, a notification
message.params = slice.call(arguments, 0);
}
if (definition.namedParams && message.params.length === 1) {
message.params = message.params[0];
}
// Send the method request
_send(message);
};
}
/**
* Executes the exposed method
* @private
* @param {String} method The name of the method
* @param {Number} id The callback id to use
* @param {Function} method The exposed implementation
* @param {Array} params The parameters supplied by the remote end
*/
function _executeMethod(method, id, fn, params){
if (!fn) {
if (id) {
_send({
id: id,
error: {
code: -32601,
message: "Procedure not found."
}
});
}
return;
}
var success, error;
if (id) {
success = function(result){
success = emptyFn;
_send({
id: id,
result: result
});
};
error = function(message, data){
error = emptyFn;
var msg = {
id: id,
error: {
code: -32099,
message: message
}
};
if (data) {
msg.error.data = data;
}
_send(msg);
};
}
else {
success = error = emptyFn;
}
// Call local method
if (!isArray(params)) {
params = [params];
}
try {
var result = fn.method.apply(fn.scope, params.concat([success, error]));
if (!undef(result)) {
success(result);
}
}
catch (ex1) {
error(ex1.message);
}
}
return (pub = {
incoming: function(message, origin){
var data = serializer.parse(message);
if (data.method) {
// A method call from the remote end
if (config.handle) {
config.handle(data, _send);
}
else {
_executeMethod(data.method, data.id, config.local[data.method], data.params);
}
}
else {
// A method response from the other end
var callback = _callbacks[data.id];
if (data.error) {
if (callback.error) {
callback.error(data.error);
}
}
else if (callback.success) {
callback.success(data.result);
}
delete _callbacks[data.id];
}
},
init: function(){
if (config.remote) {
// Implement the remote sides exposed methods
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method)) {
proxy[method] = _createMethod(config.remote[method], method);
}
}
}
pub.down.init();
},
destroy: function(){
for (var method in config.remote) {
if (config.remote.hasOwnProperty(method) && proxy.hasOwnProperty(method)) {
delete proxy[method];
}
}
pub.down.destroy();
}
});
};
global.easyXDM = easyXDM;
})(window, document, location, window.setTimeout, decodeURIComponent, encodeURIComponent);
/*!
* F2 v1.3.3 04-07-2014
* Copyright (c) 2013 Markit On Demand, Inc. http://www.openf2.org
*
* "F2" is 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.
*
* Please note that F2 ("Software") may contain third party material that Markit
* On Demand Inc. has a license to use and include within the Software (the
* "Third Party Material"). A list of the software comprising the Third Party Material
* and the terms and conditions under which such Third Party Material is distributed
* are reproduced in the ThirdPartyMaterial.md file available at:
*
* https://github.com/OpenF2/F2/blob/master/ThirdPartyMaterial.md
*
* The inclusion of the Third Party Material in the Software does not grant, provide
* nor result in you having acquiring any rights whatsoever, other than as stipulated
* in the terms and conditions related to the specific Third Party Material, if any.
*
*/
var F2;
/**
* Open F2
* @module f2
* @main f2
*/
F2 = (function() {
/**
* Abosolutizes a relative URL
* @method _absolutizeURI
* @private
* @param {e.g., location.href} base
* @param {URL to absolutize} href
* @returns {string} URL
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _absolutizeURI = function(base, href) {// RFC 3986
function removeDotSegments(input) {
var output = [];
input.replace(/^(\.\.?(\/|$))+/, '')
.replace(/\/(\.(\/|$))+/g, '/')
.replace(/\/\.\.$/, '/../')
.replace(/\/?[^\/]*/g, function (p) {
if (p === '/..') {
output.pop();
} else {
output.push(p);
}
});
return output.join('').replace(/^\//, input.charAt(0) === '/' ? '/' : '');
}
href = _parseURI(href || '');
base = _parseURI(base || '');
return !href || !base ? null : (href.protocol || base.protocol) +
(href.protocol || href.authority ? href.authority : base.authority) +
removeDotSegments(href.protocol || href.authority || href.pathname.charAt(0) === '/' ? href.pathname : (href.pathname ? ((base.authority && !base.pathname ? '/' : '') + base.pathname.slice(0, base.pathname.lastIndexOf('/') + 1) + href.pathname) : base.pathname)) +
(href.protocol || href.authority || href.pathname ? href.search : (href.search || base.search)) +
href.hash;
};
/**
* Parses URI
* @method _parseURI
* @private
* @param {The URL to parse} url
* @returns {Parsed URL} string
* Source: https://gist.github.com/Yaffle/1088850
* Tests: http://skew.org/uri/uri_tests.html
*/
var _parseURI = function(url) {
var m = String(url).replace(/^\s+|\s+$/g, '').match(/^([^:\/?#]+:)?(\/\/(?:[^:@]*(?::[^:@]*)?@)?(([^:\/?#]*)(?::(\d*))?))?([^?#]*)(\?[^#]*)?(#[\s\S]*)?/);
// authority = '//' + user + ':' + pass '@' + hostname + ':' port
return (m ? {
href : m[0] || '',
protocol : m[1] || '',
authority: m[2] || '',
host : m[3] || '',
hostname : m[4] || '',
port : m[5] || '',
pathname : m[6] || '',
search : m[7] || '',
hash : m[8] || ''
} : null);
};
return {
/**
* A function to pass into F2.stringify which will prevent circular
* reference errors when serializing objects
* @method appConfigReplacer
*/
appConfigReplacer: function(key, value) {
if (key == 'root' || key == 'ui' || key == 'height') {
return undefined;
} else {
return value;
}
},
/**
* The apps namespace is a place for app developers to put the javascript
* class that is used to initialize their app. The javascript classes should
* be namepaced with the {{#crossLink "F2.AppConfig"}}{{/crossLink}}.appId.
* It is recommended that the code be placed in a closure to help keep the
* global namespace clean.
*
* If the class has an 'init' function, that function will be called
* automatically by F2.
* @property Apps
* @type object
* @example
* F2.Apps["com_example_helloworld"] = (function() {
* var App_Class = function(appConfig, appContent, root) {
* this._app = appConfig; // the F2.AppConfig object
* this._appContent = appContent // the F2.AppManifest.AppContent object
* this.$root = $(root); // the root DOM Element that contains this app
* }
*
* App_Class.prototype.init = function() {
* // perform init actions
* }
*
* return App_Class;
* })();
* @example
* F2.Apps["com_example_helloworld"] = function(appConfig, appContent, root) {
* return {
* init:function() {
* // perform init actions
* }
* };
* };
* @for F2
*/
Apps: {},
/**
* Creates a namespace on F2 and copies the contents of an object into
* that namespace optionally overwriting existing properties.
* @method extend
* @param {string} ns The namespace to create. Pass a falsy value to
* add properties to the F2 namespace directly.
* @param {object} obj The object to copy into the namespace.
* @param {bool} overwrite True if object properties should be overwritten
* @return {object} The created object
*/
extend: function (ns, obj, overwrite) {
var isFunc = typeof obj === 'function';
var parts = ns ? ns.split('.') : [];
var parent = this;
obj = obj || {};
// ignore leading global
if (parts[0] === 'F2') {
parts = parts.slice(1);
}
// create namespaces
for (var i = 0, len = parts.length; i < len; i++) {
if (!parent[parts[i]]) {
parent[parts[i]] = isFunc && i + 1 == len ? obj : {};
}
parent = parent[parts[i]];
}
// copy object into namespace
if (!isFunc) {
for (var prop in obj) {
if (typeof parent[prop] === 'undefined' || overwrite) {
parent[prop] = obj[prop];
}
}
}
return parent;
},
/**
* Generates a somewhat random id
* @method guid
* @return {string} A random id
* @for F2
*/
guid: function() {
var S4 = function() {
return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
};
return (S4()+S4()+'-'+S4()+'-'+S4()+'-'+S4()+'-'+S4()+S4()+S4());
},
/**
* Search for a value within an array.
* @method inArray
* @param {object} value The value to search for
* @param {Array} array The array to search
* @return {bool} True if the item is in the array
*/
inArray: function(value, array) {
return jQuery.inArray(value, array) > -1;
},
/**
* Tests a URL to see if it's on the same domain (local) or not
* @method isLocalRequest
* @param {URL to test} url
* @returns {bool} Whether the URL is local or not
* Derived from: https://github.com/jquery/jquery/blob/master/src/ajax.js
*/
isLocalRequest: function(url){
var rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
urlLower = url.toLowerCase(),
parts = rurl.exec( urlLower ),
ajaxLocation,
ajaxLocParts;
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement('a');
ajaxLocation.href = '';
ajaxLocation = ajaxLocation.href;
}
ajaxLocation = ajaxLocation.toLowerCase();
// uh oh, the url must be relative
// make it fully qualified and re-regex url
if (!parts){
urlLower = _absolutizeURI(ajaxLocation,urlLower).toLowerCase();
parts = rurl.exec( urlLower );
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation ) || [];
// do hostname and protocol and port of manifest URL match location.href? (a "local" request on the same domain)
var matched = !(parts &&
(parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
(parts[ 3 ] || (parts[ 1 ] === 'http:' ? '80' : '443')) !==
(ajaxLocParts[ 3 ] || (ajaxLocParts[ 1 ] === 'http:' ? '80' : '443'))));
return matched;
},
/**
* Utility method to determine whether or not the argument passed in is or is not a native dom node.
* @method isNativeDOMNode
* @param {object} testObject The object you want to check as native dom node.
* @return {bool} Returns true if the object passed is a native dom node.
*/
isNativeDOMNode: function(testObject) {
var bIsNode = (
typeof Node === 'object' ? testObject instanceof Node :
testObject && typeof testObject === 'object' && typeof testObject.nodeType === 'number' && typeof testObject.nodeName === 'string'
);
var bIsElement = (
typeof HTMLElement === 'object' ? testObject instanceof HTMLElement : //DOM2
testObject && typeof testObject === 'object' && testObject.nodeType === 1 && typeof testObject.nodeName === 'string'
);
return (bIsNode || bIsElement);
},
/**
* A utility logging function to write messages or objects to the browser console. This is a proxy for the [`console` API](https://developers.google.com/chrome-developer-tools/docs/console).
* @method log
* @param {object|string} Object/Method An object to be logged _or_ a `console` API method name, such as `warn` or `error`. All of the console method names are [detailed in the Chrome docs](https://developers.google.com/chrome-developer-tools/docs/console-api).
* @param {object} [obj2]* An object to be logged
* @example
//Pass any object (string, int, array, object, bool) to .log()
F2.log('foo');
F2.log(myArray);
//Use a console method name as the first argument.
F2.log('error', err);
F2.log('info', 'The session ID is ' + sessionId);
* Some code derived from [HTML5 Boilerplate console plugin](https://github.com/h5bp/html5-boilerplate/blob/master/js/plugins.js)
*/
log: function() {
var _log;
var _logMethod = 'log';
var method;
var noop = function () { };
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'
];
var length = methods.length;
var console = (window.console = window.console || {});
var args;
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
//if first arg is a console function, use it.
//defaults to console.log()
if (arguments && arguments.length > 1 && arguments[0] == method){
_logMethod = method;
//remove console func from args
args = Array.prototype.slice.call(arguments, 1);
}
}
if (Function.prototype.bind) {
_log = Function.prototype.bind.call(console[_logMethod], console);
} else {
_log = function() {
Function.prototype.apply.call(console[_logMethod], console, (args || arguments));
};
}
_log.apply(this, (args || arguments));
},
/**
* Wrapper to convert a JSON string to an object
* @method parse
* @param {string} str The JSON string to convert
* @return {object} The parsed object
*/
parse: function(str) {
return JSON.parse(str);
},
/**
* Wrapper to convert an object to JSON
*
* **Note: When using F2.stringify on an F2.AppConfig object, it is
* recommended to pass F2.appConfigReplacer as the replacer function in
* order to prevent circular serialization errors.**
* @method stringify
* @param {object} value The object to convert
* @param {function|Array} replacer An optional parameter that determines
* how object values are stringified for objects. It can be a function or an
* array of strings.
* @param {int|string} space An optional parameter that specifies the
* indentation of nested structures. If it is omitted, the text will be
* packed without extra whitespace. If it is a number, it will specify the
* number of spaces to indent at each level. If it is a string (such as '\t'
* or ' '), it contains the characters used to indent at each level.
* @return {string} The JSON string
*/
stringify: function(value, replacer, space) {
return JSON.stringify(value, replacer, space);
},
/**
* Function to get the F2 version number
* @method version
* @return {string} F2 version number
*/
version: function() { return '1.3.3'; }
};
})();
/**
* The new `AppHandlers` functionality provides Container Developers a higher level of control over configuring app rendering and interaction.
*
*<p class="alert alert-block alert-warning">
*The addition of `F2.AppHandlers` replaces the previous {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} properties `beforeAppRender`, `appRender`, and `afterAppRender`. These methods were deprecated—but not removed—in version 1.2. They will be permanently removed in a future version of F2.
*</p>
*
*<p class="alert alert-block alert-info">
*Starting with F2 version 1.2, `AppHandlers` is the preferred method for Container Developers to manage app layout.
*</p>
*
* ### Order of Execution
*
* **App Rendering**
*
* 0. {{#crossLink "F2/registerApps"}}F2.registerApps(){{/crossLink}} method is called by the Container Developer and the following methods are run for *each* {{#crossLink "F2.AppConfig"}}{{/crossLink}} passed.
* 1. **'appCreateRoot'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_CREATE\_ROOT*) handlers are fired in the order they were attached.
* 2. **'appRenderBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_BEFORE*) handlers are fired in the order they were attached.
* 3. Each app's `manifestUrl` is requested asynchronously; on success the following methods are fired.
* 3. **'appRender'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER*) handlers are fired in the order they were attached.
* 4. **'appRenderAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_RENDER\_AFTER*) handlers are fired in the order they were attached.
*
*
* **App Removal**
* 0. {{#crossLink "F2/removeApp"}}F2.removeApp(){{/crossLink}} with a specific {{#crossLink "F2.AppConfig/instanceId "}}{{/crossLink}} or {{#crossLink "F2/removeAllApps"}}F2.removeAllApps(){{/crossLink}} method is called by the Container Developer and the following methods are run.
* 1. **'appDestroyBefore'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_BEFORE*) handlers are fired in the order they were attached.
* 2. **'appDestroy'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY*) handlers are fired in the order they were attached.
* 3. **'appDestroyAfter'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_DESTROY\_AFTER*) handlers are fired in the order they were attached.
*
* **Error Handling**
* 0. **'appScriptLoadFailed'** (*{{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.APP\_SCRIPT\_LOAD\_FAILED*) handlers are fired in the order they were attached.
*
* @class F2.AppHandlers
*/
F2.extend('AppHandlers', (function() {
// the hidden token that we will check against every time someone tries to add, remove, fire handler
var _ct = F2.guid();
var _f2t = F2.guid();
var _handlerCollection = {
appCreateRoot: [],
appRenderBefore: [],
appDestroyBefore: [],
appRenderAfter: [],
appDestroyAfter: [],
appRender: [],
appDestroy: [],
appScriptLoadFailed: []
};
var _defaultMethods = {
appRender: function(appConfig, appHtml)
{
var $root = null;
// if no app root is defined use the app's outer most node
if(!F2.isNativeDOMNode(appConfig.root))
{
appConfig.root = jQuery(appHtml).get(0);
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
}
else
{
// get a handle on the root in jQuery
$root = jQuery(appConfig.root);
// append the app html to the root
$root.append(appHtml);
}
// append the root to the body by default.
jQuery('body').append($root);
},
appDestroy: function(appInstance)
{
// call the apps destroy method, if it has one
if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
{
appInstance.app.destroy();
}
// warn the Container and App Developer that even though they have a destroy method it hasn't been
else if(appInstance && appInstance.app && appInstance.app.destroy)
{
F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
}
// fade out and remove the root
jQuery(appInstance.config.root).fadeOut(500, function() {
jQuery(this).remove();
});
}
};
var _createHandler = function(token, sNamespace, func_or_element, bDomNodeAppropriate)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(token);
// create handler structure. Not all arguments properties will be populated/used.
var handler = {
func: (typeof(func_or_element)) ? func_or_element : null,
namespace: sNamespace,
domNode: (F2.isNativeDOMNode(func_or_element)) ? func_or_element : null
};
if(!handler.func && !handler.domNode)
{
throw ('Invalid or null argument passed. Handler will not be added to collection. A valid dom element or callback function is required.');
}
if(handler.domNode && !bDomNodeAppropriate)
{
throw ('Invalid argument passed. Handler will not be added to collection. A callback function is required for this event type.');
}
return handler;
};
var _validateToken = function(sToken)
{
// check token against F2 and container
if(_ct != sToken && _f2t != sToken) { throw ('Invalid token passed. Please verify that you have correctly received and stored token from F2.AppHandlers.getToken().'); }
};
var _removeHandler = function(sToken, eventKey, sNamespace)
{
// will throw an exception and stop execution if the token is invalid
_validateToken(sToken);
if(!sNamespace && !eventKey)
{
return;
}
// remove by event key
else if(!sNamespace && eventKey)
{
_handlerCollection[eventKey] = [];
}
// remove by namespace only
else if(sNamespace && !eventKey)
{
sNamespace = sNamespace.toLowerCase();
for(var currentEventKey in _handlerCollection)
{
var eventCollection = _handlerCollection[currentEventKey];
var newEvents = [];
for(var i = 0, ec = eventCollection.length; i < ec; i++)
{
var currentEventHandler = eventCollection[i];
if(currentEventHandler)
{
if(!currentEventHandler.namespace || currentEventHandler.namespace.toLowerCase() != sNamespace)
{
newEvents.push(currentEventHandler);
}
}
}
eventCollection = newEvents;
}
}
else if(sNamespace && _handlerCollection[eventKey])
{
sNamespace = sNamespace.toLowerCase();
var newHandlerCollection = [];
for(var iCounter = 0, hc = _handlerCollection[eventKey].length; iCounter < hc; iCounter++)
{
var currentHandler = _handlerCollection[eventKey][iCounter];
if(currentHandler)
{
if(!currentHandler.namespace || currentHandler.namespace.toLowerCase() != sNamespace)
{
newHandlerCollection.push(currentHandler);
}
}
}
_handlerCollection[eventKey] = newHandlerCollection;
}
};
return {
/**
* Allows Container Developer to retrieve a unique token which must be passed to
* all `on` and `off` methods. This function will self destruct and can only be called
* one time. Container Developers must store the return value inside of a closure.
* @method getToken
**/
getToken: function()
{
// delete this method for security that way only the container has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.getToken;
// return the token, which we validate against.
return _ct;
},
/**
* Allows F2 to get a token internally. Token is required to call {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}.
* This function will self destruct to eliminate other sources from using the {{#crossLink "F2.AppHandlers/\_\_trigger:method"}}{{/crossLink}}
* and additional internal methods.
* @method __f2GetToken
* @private
**/
__f2GetToken: function()
{
// delete this method for security that way only the F2 internally has access to the token 1 time.
// kind of Ethan Hunt-ish, this message will self destruct immediately.
delete this.__f2GetToken;
// return the token, which we validate against.
return _f2t;
},
/**
* Allows F2 to trigger specific events internally.
* @method __trigger
* @private
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/\_\_f2GetToken:method"}}{{/crossLink}}.
* @param {String} eventKey The event to fire. The complete list of event keys is available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
**/
__trigger: function(token, eventKey) // additional arguments will likely be passed
{
// will throw an exception and stop execution if the token is invalid
if(token != _f2t)
{
throw ('Token passed is invalid. Only F2 is allowed to call F2.AppHandlers.__trigger().');
}
if(_handlerCollection && _handlerCollection[eventKey])
{
// create a collection of arguments that are safe to pass to the callback.
var passableArgs = [];
// populate that collection with all arguments except token and eventKey
for(var i = 2, j = arguments.length; i < j; i++)
{
passableArgs.push(arguments[i]);
}
if(_handlerCollection[eventKey].length === 0 && _defaultMethods[eventKey])
{
_defaultMethods[eventKey].apply(F2, passableArgs);
return this;
}
else if(_handlerCollection[eventKey].length === 0 && !_handlerCollection[eventKey])
{
return this;
}
// fire all event listeners in the order that they were added.
for(var iCounter = 0, hcl = _handlerCollection[eventKey].length; iCounter < hcl; iCounter++)
{
var handler = _handlerCollection[eventKey][iCounter];
// appRender where root is already defined
if (handler.domNode && arguments[2] && arguments[2].root && arguments[3])
{
var $appRoot = jQuery(arguments[2].root).append(arguments[3]);
jQuery(handler.domNode).append($appRoot);
}
else if (handler.domNode && arguments[2] && !arguments[2].root && arguments[3])
{
// set the root to the actual HTML of the app
arguments[2].root = jQuery(arguments[3]).get(0);
// appends the root to the dom node specified
jQuery(handler.domNode).append(arguments[2].root);
}
else
{
handler.func.apply(F2, passableArgs);
}
}
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to easily tell all apps to render in a specific location. Only valid for eventType `appRender`.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {HTMLElement} element Specific DOM element to which app gets appended.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRender',
* document.getElementById('my_app')
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRender.myNamespace',
* document.getElementById('my_app')
* );
**/
/**
* Allows Container Developer to add listener method that will be triggered when a specific event occurs.
* @method on
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. The namespace is useful for removal
* purposes. At this time it does not affect when an event is fired. Complete list of event keys available in
* {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @params {Function} listener A function that will be triggered when a specific event occurs. For detailed argument definition refer to {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore'
* function() { F2.log('before app rendered!'); }
* );
*
* Or:
* @example
* F2.AppHandlers.on(
* _token,
* 'appRenderBefore.myNamespace',
* function() { F2.log('before app rendered!'); }
* );
**/
on: function(token, eventKey, func_or_element)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_handlerCollection[eventKey].push(
_createHandler(
token,
sNamespace,
func_or_element,
(eventKey == 'appRender')
)
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
},
/**
* Allows Container Developer to remove listener methods for specific events
* @method off
* @chainable
* @param {String} token The token received from {{#crossLink "F2.AppHandlers/getToken:method"}}{{/crossLink}}.
* @param {String} eventKey{.namespace} The event key used to determine which event to attach the listener to. If no namespace is provided all
* listeners for the specified event type will be removed.
* Complete list available in {{#crossLink "F2.Constants.AppHandlers"}}{{/crossLink}}.
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.off(_token,'appRenderBefore');
*
**/
off: function(token, eventKey)
{
var sNamespace = null;
if(!eventKey)
{
throw ('eventKey must be of type string and not null. For available appHandlers check F2.Constants.AppHandlers.');
}
// we need to check the key for a namespace
if(eventKey.indexOf('.') > -1)
{
var arData = eventKey.split('.');
eventKey = arData[0];
sNamespace = arData[1];
}
if(_handlerCollection && _handlerCollection[eventKey])
{
_removeHandler(
token,
eventKey,
sNamespace
);
}
else
{
throw ('Invalid EventKey passed. Check your inputs and try again.');
}
return this;
}
};
})());
F2.extend('Constants', {
/**
* A convenient collection of all available appHandler events.
* @class F2.Constants.AppHandlers
**/
AppHandlers: (function()
{
return {
/**
* Equivalent to `appCreateRoot`. Identifies the create root method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_CREATE_ROOT
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_CREATE_ROOT,
* function(appConfig)
* {
* // If you want to create a custom root. By default F2 uses the app's outermost HTML element.
* // the app's html is not available until after the manifest is retrieved so this logic occurs in F2.Constants.AppHandlers.APP_RENDER
* appConfig.root = jQuery('<section></section>').get(0);
* }
* );
*/
APP_CREATE_ROOT: 'appCreateRoot',
/**
* Equivalent to `appRenderBefore`. Identifies the before app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_BEFORE,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_BEFORE: 'appRenderBefore',
/**
* Equivalent to `appRender`. Identifies the app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, [appHtml](../../app-development.html#app-design) )
* @property APP_RENDER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER,
* function(appConfig, appHtml)
* {
* var $root = null;
*
* // if no app root is defined use the app's outer most node
* if(!F2.isNativeDOMNode(appConfig.root))
* {
* appConfig.root = jQuery(appHtml).get(0);
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
* }
* else
* {
* // get a handle on the root in jQuery
* $root = jQuery(appConfig.root);
*
* // append the app html to the root
* $root.append(appHtml);
* }
*
* // append the root to the body by default.
* jQuery('body').append($root);
* }
* );
*/
APP_RENDER: 'appRender',
/**
* Equivalent to `appRenderAfter`. Identifies the after app render method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}} )
* @property APP_RENDER_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_RENDER_AFTER,
* function(appConfig)
* {
* F2.log(appConfig);
* }
* );
*/
APP_RENDER_AFTER: 'appRenderAfter',
/**
* Equivalent to `appDestroyBefore`. Identifies the before app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_BEFORE
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_BEFORE: 'appDestroyBefore',
/**
* Equivalent to `appDestroy`. Identifies the app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY,
* function(appInstance)
* {
* // call the apps destroy method, if it has one
* if(appInstance && appInstance.app && appInstance.app.destroy && typeof(appInstance.app.destroy) == 'function')
* {
* appInstance.app.destroy();
* }
* else if(appInstance && appInstance.app && appInstance.app.destroy)
* {
* F2.log(appInstance.config.appId + ' has a destroy property, but destroy is not of type function and as such will not be executed.');
* }
*
* // fade out and remove the root
* jQuery(appInstance.config.root).fadeOut(500, function() {
* jQuery(this).remove();
* });
* }
* );
*/
APP_DESTROY: 'appDestroy',
/**
* Equivalent to `appDestroyAfter`. Identifies the after app destroy method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( appInstance )
* @property APP_DESTROY_AFTER
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_DESTROY_AFTER,
* function(appInstance)
* {
* F2.log(appInstance);
* }
* );
*/
APP_DESTROY_AFTER: 'appDestroyAfter',
/**
* Equivalent to `appScriptLoadFailed`. Identifies the app script load failed method for use in AppHandlers.on/off.
* When bound using {{#crossLink "F2.AppHandlers/on"}}F2.AppHandlers.on(){{/crossLink}} the listener function passed will receive the
* following argument(s): ( {{#crossLink "F2.AppConfig"}}appConfig{{/crossLink}}, scriptInfo )
* @property APP_SCRIPT_LOAD_FAILED
* @type string
* @static
* @final
* @example
* var _token = F2.AppHandlers.getToken();
* F2.AppHandlers.on(
* _token,
* F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
* function(appConfig, scriptInfo)
* {
* F2.log(appConfig.appId);
* }
* );
*/
APP_SCRIPT_LOAD_FAILED: 'appScriptLoadFailed'
};
})()
});
/**
* Class stubs for documentation purposes
* @main F2
*/
F2.extend('', {
/**
* The App Class is an optional class that can be namespaced onto the
* {{#crossLink "F2\Apps"}}{{/crossLink}} namespace. The
* [F2 Docs](../../app-development.html#app-class)
* has more information on the usage of the App Class.
* @class F2.App
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object for the app
* @param {F2.AppManifest.AppContent} appContent The F2.AppManifest.AppContent
* object
* @param {Element} root The root DOM Element for the app
*/
App: function(appConfig, appContent, root) {
return {
/**
* An optional init function that will automatically be called when
* F2.{{#crossLink "F2\registerApps"}}{{/crossLink}} is called.
* @method init
* @optional
*/
init:function() {}
};
},
/**
* The AppConfig object represents an app's meta data
* @class F2.AppConfig
*/
AppConfig: {
/**
* The unique ID of the app. More information can be found
* [here](../../app-development.html#f2-appid)
* @property appId
* @type string
* @required
*/
appId: '',
/**
* An object that represents the context of an app
* @property context
* @type object
*/
context: {},
/**
* True if the app should be requested in a single request with other apps.
* @property enableBatchRequests
* @type bool
* @default false
*/
enableBatchRequests: false,
/**
* The height of the app. The initial height will be pulled from
* the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object, but later
* modified by calling
* F2.UI.{{#crossLink "F2.UI/updateHeight"}}{{/crossLink}}. This is used
* for secure apps to be able to set the initial height of the iframe.
* @property height
* @type int
*/
height: 0,
/**
* The unique runtime ID of the app.
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property instanceId
* @type string
*/
instanceId: '',
/**
* True if the app will be loaded in an iframe. This property
* will be true if the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object
* sets isSecure = true. It will also be true if the
* [container](../../container-development.html) has made the decision to
* run apps in iframes.
* @property isSecure
* @type bool
* @default false
*/
isSecure: false,
/**
* The url to retrieve the {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* object.
* @property manifestUrl
* @type string
* @required
*/
manifestUrl: '',
/**
* The recommended maximum width in pixels that this app should be run.
* **It is up to the [container](../../container-development.html) to
* implement the logic to prevent an app from being run when the maxWidth
* requirements are not met.**
* @property maxWidth
* @type int
*/
maxWidth: 0,
/**
* The recommended minimum grid size that this app should be run. This
* value corresponds to the 12-grid system that is used by the
* [container](../../container-development.html). This property should be
* set by apps that require a certain number of columns in their layout.
* @property minGridSize
* @type int
* @default 4
*/
minGridSize: 4,
/**
* The recommended minimum width in pixels that this app should be run. **It
* is up to the [container](../../container-development.html) to implement
* the logic to prevent an app from being run when the minWidth requirements
* are not met.
* @property minWidth
* @type int
* @default 300
*/
minWidth: 300,
/**
* The name of the app
* @property name
* @type string
* @required
*/
name: '',
/**
* The root DOM element that contains the app
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property root
* @type Element
*/
root: undefined,
/**
* The instance of F2.UI providing easy access to F2.UI methods
*
* **This property is populated during the
* F2.{{#crossLink "F2/registerApps"}}{{/crossLink}} process**
* @property ui
* @type F2.UI
*/
ui: undefined,
/**
* The views that this app supports. Available views
* are defined in {{#crossLink "F2.Constants.Views"}}{{/crossLink}}. The
* presence of a view can be checked via
* F2.{{#crossLink "F2/inArray"}}{{/crossLink}}:
*
* F2.inArray(F2.Constants.Views.SETTINGS, app.views)
*
* @property views
* @type Array
*/
views: []
},
/**
* The assets needed to render an app on the page
* @class F2.AppManifest
*/
AppManifest: {
/**
* The array of {{#crossLink "F2.AppManifest.AppContent"}}{{/crossLink}}
* objects
* @property apps
* @type Array
* @required
*/
apps: [],
/**
* Any inline javascript tha should initially be run
* @property inlineScripts
* @type Array
* @optional
*/
inlineScripts: [],
/**
* Urls to javascript files required by the app
* @property scripts
* @type Array
* @optional
*/
scripts: [],
/**
* Urls to CSS files required by the app
* @property styles
* @type Array
* @optional
*/
styles: []
},
/**
* The AppContent object
* @class F2.AppManifest.AppContent
**/
AppContent: {
/**
* Arbitrary data to be passed along with the app
* @property data
* @type object
* @optional
*/
data: {},
/**
* The string of HTML representing the app
* @property html
* @type string
* @required
*/
html: '',
/**
* A status message
* @property status
* @type string
* @optional
*/
status: ''
},
/**
* An object containing configuration information for the
* [container](../../container-development.html)
* @class F2.ContainerConfig
*/
ContainerConfig: {
/**
* Allows the [container](../../container-development.html) to override how
* an app's html is inserted into the page. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html
* @method afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
* @return {Element} The DOM Element surrounding the app
*/
afterAppRender: function(appConfig, html) {},
/**
* Allows the [container](../../container-development.html) to wrap an app
* in extra html. The function should accept an
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} object and also a string of
* html. The extra html can provide links to edit app settings and remove an
* app from the container. See
* {{#crossLink "F2.Constants.Css"}}{{/crossLink}} for CSS classes that
* should be applied to elements.
* @method appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html representing the app
*/
appRender: function(appConfig, html) {},
/**
* Allows the container to render html for an app before the AppManifest for
* an app has loaded. This can be useful if the design calls for loading
* icons to appear for each app before each app is loaded and rendered to
* the page.
* @method beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
beforeAppRender: function(appConfig) {},
/**
* True to enable debug mode in F2.js. Adds additional logging, resource cache busting, etc.
* @property debugMode
* @type bool
* @default false
*/
debugMode: false,
/**
* Milliseconds before F2 fires callback on script resource load errors. Due to issue with the way Internet Explorer attaches load events to script elements, the error event doesn't fire.
* @property scriptErrorTimeout
* @type milliseconds
* @default 7000 (7 seconds)
*/
scriptErrorTimeout: 7000,
/**
* Tells the container that it is currently running within
* a secure app page
* @property isSecureAppPage
* @type bool
*/
isSecureAppPage: false,
/**
* Allows the container to specify which page is used when
* loading a secure app. The page must reside on a different domain than the
* container
* @property secureAppPagePath
* @type string
* @for F2.ContainerConfig
*/
secureAppPagePath: '',
/**
* Specifies what views a container will provide buttons
* or links to. Generally, the views will be switched via buttons or links
* in the app's header.
* @property supportedViews
* @type Array
* @required
*/
supportedViews: [],
/**
* An object containing configuration defaults for F2.UI
* @class F2.ContainerConfig.UI
*/
UI: {
/**
* An object containing configuration defaults for the
* F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} and
* F2.UI.{{#crossLink "F2.UI/hideMask"}}{{/crossLink}} methods.
* @class F2.ContainerConfig.UI.Mask
*/
Mask: {
/**
* The backround color of the overlay
* @property backgroundColor
* @type string
* @default #FFF
*/
backgroundColor: '#FFF',
/**
* The path to the loading icon
* @property loadingIcon
* @type string
*/
loadingIcon: '',
/**
* The opacity of the background overlay
* @property opacity
* @type int
* @default 0.6
*/
opacity: 0.6,
/**
* Do not use inline styles for mask functinality. Instead classes will
* be applied to the elements and it is up to the container provider to
* implement the class definitions.
* @property useClasses
* @type bool
* @default false
*/
useClasses: false,
/**
* The z-index to use for the overlay
* @property zIndex
* @type int
* @default 2
*/
zIndex: 2
}
},
/**
* Allows the container to fully override how the AppManifest request is
* made inside of F2.
*
* @method xhr
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {function} success The function to be called if the request
* succeeds
* @param {function} error The function to be called if the request fails
* @param {function} complete The function to be called when the request
* finishes (after success and error callbacks have been executed)
* @return {XMLHttpRequest} The XMLHttpRequest object (or an object that has
* an `abort` function (such as the jqXHR object in jQuery) to abort the
* request)
*
* @example
* F2.init({
* xhr: function(url, appConfigs, success, error, complete) {
* $.ajax({
* url: url,
* type: 'POST',
* data: {
* params: F2.stringify(appConfigs, F2.appConfigReplacer)
* },
* jsonp: false, // do not put 'callback=' in the query string
* jsonpCallback: F2.Constants.JSONP_CALLBACK + appConfigs[0].appId, // Unique function name
* dataType: 'json',
* success: function(appManifest) {
* // custom success logic
* success(appManifest); // fire success callback
* },
* error: function() {
* // custom error logic
* error(); // fire error callback
* },
* complete: function() {
* // custom complete logic
* complete(); // fire complete callback
* }
* });
* }
* });
*
* @for F2.ContainerConfig
*/
//xhr: function(url, appConfigs, success, error, complete) {},
/**
* Allows the container to override individual parts of the AppManifest
* request. See properties and methods with the `xhr.` prefix.
* @property xhr
* @type Object
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
xhr: {
/**
* Allows the container to override the request data type (JSON or JSONP)
* that is used for the request
* @method xhr.dataType
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request data type that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
dataType: function(url, appConfigs) {},
/**
* Allows the container to override the request method that is used (just
* like the `type` parameter to `jQuery.ajax()`.
* @method xhr.type
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The request method that should be used
*
* @example
* F2.init({
* xhr: {
* dataType: function(url) {
* return F2.isLocalRequest(url) ? 'json' : 'jsonp';
* },
* type: function(url) {
* return F2.isLocalRequest(url) ? 'POST' : 'GET';
* }
* }
* });
*/
type: function(url, appConfigs) {},
/**
* Allows the container to override the url that is used to request an
* app's F2.{{#crossLink "F2.AppManifest"}}{{/crossLink}}
* @method xhr.url
* @param {string} url The manifest url
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @return {string} The url that should be used for the request
*
* @example
* F2.init({
* xhr: {
* url: function(url, appConfigs) {
* return 'http://example.com/proxy.php?url=' + encocdeURIComponent(url);
* }
* }
* });
*/
url: function(url, appConfigs) {}
},
/**
* Allows the container to override the script loader which requests
* dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}.
* @property loadScripts
* @type function
*
* @example
* F2.init({
* loadScripts: function(scripts,inlines,callback){
* //load scripts using $.load() for each script or require(scripts)
* callback();
* }
* });
*/
loadScripts: function(scripts,inlines,callback){},
/**
* Allows the container to override the stylesheet loader which requests
* dependencies defined in the {{#crossLink "F2.AppManifest"}}{{/crossLink}}.
* @property loadStyles
* @type function
*
* @example
* F2.init({
* loadStyles: function(styles,callback){
* //load styles using $.load() for each stylesheet or another method
* callback();
* }
* });
*/
loadStyles: function(styles,callback){}
}
});
/**
* Constants used throughout the Open Financial Framework
* @class F2.Constants
* @static
*/
F2.extend('Constants', {
/**
* CSS class constants
* @class F2.Constants.Css
*/
Css: (function() {
/** @private */
var _PREFIX = 'f2-';
return {
/**
* The APP class should be applied to the DOM Element that surrounds the
* entire app, including any extra html that surrounds the APP\_CONTAINER
* that is inserted by the container. See the
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}} object.
* @property APP
* @type string
* @static
* @final
*/
APP: _PREFIX + 'app',
/**
* The APP\_CONTAINER class should be applied to the outermost DOM Element
* of the app.
* @property APP_CONTAINER
* @type string
* @static
* @final
*/
APP_CONTAINER: _PREFIX + 'app-container',
/**
* The APP\_TITLE class should be applied to the DOM Element that contains
* the title for an app. If this class is not present, then
* F2.UI.{{#crossLink "F2.UI/setTitle"}}{{/crossLink}} will not function.
* @property APP_TITLE
* @type string
* @static
* @final
*/
APP_TITLE: _PREFIX + 'app-title',
/**
* The APP\_VIEW class should be applied to the DOM Element that contains
* a view for an app. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it is.
* @property APP_VIEW
* @type string
* @static
* @final
*/
APP_VIEW: _PREFIX + 'app-view',
/**
* APP\_VIEW\_TRIGGER class should be applied to the DOM Elements that
* trigger an
* {{#crossLink "F2.Constants.Events"}}{{/crossLink}}.APP\_VIEW\_CHANGE
* event. The DOM Element should also have a
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}}.DATA_ATTRIBUTE
* attribute that specifies which
* {{#crossLink "F2.Constants.Views"}}{{/crossLink}} it will trigger.
* @property APP_VIEW_TRIGGER
* @type string
* @static
* @final
*/
APP_VIEW_TRIGGER: _PREFIX + 'app-view-trigger',
/**
* The MASK class is applied to the overlay element that is created
* when the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method is
* fired.
* @property MASK
* @type string
* @static
* @final
*/
MASK: _PREFIX + 'mask',
/**
* The MASK_CONTAINER class is applied to the Element that is passed into
* the F2.UI.{{#crossLink "F2.UI/showMask"}}{{/crossLink}} method.
* @property MASK_CONTAINER
* @type string
* @static
* @final
*/
MASK_CONTAINER: _PREFIX + 'mask-container'
};
})(),
/**
* Events constants
* @class F2.Constants.Events
*/
Events: (function() {
/** @private */
var _APP_EVENT_PREFIX = 'App.';
/** @private */
var _CONTAINER_EVENT_PREFIX = 'Container.';
return {
/**
* The APP\_SYMBOL\_CHANGE event is fired when the symbol is changed in an
* app. It is up to the app developer to fire this event.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property APP_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
APP_SYMBOL_CHANGE: _APP_EVENT_PREFIX + 'symbolChange',
/**
* The APP\_WIDTH\_CHANGE event will be fired by the container when the
* width of an app is changed. The app's instanceId should be concatenated
* to this constant.
* Returns an object with the gridSize and width in pixels:
*
* { gridSize:8, width:620 }
*
* @property APP_WIDTH_CHANGE
* @type string
* @static
* @final
*/
APP_WIDTH_CHANGE: _APP_EVENT_PREFIX + 'widthChange.',
/**
* The CONTAINER\_SYMBOL\_CHANGE event is fired when the symbol is changed
* at the container level. This event should only be fired by the
* container or container provider.
* Returns an object with the symbol and company name:
*
* { symbol: 'MSFT', name: 'Microsoft Corp (NASDAQ)' }
*
* @property CONTAINER_SYMBOL_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_SYMBOL_CHANGE: _CONTAINER_EVENT_PREFIX + 'symbolChange',
/**
* The CONTAINER\_WIDTH\_CHANGE event will be fired by the container when
* the width of the container has changed.
* @property CONTAINER_WIDTH_CHANGE
* @type string
* @static
* @final
*/
CONTAINER_WIDTH_CHANGE: _CONTAINER_EVENT_PREFIX + 'widthChange'
};
})(),
JSONP_CALLBACK: 'F2_jsonpCallback_',
/**
* Constants for use with cross-domain sockets
* @class F2.Constants.Sockets
* @protected
*/
Sockets: {
/**
* The EVENT message is sent whenever
* F2.Events.{{#crossLink "F2.Events/emit"}}{{/crossLink}} is fired
* @property EVENT
* @type string
* @static
* @final
*/
EVENT: '__event__',
/**
* The LOAD message is sent when an iframe socket initially loads.
* Returns a JSON string that represents:
*
* [ App, AppManifest]
*
* @property LOAD
* @type string
* @static
* @final
*/
LOAD: '__socketLoad__',
/**
* The RPC message is sent when a method is passed up from within a secure
* app page.
* @property RPC
* @type string
* @static
* @final
*/
RPC: '__rpc__',
/**
* The RPC\_CALLBACK message is sent when a call back from an RPC method is
* fired.
* @property RPC_CALLBACK
* @type string
* @static
* @final
*/
RPC_CALLBACK: '__rpcCallback__',
/**
* The UI\_RPC message is sent when a UI method called.
* @property UI_RPC
* @type string
* @static
* @final
*/
UI_RPC: '__uiRpc__'
},
/**
* The available view types to apps. The view should be specified by applying
* the {{#crossLink "F2.Constants.Css"}}{{/crossLink}}.APP\_VIEW class to the
* containing DOM Element. A DATA\_ATTRIBUTE attribute should be added to the
* Element as well which defines what view type is represented.
* The `hide` class can be applied to views that should be hidden by default.
* @class F2.Constants.Views
*/
Views: {
/**
* The DATA_ATTRIBUTE should be placed on the DOM Element that contains the
* view.
* @property DATA_ATTRIBUTE
* @type string
* @static
* @final
*/
DATA_ATTRIBUTE: 'data-f2-view',
/**
* The ABOUT view gives details about the app.
* @property ABOUT
* @type string
* @static
* @final
*/
ABOUT: 'about',
/**
* The HELP view provides users with help information for using an app.
* @property HELP
* @type string
* @static
* @final
*/
HELP: 'help',
/**
* The HOME view is the main view for an app. This view should always
* be provided by an app.
* @property HOME
* @type string
* @static
* @final
*/
HOME: 'home',
/**
* The REMOVE view is a special view that handles the removal of an app
* from the container.
* @property REMOVE
* @type string
* @static
* @final
*/
REMOVE: 'remove',
/**
* The SETTINGS view provides users the ability to modify advanced settings
* for an app.
* @property SETTINGS
* @type string
* @static
* @final
*/
SETTINGS: 'settings'
}
});
/**
* Handles [Context](../../app-development.html#context) passing from
* containers to apps and apps to apps.
* @class F2.Events
*/
F2.extend('Events', (function() {
// init EventEmitter
var _events = new EventEmitter2({
wildcard:true
});
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
return {
/**
* Same as F2.Events.emit except that it will not send the event
* to all sockets.
* @method _socketEmit
* @private
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
_socketEmit: function() {
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Execute each of the listeners that may be listening for the specified
* event name in order with the list of arguments.
* @method emit
* @param {string} event The event name
* @param {object} [arg]* The arguments to be passed
*/
emit: function() {
F2.Rpc.broadcast(F2.Constants.Sockets.EVENT, [].slice.call(arguments));
return EventEmitter2.prototype.emit.apply(_events, [].slice.call(arguments));
},
/**
* Adds a listener that will execute n times for the event before being
* removed. The listener is invoked only the first time the event is
* fired, after which it is removed.
* @method many
* @param {string} event The event name
* @param {int} timesToListen The number of times to execute the event
* before being removed
* @param {function} listener The function to be fired when the event is
* emitted
*/
many: function(event, timesToListen, listener) {
return _events.many(event, timesToListen, listener);
},
/**
* Remove a listener for the specified event.
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
*/
off: function(event, listener) {
return _events.off(event, listener);
},
/**
* Adds a listener for the specified event
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
on: function(event, listener){
return _events.on(event, listener);
},
/**
* Adds a one time listener for the event. The listener is invoked only
* the first time the event is fired, after which it is removed.
* @method once
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
*/
once: function(event, listener) {
return _events.once(event, listener);
}
};
})());
/**
* Handles socket communication between the container and secure apps
* @class F2.Rpc
*/
F2.extend('Rpc', (function(){
var _callbacks = {};
var _secureAppPagePath = '';
var _apps = {};
var _rEvents = new RegExp('^' + F2.Constants.Sockets.EVENT);
var _rRpc = new RegExp('^' + F2.Constants.Sockets.RPC);
var _rRpcCallback = new RegExp('^' + F2.Constants.Sockets.RPC_CALLBACK);
var _rSocketLoad = new RegExp('^' + F2.Constants.Sockets.LOAD);
var _rUiCall = new RegExp('^' + F2.Constants.Sockets.UI_RPC);
/**
* Creates a socket connection from the app to the container using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createAppToContainerSocket
* @private
*/
var _createAppToContainerSocket = function() {
var appConfig; // socket closure
var isLoaded = false;
// its possible for messages to be received before the socket load event has
// happened. We'll save off these messages and replay them once the socket
// is ready
var messagePlayback = [];
var socket = new easyXDM.Socket({
onMessage: function(message, origin){
// handle Socket Load
if (!isLoaded && _rSocketLoad.test(message)) {
message = message.replace(_rSocketLoad, '');
var appParts = F2.parse(message);
// make sure we have the AppConfig and AppManifest
if (appParts.length == 2) {
appConfig = appParts[0];
// save socket
_apps[appConfig.instanceId] = {
config:appConfig,
socket:socket
};
// register app
F2.registerApps([appConfig], [appParts[1]]);
// socket message playback
jQuery.each(messagePlayback, function(i, e) {
_onMessage(appConfig, message, origin);
});
isLoaded = true;
}
} else if (isLoaded) {
// pass everyting else to _onMessage
_onMessage(appConfig, message, origin);
} else {
//F2.log('socket not ready, queuing message', message);
messagePlayback.push(message);
}
}
});
};
/**
* Creates a socket connection from the container to the app using
* <a href="http://easyxdm.net" target="_blank">easyXDM</a>.
* @method _createContainerToAppSocket
* @private
* @param {appConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The F2.AppManifest object
*/
var _createContainerToAppSocket = function(appConfig, appManifest) {
var container = jQuery(appConfig.root);
if (!container.is('.' + F2.Constants.Css.APP_CONTAINER)) {
container.find('.' + F2.Constants.Css.APP_CONTAINER);
}
if (!container.length) {
F2.log('Unable to locate app in order to establish secure connection.');
return;
}
var iframeProps = {
scrolling:'no',
style:{
width:'100%'
}
};
if (appConfig.height) {
iframeProps.style.height = appConfig.height + 'px';
}
var socket = new easyXDM.Socket({
remote: _secureAppPagePath,
container: container.get(0),
props:iframeProps,
onMessage: function(message, origin) {
// pass everything to _onMessage
_onMessage(appConfig, message, origin);
},
onReady: function() {
socket.postMessage(F2.Constants.Sockets.LOAD + F2.stringify([appConfig, appManifest], F2.appConfigReplacer));
}
});
return socket;
};
/**
* @method _createRpcCallback
* @private
* @param {string} instanceId The app's Instance ID
* @param {function} callbackId The callback ID
* @return {function} A function to make the RPC call
*/
var _createRpcCallback = function(instanceId, callbackId) {
return function() {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC_CALLBACK,
callbackId,
[].slice.call(arguments).slice(2)
);
};
};
/**
* Handles messages that come across the sockets
* @method _onMessage
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} message The socket message
* @param {string} origin The originator
*/
var _onMessage = function(appConfig, message, origin) {
var obj, func;
function parseFunction(parent, functionName) {
var path = String(functionName).split('.');
for (var i = 0; i < path.length; i++) {
if (parent[path[i]] === undefined) {
parent = undefined;
break;
}
parent = parent[path[i]];
}
return parent;
}
function parseMessage(regEx, message, instanceId) {
var o = F2.parse(message.replace(regEx, ''));
// if obj.callbacks
// for each callback
// for each params
// if callback matches param
// replace param with _createRpcCallback(app.instanceId, callback)
if (o.params && o.params.length && o.callbacks && o.callbacks.length) {
jQuery.each(o.callbacks, function(i, c) {
jQuery.each(o.params, function(i, p) {
if (c == p) {
o.params[i] = _createRpcCallback(instanceId, c);
}
});
});
}
return o;
}
// handle UI Call
if (_rUiCall.test(message)) {
obj = parseMessage(_rUiCall, message, appConfig.instanceId);
func = parseFunction(appConfig.ui, obj.functionName);
// if we found the function, call it
if (func !== undefined) {
func.apply(appConfig.ui, obj.params);
} else {
F2.log('Unable to locate UI RPC function: ' + obj.functionName);
}
// handle RPC
} else if (_rRpc.test(message)) {
obj = parseMessage(_rRpc, message, appConfig.instanceId);
func = parseFunction(window, obj.functionName);
if (func !== undefined) {
func.apply(func, obj.params);
} else {
F2.log('Unable to locate RPC function: ' + obj.functionName);
}
// handle RPC Callback
} else if (_rRpcCallback.test(message)) {
obj = parseMessage(_rRpcCallback, message, appConfig.instanceId);
if (_callbacks[obj.functionName] !== undefined) {
_callbacks[obj.functionName].apply(_callbacks[obj.functionName], obj.params);
delete _callbacks[obj.functionName];
}
// handle Events
} else if (_rEvents.test(message)) {
obj = parseMessage(_rEvents, message, appConfig.instanceId);
F2.Events._socketEmit.apply(F2.Events, obj);
}
};
/**
* Registers a callback function
* @method _registerCallback
* @private
* @param {function} callback The callback function
* @return {string} The callback ID
*/
var _registerCallback = function(callback) {
var callbackId = F2.guid();
_callbacks[callbackId] = callback;
return callbackId;
};
return {
/**
* Broadcast an RPC function to all sockets
* @method broadcast
* @param {string} messageType The message type
* @param {Array} params The parameters to broadcast
*/
broadcast: function(messageType, params) {
// check valid messageType
var message = messageType + F2.stringify(params);
jQuery.each(_apps, function(i, a) {
a.socket.postMessage(message);
});
},
/**
* Calls a remote function
* @method call
* @param {string} instanceId The app's Instance ID
* @param {string} messageType The message type
* @param {string} functionName The name of the remote function
* @param {Array} params An array of parameters to pass to the remote
* function. Any functions found within the params will be treated as a
* callback function.
*/
call: function(instanceId, messageType, functionName, params) {
// loop through params and find functions and convert them to callbacks
var callbacks = [];
jQuery.each(params, function(i, e) {
if (typeof e === 'function') {
var cid = _registerCallback(e);
params[i] = cid;
callbacks.push(cid);
}
});
// check valid messageType
_apps[instanceId].socket.postMessage(
messageType + F2.stringify({
functionName:functionName,
params:params,
callbacks:callbacks
})
);
},
/**
* Init function which tells F2.Rpc whether it is running at the container-
* level or the app-level. This method is generally called by
* F2.{{#crossLink "F2/init"}}{{/crossLink}}
* @method init
* @param {string} [secureAppPagePath] The
* {{#crossLink "F2.ContainerConfig"}}{{/crossLink}}.secureAppPagePath
* property
*/
init: function(secureAppPagePath) {
_secureAppPagePath = secureAppPagePath;
if (!_secureAppPagePath) {
_createAppToContainerSocket();
}
},
/**
* Determines whether the Instance ID is considered to be 'remote'. This is
* determined by checking if 1) the app has an open socket and 2) whether
* F2.Rpc is running inside of an iframe
* @method isRemote
* @param {string} instanceId The Instance ID
* @return {bool} True if there is an open socket
*/
isRemote: function(instanceId) {
return (
// we have an app
_apps[instanceId] !== undefined &&
// the app is secure
_apps[instanceId].config.isSecure &&
// we can't access the iframe
jQuery(_apps[instanceId].config.root).find('iframe').length === 0
);
},
/**
* Creates a container-to-app or app-to-container socket for communication
* @method register
* @param {F2.AppConfig} [appConfig] The F2.AppConfig object
* @param {F2.AppManifest} [appManifest] The F2.AppManifest object
*/
register: function(appConfig, appManifest) {
if (!!appConfig && !!appManifest) {
_apps[appConfig.instanceId] = {
config:appConfig,
socket:_createContainerToAppSocket(appConfig, appManifest)
};
} else {
F2.log('Unable to register socket connection. Please check container configuration.');
}
}
};
})());
F2.extend('UI', (function(){
var _containerConfig;
/**
* UI helper methods
* @class F2.UI
* @constructor
* @param {F2.AppConfig} appConfig The F2.AppConfig object
*/
var UI_Class = function(appConfig) {
var _appConfig = appConfig;
var $root = jQuery(appConfig.root);
var _updateHeight = function(height) {
height = height || jQuery(_appConfig.root).outerHeight();
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'updateHeight',
[
height
]
);
} else {
_appConfig.height = height;
$root.find('iframe').height(_appConfig.height);
}
};
return {
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
*/
hideMask: function(selector) {
F2.UI.hideMask(_appConfig.instanceId, selector);
},
/**
* Helper methods for creating and using Modals
* @class F2.UI.Modals
* @for F2.UI
*/
Modals: (function(){
var _renderAlert = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Alert!</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button class="btn btn-primary btn-ok">OK</button>',
'</div>',
'</div>'
].join('');
};
var _renderConfirm = function(message) {
return [
'<div class="modal">',
'<header class="modal-header">',
'<h3>Confirm</h3>',
'</header>',
'<div class="modal-body">',
'<p>',
message,
'</p>',
'</div>',
'<div class="modal-footer">',
'<button type="button" class="btn btn-primary btn-ok">OK</button>',
'<button type="button" class="btn btn-cancel">Cancel</button">',
'</div>',
'</div>'
].join('');
};
return {
/**
* Display an alert message on the page
* @method alert
* @param {string} message The message to be displayed
* @param {function} [callback] The callback to be fired when the user
* closes the dialog
* @for F2.UI.Modals
*/
alert: function(message, callback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.alert()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.alert',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderAlert(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-primary').on('click', function() {
jQuery(modal).modal('hide').remove();
(callback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
},
/**
* Display a confirm message on the page
* @method confirm
* @param {string} message The message to be displayed
* @param {function} okCallback The function that will be called when the OK
* button is pressed
* @param {function} cancelCallback The function that will be called when
* the Cancel button is pressed
* @for F2.UI.Modals
*/
confirm: function(message, okCallback, cancelCallback) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.Modals.confirm()');
return;
}
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Modals.confirm',
[].slice.call(arguments)
);
} else {
// display the alert
jQuery(_renderConfirm(message))
.on('show', function() {
var modal = this;
jQuery(modal).find('.btn-ok').on('click', function() {
jQuery(modal).modal('hide').remove();
(okCallback || jQuery.noop)();
});
jQuery(modal).find('.btn-cancel').on('click', function() {
jQuery(modal).modal('hide').remove();
(cancelCallback || jQuery.noop)();
});
})
.modal({backdrop:true});
}
}
};
})(),
/**
* Sets the title of the app as shown in the browser. Depending on the
* container HTML, this method may do nothing if the container has not been
* configured properly or else the container provider does not allow Title's
* to be set.
* @method setTitle
* @params {string} title The title of the app
* @for F2.UI
*/
setTitle: function(title) {
if (F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'setTitle',
[
title
]
);
} else {
jQuery(_appConfig.root).find('.' + F2.Constants.Css.APP_TITLE).text(title);
}
},
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
showMask: function(selector, showLoader) {
F2.UI.showMask(_appConfig.instanceId, selector, showLoader);
},
/**
* For secure apps, this method updates the size of the iframe that
* contains the app. **Note: It is recommended that app developers call
* this method anytime Elements are added or removed from the DOM**
* @method updateHeight
* @params {int} height The height of the app
*/
updateHeight: _updateHeight,
/**
* Helper methods for creating and using Views
* @class F2.UI.Views
* @for F2.UI
*/
Views: (function(){
var _events = new EventEmitter2();
var _rValidEvents = /change/i;
// unlimited listeners, set to > 0 for debugging
_events.setMaxListeners(0);
var _isValid = function(eventName) {
if (_rValidEvents.test(eventName)) {
return true;
} else {
F2.log('"' + eventName + '" is not a valid F2.UI.Views event name');
return false;
}
};
return {
/**
* Change the current view for the app or add an event listener
* @method change
* @param {string|function} [input] If a string is passed in, the view
* will be changed for the app. If a function is passed in, a change
* event listener will be added.
* @for F2.UI.Views
*/
change: function(input) {
if (typeof input === 'function') {
this.on('change', input);
} else if (typeof input === 'string') {
if (_appConfig.isSecure && !F2.Rpc.isRemote(_appConfig.instanceId)) {
F2.Rpc.call(
_appConfig.instanceId,
F2.Constants.Sockets.UI_RPC,
'Views.change',
[].slice.call(arguments)
);
} else if (F2.inArray(input, _appConfig.views)) {
jQuery('.' + F2.Constants.Css.APP_VIEW, $root)
.addClass('hide')
.filter('[data-f2-view="' + input + '"]', $root)
.removeClass('hide');
_updateHeight();
_events.emit('change', input);
}
}
},
/**
* Removes a view event listener
* @method off
* @param {string} event The event name
* @param {function} listener The function that will be removed
* @for F2.UI.Views
*/
off: function(event, listener) {
if (_isValid(event)) {
_events.off(event, listener);
}
},
/**
* Adds a view event listener
* @method on
* @param {string} event The event name
* @param {function} listener The function to be fired when the event is
* emitted
* @for F2.UI.Views
*/
on: function(event, listener) {
if (_isValid(event)) {
_events.on(event, listener);
}
}
};
})()
};
};
/**
* Removes a overlay from an Element on the page
* @method hideMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* that currently contains the loader
* @for F2.UI
*/
UI_Class.hideMask = function(instanceId, selector) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.hideMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && !jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.hideMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector
]
);
} else {
var container = jQuery(selector);
container.find('> .' + F2.Constants.Css.MASK).remove();
container.removeClass(F2.Constants.Css.MASK_CONTAINER);
// if the element contains this data property, we need to reset static
// position
if (container.data(F2.Constants.Css.MASK_CONTAINER)) {
container.css({'position':'static'});
}
}
};
/**
*
* @method init
* @static
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
UI_Class.init = function(containerConfig) {
_containerConfig = containerConfig;
// set defaults
_containerConfig.UI = jQuery.extend(true, {}, F2.ContainerConfig.UI, _containerConfig.UI || {});
};
/**
* Display an ovarlay over an Element on the page
* @method showMask
* @static
* @param {string} instanceId The Instance ID of the app
* @param {string|Element} selector The Element or selector to an Element
* over which to display the loader
* @param {bool} showLoading Display a loading icon
*/
UI_Class.showMask = function(instanceId, selector, showLoading) {
if (!F2.isInit()) {
F2.log('F2.init() must be called before F2.UI.showMask()');
return;
}
if (F2.Rpc.isRemote(instanceId) && jQuery(selector).is('.' + F2.Constants.Css.APP)) {
F2.Rpc.call(
instanceId,
F2.Constants.Sockets.RPC,
'F2.UI.showMask',
[
instanceId,
// must only pass the selector argument. if we pass an Element there
// will be F2.stringify() errors
jQuery(selector).selector,
showLoading
]
);
} else {
if (showLoading && !_containerConfig.UI.Mask.loadingIcon) {
F2.log('Unable to display loading icon. Please set F2.ContainerConfig.UI.Mask.loadingIcon when calling F2.init();');
}
var container = jQuery(selector).addClass(F2.Constants.Css.MASK_CONTAINER);
var mask = jQuery('<div>')
.height('100%' /*container.outerHeight()*/)
.width('100%' /*container.outerWidth()*/)
.addClass(F2.Constants.Css.MASK);
// set inline styles if useClasses is false
if (!_containerConfig.UI.Mask.useClasses) {
mask.css({
'background-color':_containerConfig.UI.Mask.backgroundColor,
'background-image': !!_containerConfig.UI.Mask.loadingIcon ? ('url(' + _containerConfig.UI.Mask.loadingIcon + ')') : '',
'background-position':'50% 50%',
'background-repeat':'no-repeat',
'display':'block',
'left':0,
'min-height':30,
'padding':0,
'position':'absolute',
'top':0,
'z-index':_containerConfig.UI.Mask.zIndex,
'filter':'alpha(opacity=' + (_containerConfig.UI.Mask.opacity * 100) + ')',
'opacity':_containerConfig.UI.Mask.opacity
});
}
// only set the position if the container is currently static
if (container.css('position') === 'static') {
container.css({'position':'relative'});
// setting this data property tells hideMask to set the position
// back to static
container.data(F2.Constants.Css.MASK_CONTAINER, true);
}
// add the mask to the container
container.append(mask);
}
};
return UI_Class;
})());
/**
* Root namespace of the F2 SDK
* @module f2
* @class F2
*/
F2.extend('', (function() {
var _apps = {};
var _config = false;
var _bUsesAppHandlers = false;
var _sAppHandlerToken = F2.AppHandlers.__f2GetToken();
/**
* Appends the app's html to the DOM
* @method _afterAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
* @return {Element} The DOM Element that contains the app
*/
var _afterAppRender = function(appConfig, html) {
var handler = _config.afterAppRender || function(appConfig, html) {
return jQuery(html).appendTo('body');
};
var appContainer = handler(appConfig, html);
if ( !! _config.afterAppRender && !appContainer) {
F2.log('F2.ContainerConfig.afterAppRender() must return the DOM Element that contains the app');
return;
}
else {
// apply APP class and Instance ID
jQuery(appContainer).addClass(F2.Constants.Css.APP);
return appContainer.get(0);
}
};
/**
* Renders the html for an app.
* @method _appRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {string} html The string of html
*/
var _appRender = function(appConfig, html) {
// apply APP_CONTAINER class
html = _outerHtml(jQuery(html).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId));
// optionally apply wrapper html
if (_config.appRender) {
html = _config.appRender(appConfig, html);
}
// apply APP class and instanceId
return _outerHtml(html);
};
/**
* Rendering hook to allow containers to render some html prior to an app
* loading
* @method _beforeAppRender
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {Element} The DOM Element surrounding the app
*/
var _beforeAppRender = function(appConfig) {
var handler = _config.beforeAppRender || jQuery.noop;
return handler(appConfig);
};
/**
* Handler to inform the container that a script failed to load
* @method _onScriptLoadFailure
* @deprecated This has been replaced with {{#crossLink "F2.AppHandlers"}}{{/crossLink}} and will be removed in v2.0
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param scriptInfo The path of the script that failed to load or the exception info
* for the inline script that failed to execute
*/
var _appScriptLoadFailed = function(appConfig, scriptInfo) {
var handler = _config.appScriptLoadFailed || jQuery.noop;
return handler(appConfig, scriptInfo);
};
/**
* Adds properties to the AppConfig object
* @method _createAppConfig
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @return {F2.AppConfig} The new F2.AppConfig object, prepopulated with
* necessary properties
*/
var _createAppConfig = function(appConfig) {
// make a copy of the app config to ensure that the original is not modified
appConfig = jQuery.extend(true, {}, appConfig);
// create the instanceId for the app
appConfig.instanceId = appConfig.instanceId || F2.guid();
// default the views if not provided
appConfig.views = appConfig.views || [];
if (!F2.inArray(F2.Constants.Views.HOME, appConfig.views)) {
appConfig.views.push(F2.Constants.Views.HOME);
}
return appConfig;
};
/**
* Adds properties to the ContainerConfig object to take advantage of defaults
* @method _hydrateContainerConfig
* @private
* @param {F2.ContainerConfig} containerConfig The F2.ContainerConfig object
*/
var _hydrateContainerConfig = function(containerConfig) {
if (!containerConfig.scriptErrorTimeout) {
containerConfig.scriptErrorTimeout = F2.ContainerConfig.scriptErrorTimeout;
}
if (containerConfig.debugMode !== true) {
containerConfig.debugMode = F2.ContainerConfig.debugMode;
}
};
/**
* Attach app events
* @method _initAppEvents
* @private
*/
var _initAppEvents = function(appConfig) {
jQuery(appConfig.root).on('click', '.' + F2.Constants.Css.APP_VIEW_TRIGGER + '[' + F2.Constants.Views.DATA_ATTRIBUTE + ']', function(event) {
event.preventDefault();
var view = jQuery(this).attr(F2.Constants.Views.DATA_ATTRIBUTE).toLowerCase();
// handle the special REMOVE view
if (view == F2.Constants.Views.REMOVE) {
F2.removeApp(appConfig.instanceId);
}
else {
appConfig.ui.Views.change(view);
}
});
};
/**
* Attach container Events
* @method _initContainerEvents
* @private
*/
var _initContainerEvents = function() {
var resizeTimeout;
var resizeHandler = function() {
F2.Events.emit(F2.Constants.Events.CONTAINER_WIDTH_CHANGE);
};
jQuery(window).on('resize', function() {
clearTimeout(resizeTimeout);
resizeTimeout = setTimeout(resizeHandler, 100);
});
};
/**
* Has the container been init?
* @method _isInit
* @private
* @return {bool} True if the container has been init
*/
var _isInit = function() {
return !!_config;
};
/**
* Instantiates each app from it's appConfig and stores that in a local private collection
* @method _createAppInstance
* @private
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
*/
var _createAppInstance = function(appConfig, appContent) {
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// instantiate F2.App
if (F2.Apps[appConfig.appId] !== undefined) {
if (typeof F2.Apps[appConfig.appId] === 'function') {
// IE
setTimeout(function() {
_apps[appConfig.instanceId].app = new F2.Apps[appConfig.appId](appConfig, appContent, appConfig.root);
if (_apps[appConfig.instanceId].app['init'] !== undefined) {
_apps[appConfig.instanceId].app.init();
}
}, 0);
}
else {
F2.log('app initialization class is defined but not a function. (' + appConfig.appId + ')');
}
}
};
/**
* Loads the app's html/css/javascript
* @method loadApp
* @private
* @param {Array} appConfigs An array of
* {{#crossLink "F2.AppConfig"}}{{/crossLink}} objects
* @param {F2.AppManifest} [appManifest] The AppManifest object
*/
var _loadApps = function(appConfigs, appManifest) {
appConfigs = [].concat(appConfigs);
// check for secure app
if (appConfigs.length == 1 && appConfigs[0].isSecure && !_config.isSecureAppPage) {
_loadSecureApp(appConfigs[0], appManifest);
return;
}
// check that the number of apps in manifest matches the number requested
if (appConfigs.length != appManifest.apps.length) {
F2.log('The number of apps defined in the AppManifest do not match the number requested.', appManifest);
return;
}
// Fn for loading manifest Styles
var _loadStyles = function(styles, cb) {
// Attempt to use the user provided method
if (_config.loadStyles) {
_config.loadStyles(styles, cb);
}
else {
// load styles, see #101
var stylesFragment = null,
useCreateStyleSheet = !! document.createStyleSheet;
jQuery.each(styles, function(i, e) {
if (useCreateStyleSheet) {
document.createStyleSheet(e);
}
else {
stylesFragment = stylesFragment || [];
stylesFragment.push('<link rel="stylesheet" type="text/css" href="' + e + '"/>');
}
});
if (stylesFragment) {
jQuery('head').append(stylesFragment.join(''));
}
cb();
}
};
// Fn for loading manifest Scripts
var _loadScripts = function(scripts, cb) {
// Attempt to use the user provided method
if (_config.loadScripts) {
_config.loadScripts(scripts, cb);
}
else {
if (scripts.length) {
var scriptCount = scripts.length;
var scriptsLoaded = 0;
// Check for IE10+ so that we don't rely on onreadystatechange
var readyStates = ('addEventListener' in window) ? {} : {
'loaded': true,
'complete': true
};
// Log and emit event for the failed (400,500) scripts
var _error = function(e) {
setTimeout(function() {
var evtData = {
src: e.target.src,
appId: appConfigs[0].appId
};
// Send error to console
F2.log('Script defined in \'' + evtData.appId + '\' failed to load \'' + evtData.src + '\'');
// Emit event
F2.Events.emit('RESOURCE_FAILED_TO_LOAD', evtData);
if (!_bUsesAppHandlers) {
_appScriptLoadFailed(appConfigs[0], evtData.src);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
appConfigs[0],
evtData.src
);
}
}, _config.scriptErrorTimeout); // Defaults to 7000
};
// Load scripts and eval inlines once complete
jQuery.each(scripts, function(i, e) {
var doc = document,
script = doc.createElement('script'),
resourceUrl = e;
// If in debugMode, add cache buster to each script URL
if (_config.debugMode) {
resourceUrl += '?cachebuster=' + new Date().getTime();
}
// Scripts needed to be loaded in order they're defined in the AppManifest
script.async = false;
// Add other attrs
script.src = resourceUrl;
script.type = 'text/javascript';
script.charset = 'utf-8';
script.onerror = _error;
// Use a closure for the load event so that we can dereference the original script
script.onload = script.onreadystatechange = function(e) {
e = e || window.event; // For older IE
if (e.type == 'load' || readyStates[script.readyState]) {
// Done, cleanup
script.onload = script.onreadystatechange = script.onerror = null;
// Dereference script
script = null;
// Are we done loading all scripts for this app?
if (++scriptsLoaded === scriptCount) {
cb();
}
}
};
doc.body.appendChild(script);
});
}
else {
cb();
}
}
};
var _loadInlineScripts = function(inlines, cb) {
// Attempt to use the user provided method
if (_config.loadInlineScripts) {
_config.loadInlineScripts(inlines, cb);
}
else {
for (var i = 0, len = inlines.length; i < len; i++) {
try {
eval(inlines[i]);
}
catch (exception) {
F2.log('Error loading inline script: ' + exception + '\n\n' + inlines[i]);
if (!_bUsesAppHandlers) {
_appScriptLoadFailed(appConfigs[0], exception);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_SCRIPT_LOAD_FAILED,
appConfigs[0],
exception
);
}
}
}
cb();
}
};
// Determine whether an element has been added to the page
var elementInDocument = function(element) {
if (element) {
while (element.parentNode) {
element = element.parentNode;
if (element === document) {
return true;
}
}
}
return false;
};
// Fn for loading manifest app html
var _loadHtml = function(apps) {
jQuery.each(apps, function(i, a) {
if (!_bUsesAppHandlers) {
// load html and save the root node
appConfigs[i].root = _afterAppRender(appConfigs[i], _appRender(appConfigs[i], a.html));
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfigs[i], // the app config
_outerHtml(a.html)
);
var appId = appConfigs[i].appId;
var root = appConfigs[i].root;
if (!root) {
throw ('Root for ' + appId + ' must be a native DOM element and cannot be null or undefined. Check your AppHandler callbacks to ensure you have set App root to a native DOM element.');
}
if (!elementInDocument(root)) {
throw ('App root for ' + appId + ' was not appended to the DOM. Check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfigs[i] // the app config
);
if (!F2.isNativeDOMNode(root)) {
throw ('App root for ' + appId + ' must be a native DOM element. Check your AppHandler callbacks to ensure you have set app root to a native DOM element.');
}
$(root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appId);
}
// init events
_initAppEvents(appConfigs[i]);
});
};
// Pull out the manifest data
var scripts = appManifest.scripts || [];
var styles = appManifest.styles || [];
var inlines = appManifest.inlineScripts || [];
var apps = appManifest.apps || [];
// Finally, load the styles, html, and scripts
_loadStyles(styles, function() {
// Put the html on the page
_loadHtml(apps);
// Add the script content to the page
_loadScripts(scripts, function() {
// Load any inline scripts
_loadInlineScripts(inlines, function() {
// Create the apps
jQuery.each(appConfigs, function(i, a) {
_createAppInstance(a, appManifest.apps[i]);
});
});
});
});
};
/**
* Loads the app's html/css/javascript into an iframe
* @method loadSecureApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @param {F2.AppManifest} appManifest The app's html/css/js to be loaded into the
* page.
*/
var _loadSecureApp = function(appConfig, appManifest) {
// make sure the container is configured for secure apps
if (_config.secureAppPagePath) {
if (!_bUsesAppHandlers) {
// create the html container for the iframe
appConfig.root = _afterAppRender(appConfig, _appRender(appConfig, '<div></div>'));
}
else {
var $root = jQuery(appConfig.root);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER,
appConfig, // the app config
appManifest.html
);
if ($root.parents('body:first').length === 0) {
throw ('App was never rendered on the page. Please check your AppHandler callbacks to ensure you have rendered the app root to the DOM.');
}
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_AFTER,
appConfig // the app config
);
if (!appConfig.root) {
throw ('App Root must be a native dom node and can not be null or undefined. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
if (!F2.isNativeDOMNode(appConfig.root)) {
throw ('App Root must be a native dom node. Please check your AppHandler callbacks to ensure you have set App Root to a native dom node.');
}
jQuery(appConfig.root).addClass(F2.Constants.Css.APP_CONTAINER + ' ' + appConfig.appId);
}
// instantiate F2.UI
appConfig.ui = new F2.UI(appConfig);
// init events
_initAppEvents(appConfig);
// create RPC socket
F2.Rpc.register(appConfig, appManifest);
}
else {
F2.log('Unable to load secure app: "secureAppPagePath" is not defined in F2.ContainerConfig.');
}
};
var _outerHtml = function(html) {
return jQuery('<div></div>').append(html).html();
};
/**
* Checks if the app is valid
* @method _validateApp
* @private
* @param {F2.AppConfig} appConfig The F2.AppConfig object
* @returns {bool} True if the app is valid
*/
var _validateApp = function(appConfig) {
// check for valid app configurations
if (!appConfig.appId) {
F2.log('"appId" missing from app object');
return false;
}
else if (!appConfig.root && !appConfig.manifestUrl) {
F2.log('"manifestUrl" missing from app object');
return false;
}
return true;
};
/**
* Checks if the ContainerConfig is valid
* @method _validateContainerConfig
* @private
* @returns {bool} True if the config is valid
*/
var _validateContainerConfig = function() {
if (_config) {
if (_config.xhr) {
if (!(typeof _config.xhr === 'function' || typeof _config.xhr === 'object')) {
throw ('ContainerConfig.xhr should be a function or an object');
}
if (_config.xhr.dataType && typeof _config.xhr.dataType !== 'function') {
throw ('ContainerConfig.xhr.dataType should be a function');
}
if (_config.xhr.type && typeof _config.xhr.type !== 'function') {
throw ('ContainerConfig.xhr.type should be a function');
}
if (_config.xhr.url && typeof _config.xhr.url !== 'function') {
throw ('ContainerConfig.xhr.url should be a function');
}
}
}
return true;
};
return {
/**
* Gets the current list of apps in the container
* @method getContainerState
* @returns {Array} An array of objects containing the appId
*/
getContainerState: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.getContainerState()');
return;
}
return jQuery.map(_apps, function(app) {
return {
appId: app.config.appId
};
});
},
/**
* Initializes the container. This method must be called before performing
* any other actions in the container.
* @method init
* @param {F2.ContainerConfig} config The configuration object
*/
init: function(config) {
_config = config || {};
_validateContainerConfig();
_hydrateContainerConfig(_config);
// dictates whether we use the old logic or the new logic.
// TODO: Remove in v2.0
_bUsesAppHandlers = (!_config.beforeAppRender && !_config.appRender && !_config.afterAppRender && !_config.appScriptLoadFailed);
// only establish RPC connection if the container supports the secure app page
if ( !! _config.secureAppPagePath || _config.isSecureAppPage) {
F2.Rpc.init( !! _config.secureAppPagePath ? _config.secureAppPagePath : false);
}
F2.UI.init(_config);
if (!_config.isSecureAppPage) {
_initContainerEvents();
}
},
/**
* Has the container been init?
* @method isInit
* @return {bool} True if the container has been init
*/
isInit: _isInit,
/**
* Begins the loading process for all apps and/or initialization process for pre-loaded apps.
* The app will be passed the {{#crossLink "F2.AppConfig"}}{{/crossLink}} object which will
* contain the app's unique instanceId within the container. If the
* {{#crossLink "F2.AppConfig"}}{{/crossLink}}.root property is populated the app is considered
* to be a pre-loaded app and will be handled accordingly. Optionally, the
* {{#crossLink "F2.AppManifest"}}{{/crossLink}} can be passed in and those
* assets will be used instead of making a request.
* @method registerApps
* @param {Array} appConfigs An array of {{#crossLink "F2.AppConfig"}}{{/crossLink}}
* objects
* @param {Array} [appManifests] An array of
* {{#crossLink "F2.AppManifest"}}{{/crossLink}}
* objects. This array must be the same length as the apps array that is
* objects. This array must be the same length as the apps array that is
* passed in. This can be useful if apps are loaded on the server-side and
* passed down to the client.
* @example
* Traditional App requests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* },
* {
* appId: 'com_externaldomain_example_app2',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Pre-loaded and tradition apps mixed.
*
* // Pre-loaded apps and traditional f2 app configs
* // you can preload the same app multiple times as long as you have a unique root for each
* var arConfigs = [
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-1',
* manifestUrl: ''
* },
* {
* appId: 'com_mydomain_example_app',
* context: {},
* root: 'div#example-app-2',
* manifestUrl: ''
* },
* {
* appId: 'com_externaldomain_example_app',
* context: {},
* manifestUrl: 'http://www.externaldomain.com/F2/AppManifest'
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs);
*
* @example
* Apps with predefined manifests.
*
* // Traditional f2 app configs
* var arConfigs = [
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app', context: {}},
* {appId: 'com_externaldomain_example_app2', context: {}}
* ];
*
* // Pre requested manifest responses
* var arManifests = [
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/AppClass.js'],
* styles: ['http://www.domain.com/css/AppStyles.css']
* },
* {
* apps: ['<div>Example App 2!</div>'],
* inlineScripts: [],
* scripts: ['http://www.domain.com/js/App2Class.js'],
* styles: ['http://www.domain.com/css/App2Styles.css']
* }
* ];
*
* F2.init();
* F2.registerApps(arConfigs, arManifests);
*/
registerApps: function(appConfigs, appManifests) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.registerApps()');
return;
}
else if (!appConfigs) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
}
var appStack = [];
var batches = {};
var callbackStack = {};
var haveManifests = false;
appConfigs = [].concat(appConfigs);
appManifests = [].concat(appManifests || []);
haveManifests = !! appManifests.length;
// appConfigs must have a length
if (!appConfigs.length) {
F2.log('At least one AppConfig must be passed when calling F2.registerApps()');
return;
// ensure that the array of apps and manifests are qual
}
else if (appConfigs.length && haveManifests && appConfigs.length != appManifests.length) {
F2.log('The length of "apps" does not equal the length of "appManifests"');
return;
}
// validate each app and assign it an instanceId
// then determine which apps can be batched together
jQuery.each(appConfigs, function(i, a) {
// add properties and methods
a = _createAppConfig(a);
// Will set to itself, for preloaded apps, or set to null for apps that aren't already
// on the page.
a.root = a.root || null;
// we validate the app after setting the root property because pre-load apps do no require
// manifest url
if (!_validateApp(a)) {
return; // move to the next app
}
// save app
_apps[a.instanceId] = {
config: a
};
// If the root property is defined then this app is considered to be preloaded and we will
// run it through that logic.
if (a.root) {
if ((!a.root && typeof(a.root) != 'string') && !F2.isNativeDOMNode(a.root)) {
F2.log('AppConfig invalid for pre-load, not a valid string and not dom node');
F2.log('AppConfig instance:', a);
throw ('Preloaded appConfig.root property must be a native dom node or a string representing a sizzle selector. Please check your inputs and try again.');
}
else if (jQuery(a.root).length != 1) {
F2.log('AppConfig invalid for pre-load, root not unique');
F2.log('AppConfig instance:', a);
F2.log('Number of dom node instances:', jQuery(a.root).length);
throw ('Preloaded appConfig.root property must map to a unique dom node. Please check your inputs and try again.');
}
// instantiate F2.App
_createAppInstance(a);
// init events
_initAppEvents(a);
// Continue on in the .each loop, no need to continue because the app is on the page
// the js in initialized, and it is ready to role.
return; // equivalent to continue in .each
}
if (!_bUsesAppHandlers) {
// fire beforeAppRender
a.root = _beforeAppRender(a);
}
else {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_CREATE_ROOT,
a // the app config
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_RENDER_BEFORE,
a // the app config
);
}
// if we have the manifest, go ahead and load the app
if (haveManifests) {
_loadApps(a, appManifests[i]);
}
else {
// check if this app can be batched
if (a.enableBatchRequests && !a.isSecure) {
batches[a.manifestUrl.toLowerCase()] = batches[a.manifestUrl.toLowerCase()] || [];
batches[a.manifestUrl.toLowerCase()].push(a);
}
else {
appStack.push({
apps: [a],
url: a.manifestUrl
});
}
}
});
// we don't have the manifests, go ahead and load them
if (!haveManifests) {
// add the batches to the appStack
jQuery.each(batches, function(i, b) {
appStack.push({
url: i,
apps: b
});
});
// if an app is being loaded more than once on the page, there is the
// potential that the jsonp callback will be clobbered if the request
// for the AppManifest for the app comes back at the same time as
// another request for the same app. We'll create a callbackStack
// that will ensure that requests for the same app are loaded in order
// rather than at the same time
jQuery.each(appStack, function(i, req) {
// define the callback function based on the first app's App ID
var jsonpCallback = F2.Constants.JSONP_CALLBACK + req.apps[0].appId;
// push the request onto the callback stack
callbackStack[jsonpCallback] = callbackStack[jsonpCallback] || [];
callbackStack[jsonpCallback].push(req);
});
// loop through each item in the callback stack and make the request
// for the AppManifest. When the request is complete, pop the next
// request off the stack and make the request.
jQuery.each(callbackStack, function(i, requests) {
var manifestRequest = function(jsonpCallback, req) {
if (!req) {
return;
}
// setup defaults and callbacks
var url = req.url,
type = 'GET',
dataType = 'jsonp',
completeFunc = function() {
manifestRequest(i, requests.pop());
},
errorFunc = function() {
jQuery.each(req.apps, function(idx, item) {
F2.log('Removed failed ' + item.name + ' app', item);
F2.removeApp(item.instanceId);
});
},
successFunc = function(appManifest) {
_loadApps(req.apps, appManifest);
};
// optionally fire xhr overrides
if (_config.xhr && _config.xhr.dataType) {
dataType = _config.xhr.dataType(req.url, req.apps);
if (typeof dataType !== 'string') {
throw ('ContainerConfig.xhr.dataType should return a string');
}
}
if (_config.xhr && _config.xhr.type) {
type = _config.xhr.type(req.url, req.apps);
if (typeof type !== 'string') {
throw ('ContainerConfig.xhr.type should return a string');
}
}
if (_config.xhr && _config.xhr.url) {
url = _config.xhr.url(req.url, req.apps);
if (typeof url !== 'string') {
throw ('ContainerConfig.xhr.url should return a string');
}
}
// setup the default request function if an override is not present
var requestFunc = _config.xhr;
if (typeof requestFunc !== 'function') {
requestFunc = function(url, appConfigs, successCallback, errorCallback, completeCallback) {
jQuery.ajax({
url: url,
type: type,
data: {
params: F2.stringify(req.apps, F2.appConfigReplacer)
},
jsonp: false, // do not put 'callback=' in the query string
jsonpCallback: jsonpCallback, // Unique function name
dataType: dataType,
success: successCallback,
error: function(jqxhr, settings, exception) {
F2.log('Failed to load app(s)', exception.toString(), req.apps);
errorCallback();
},
complete: completeCallback
});
};
}
requestFunc(url, req.apps, successFunc, errorFunc, completeFunc);
};
manifestRequest(i, requests.pop());
});
}
},
/**
* Removes all apps from the container
* @method removeAllApps
*/
removeAllApps: function() {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeAllApps()');
return;
}
jQuery.each(_apps, function(i, a) {
F2.removeApp(a.config.instanceId);
});
},
/**
* Removes an app from the container
* @method removeApp
* @param {string} instanceId The app's instanceId
*/
removeApp: function(instanceId) {
if (!_isInit()) {
F2.log('F2.init() must be called before F2.removeApp()');
return;
}
if (_apps[instanceId]) {
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_BEFORE,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY,
_apps[instanceId] // the app instance
);
F2.AppHandlers.__trigger(
_sAppHandlerToken,
F2.Constants.AppHandlers.APP_DESTROY_AFTER,
_apps[instanceId] // the app instance
);
delete _apps[instanceId];
}
}
};
})());
exports.F2 = F2;
if (typeof define !== 'undefined' && define.amd) {
define(function() {
return F2;
});
}
})(typeof exports !== 'undefined' ? exports : window);
|
app/javascript/mastodon/features/home_timeline/index.js
|
tootsuite/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import { expandHomeTimeline } from '../../actions/timelines';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnSettingsContainer from './containers/column_settings_container';
import { Link } from 'react-router-dom';
import { fetchAnnouncements, toggleShowAnnouncements } from 'mastodon/actions/announcements';
import AnnouncementsContainer from 'mastodon/features/getting_started/containers/announcements_container';
import classNames from 'classnames';
import IconWithBadge from 'mastodon/components/icon_with_badge';
const messages = defineMessages({
title: { id: 'column.home', defaultMessage: 'Home' },
show_announcements: { id: 'home.show_announcements', defaultMessage: 'Show announcements' },
hide_announcements: { id: 'home.hide_announcements', defaultMessage: 'Hide announcements' },
});
const mapStateToProps = state => ({
hasUnread: state.getIn(['timelines', 'home', 'unread']) > 0,
isPartial: state.getIn(['timelines', 'home', 'isPartial']),
hasAnnouncements: !state.getIn(['announcements', 'items']).isEmpty(),
unreadAnnouncements: state.getIn(['announcements', 'items']).count(item => !item.get('read')),
showAnnouncements: state.getIn(['announcements', 'show']),
});
export default @connect(mapStateToProps)
@injectIntl
class HomeTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
hasUnread: PropTypes.bool,
isPartial: PropTypes.bool,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasAnnouncements: PropTypes.bool,
unreadAnnouncements: PropTypes.number,
showAnnouncements: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HOME', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
this.props.dispatch(expandHomeTimeline({ maxId }));
}
componentDidMount () {
setTimeout(() => this.props.dispatch(fetchAnnouncements()), 700);
this._checkIfReloadNeeded(false, this.props.isPartial);
}
componentDidUpdate (prevProps) {
this._checkIfReloadNeeded(prevProps.isPartial, this.props.isPartial);
}
componentWillUnmount () {
this._stopPolling();
}
_checkIfReloadNeeded (wasPartial, isPartial) {
const { dispatch } = this.props;
if (wasPartial === isPartial) {
return;
} else if (!wasPartial && isPartial) {
this.polling = setInterval(() => {
dispatch(expandHomeTimeline());
}, 3000);
} else if (wasPartial && !isPartial) {
this._stopPolling();
}
}
_stopPolling () {
if (this.polling) {
clearInterval(this.polling);
this.polling = null;
}
}
handleToggleAnnouncementsClick = (e) => {
e.stopPropagation();
this.props.dispatch(toggleShowAnnouncements());
}
render () {
const { intl, hasUnread, columnId, multiColumn, hasAnnouncements, unreadAnnouncements, showAnnouncements } = this.props;
const pinned = !!columnId;
let announcementsButton = null;
if (hasAnnouncements) {
announcementsButton = (
<button
className={classNames('column-header__button', { 'active': showAnnouncements })}
title={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)}
aria-label={intl.formatMessage(showAnnouncements ? messages.hide_announcements : messages.show_announcements)}
aria-pressed={showAnnouncements ? 'true' : 'false'}
onClick={this.handleToggleAnnouncementsClick}
>
<IconWithBadge id='bullhorn' count={unreadAnnouncements} />
</button>
);
}
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='home'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
extraButton={announcementsButton}
appendContent={hasAnnouncements && showAnnouncements && <AnnouncementsContainer />}
>
<ColumnSettingsContainer />
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`home_timeline-${columnId}`}
onLoadMore={this.handleLoadMore}
timelineId='home'
emptyMessage={<FormattedMessage id='empty_column.home' defaultMessage='Your home timeline is empty! Follow more people to fill it up. {suggestions}' values={{ suggestions: <Link to='/start'><FormattedMessage id='empty_column.home.suggestions' defaultMessage='See some suggestions' /></Link> }} />}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.