target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
app/javascript/flavours/glitch/components/animated_number.js
Kirishima21/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedNumber } from 'react-intl'; import TransitionMotion from 'react-motion/lib/TransitionMotion'; import spring from 'react-motion/lib/spring'; import { reduceMotion } from 'flavours/glitch/util/initial_state'; const obfuscatedCount = count => { if (count < 0) { return 0; } else if (count <= 1) { return count; } else { return '1+'; } }; export default class AnimatedNumber extends React.PureComponent { static propTypes = { value: PropTypes.number.isRequired, obfuscate: PropTypes.bool, }; state = { direction: 1, }; componentWillReceiveProps (nextProps) { if (nextProps.value > this.props.value) { this.setState({ direction: 1 }); } else if (nextProps.value < this.props.value) { this.setState({ direction: -1 }); } } willEnter = () => { const { direction } = this.state; return { y: -1 * direction }; } willLeave = () => { const { direction } = this.state; return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) }; } render () { const { value, obfuscate } = this.props; const { direction } = this.state; if (reduceMotion) { return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />; } const styles = [{ key: `${value}`, data: value, style: { y: spring(0, { damping: 35, stiffness: 400 }) }, }]; return ( <TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}> {items => ( <span className='animated-number'> {items.map(({ key, data, style }) => ( <span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span> ))} </span> )} </TransitionMotion> ); } }
ajax/libs/aui/5.2-m6/js/aui-dependencies.js
johngerome/cdnjs
/*! AUI Flat Pack - version 5.2-m6 - generated 2013-05-29 03:12:37 -0400 */ /* * jQuery JavaScript Library v1.8.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (function(a2,aB){var w,af,o=a2.document,aI=a2.location,d=a2.navigator,bg=a2.jQuery,I=a2.$,am=Array.prototype.push,a4=Array.prototype.slice,aK=Array.prototype.indexOf,z=Object.prototype.toString,V=Object.prototype.hasOwnProperty,aO=String.prototype.trim,bG=function(e,bZ){return new bG.fn.init(e,bZ,w)},bx=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,aa=/\S/,aV=/\s+/,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,bo=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,a=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,bf=/^[\],:{}\s]*$/,bi=/(?:^|:|,)(?:\s*\[)+/g,bD=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,a0=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,bP=/^-ms-/,aU=/-([\da-z])/gi,N=function(e,bZ){return(bZ+"").toUpperCase()},aF=function(){if(o.addEventListener){o.removeEventListener("DOMContentLoaded",aF,false);bG.ready()}else{if(o.readyState==="complete"){o.detachEvent("onreadystatechange",aF);bG.ready()}}},Z={};bG.fn=bG.prototype={constructor:bG,init:function(e,b2,b1){var b0,b3,bZ,b4;if(!e){return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){b0=[null,e,null]}else{b0=bo.exec(e)}if(b0&&(b0[1]||!b2)){if(b0[1]){b2=b2 instanceof bG?b2[0]:b2;b4=(b2&&b2.nodeType?b2.ownerDocument||b2:o);e=bG.parseHTML(b0[1],b4,true);if(a.test(b0[1])&&bG.isPlainObject(b2)){this.attr.call(e,b2,true)}return bG.merge(this,e)}else{b3=o.getElementById(b0[2]);if(b3&&b3.parentNode){if(b3.id!==b0[2]){return b1.find(e)}this.length=1;this[0]=b3}this.context=o;this.selector=e;return this}}else{if(!b2||b2.jquery){return(b2||b1).find(e)}else{return this.constructor(b2).find(e)}}}else{if(bG.isFunction(e)){return b1.ready(e)}}if(e.selector!==aB){this.selector=e.selector;this.context=e.context}return bG.makeArray(e,this)},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return a4.call(this)},get:function(e){return e==null?this.toArray():(e<0?this[this.length+e]:this[e])},pushStack:function(bZ,b1,e){var b0=bG.merge(this.constructor(),bZ);b0.prevObject=this;b0.context=this.context;if(b1==="find"){b0.selector=this.selector+(this.selector?" ":"")+e}else{if(b1){b0.selector=this.selector+"."+b1+"("+e+")"}}return b0},each:function(bZ,e){return bG.each(this,bZ,e)},ready:function(e){bG.ready.promise().done(e);return this},eq:function(e){e=+e;return e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(a4.apply(this,arguments),"slice",a4.call(arguments).join(","))},map:function(e){return this.pushStack(bG.map(this,function(b0,bZ){return e.call(b0,bZ,b0)}))},end:function(){return this.prevObject||this.constructor(null)},push:am,sort:[].sort,splice:[].splice};bG.fn.init.prototype=bG.fn;bG.extend=bG.fn.extend=function(){var b7,b0,e,bZ,b4,b5,b3=arguments[0]||{},b2=1,b1=arguments.length,b6=false;if(typeof b3==="boolean"){b6=b3;b3=arguments[1]||{};b2=2}if(typeof b3!=="object"&&!bG.isFunction(b3)){b3={}}if(b1===b2){b3=this;--b2}for(;b2<b1;b2++){if((b7=arguments[b2])!=null){for(b0 in b7){e=b3[b0];bZ=b7[b0];if(b3===bZ){continue}if(b6&&bZ&&(bG.isPlainObject(bZ)||(b4=bG.isArray(bZ)))){if(b4){b4=false;b5=e&&bG.isArray(e)?e:[]}else{b5=e&&bG.isPlainObject(e)?e:{}}b3[b0]=bG.extend(b6,b5,bZ)}else{if(bZ!==aB){b3[b0]=bZ}}}}}return b3};bG.extend({noConflict:function(e){if(a2.$===bG){a2.$=I}if(e&&a2.jQuery===bG){a2.jQuery=bg}return bG},isReady:false,readyWait:1,holdReady:function(e){if(e){bG.readyWait++}else{bG.ready(true)}},ready:function(e){if(e===true?--bG.readyWait:bG.isReady){return}if(!o.body){return setTimeout(bG.ready,1)}bG.isReady=true;if(e!==true&&--bG.readyWait>0){return}af.resolveWith(o,[bG]);if(bG.fn.trigger){bG(o).trigger("ready").off("ready")}},isFunction:function(e){return bG.type(e)==="function"},isArray:Array.isArray||function(e){return bG.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return !isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):Z[z.call(e)]||"object"},isPlainObject:function(b1){if(!b1||bG.type(b1)!=="object"||b1.nodeType||bG.isWindow(b1)){return false}try{if(b1.constructor&&!V.call(b1,"constructor")&&!V.call(b1.constructor.prototype,"isPrototypeOf")){return false}}catch(b0){return false}var bZ;for(bZ in b1){}return bZ===aB||V.call(b1,bZ)},isEmptyObject:function(bZ){var e;for(e in bZ){return false}return true},error:function(e){throw new Error(e)},parseHTML:function(b1,b0,e){var bZ;if(!b1||typeof b1!=="string"){return null}if(typeof b0==="boolean"){e=b0;b0=0}b0=b0||o;if((bZ=a.exec(b1))){return[b0.createElement(bZ[1])]}bZ=bG.buildFragment([b1],b0,e?null:[]);return bG.merge([],(bZ.cacheable?bG.clone(bZ.fragment):bZ.fragment).childNodes)},parseJSON:function(e){if(!e||typeof e!=="string"){return null}e=bG.trim(e);if(a2.JSON&&a2.JSON.parse){return a2.JSON.parse(e)}if(bf.test(e.replace(bD,"@").replace(a0,"]").replace(bi,""))){return(new Function("return "+e))()}bG.error("Invalid JSON: "+e)},parseXML:function(b1){var bZ,b0;if(!b1||typeof b1!=="string"){return null}try{if(a2.DOMParser){b0=new DOMParser();bZ=b0.parseFromString(b1,"text/xml")}else{bZ=new ActiveXObject("Microsoft.XMLDOM");bZ.async="false";bZ.loadXML(b1)}}catch(b2){bZ=aB}if(!bZ||!bZ.documentElement||bZ.getElementsByTagName("parsererror").length){bG.error("Invalid XML: "+b1)}return bZ},noop:function(){},globalEval:function(e){if(e&&aa.test(e)){(a2.execScript||function(bZ){a2["eval"].call(a2,bZ)})(e)}},camelCase:function(e){return e.replace(bP,"ms-").replace(aU,N)},nodeName:function(bZ,e){return bZ.nodeName&&bZ.nodeName.toLowerCase()===e.toLowerCase()},each:function(b3,b4,b0){var bZ,b1=0,b2=b3.length,e=b2===aB||bG.isFunction(b3);if(b0){if(e){for(bZ in b3){if(b4.apply(b3[bZ],b0)===false){break}}}else{for(;b1<b2;){if(b4.apply(b3[b1++],b0)===false){break}}}}else{if(e){for(bZ in b3){if(b4.call(b3[bZ],bZ,b3[bZ])===false){break}}}else{for(;b1<b2;){if(b4.call(b3[b1],b1,b3[b1++])===false){break}}}}return b3},trim:aO&&!aO.call("\uFEFF\xA0")?function(e){return e==null?"":aO.call(e)}:function(e){return e==null?"":(e+"").replace(C,"")},makeArray:function(e,b0){var b1,bZ=b0||[];if(e!=null){b1=bG.type(e);if(e.length==null||b1==="string"||b1==="function"||b1==="regexp"||bG.isWindow(e)){am.call(bZ,e)}else{bG.merge(bZ,e)}}return bZ},inArray:function(b1,bZ,b0){var e;if(bZ){if(aK){return aK.call(bZ,b1,b0)}e=bZ.length;b0=b0?b0<0?Math.max(0,e+b0):b0:0;for(;b0<e;b0++){if(b0 in bZ&&bZ[b0]===b1){return b0}}}return -1},merge:function(b2,b0){var e=b0.length,b1=b2.length,bZ=0;if(typeof e==="number"){for(;bZ<e;bZ++){b2[b1++]=b0[bZ]}}else{while(b0[bZ]!==aB){b2[b1++]=b0[bZ++]}}b2.length=b1;return b2},grep:function(bZ,b4,e){var b3,b0=[],b1=0,b2=bZ.length;e=!!e;for(;b1<b2;b1++){b3=!!b4(bZ[b1],b1);if(e!==b3){b0.push(bZ[b1])}}return b0},map:function(e,b5,b6){var b3,b4,b2=[],b0=0,bZ=e.length,b1=e instanceof bG||bZ!==aB&&typeof bZ==="number"&&((bZ>0&&e[0]&&e[bZ-1])||bZ===0||bG.isArray(e));if(b1){for(;b0<bZ;b0++){b3=b5(e[b0],b0,b6);if(b3!=null){b2[b2.length]=b3}}}else{for(b4 in e){b3=b5(e[b4],b4,b6);if(b3!=null){b2[b2.length]=b3}}}return b2.concat.apply([],b2)},guid:1,proxy:function(b2,b1){var b0,e,bZ;if(typeof b1==="string"){b0=b2[b1];b1=b2;b2=b0}if(!bG.isFunction(b2)){return aB}e=a4.call(arguments,2);bZ=function(){return b2.apply(b1,e.concat(a4.call(arguments)))};bZ.guid=b2.guid=b2.guid||bG.guid++;return bZ},access:function(e,b4,b7,b5,b2,b8,b6){var b0,b3=b7==null,b1=0,bZ=e.length;if(b7&&typeof b7==="object"){for(b1 in b7){bG.access(e,b4,b1,b7[b1],1,b8,b5)}b2=1}else{if(b5!==aB){b0=b6===aB&&bG.isFunction(b5);if(b3){if(b0){b0=b4;b4=function(ca,b9,cb){return b0.call(bG(ca),cb)}}else{b4.call(e,b5);b4=null}}if(b4){for(;b1<bZ;b1++){b4(e[b1],b7,b0?b5.call(e[b1],b1,b4(e[b1],b7)):b5,b6)}}b2=1}}return b2?e:b3?b4.call(e):bZ?b4(e[0],b7):b8},now:function(){return(new Date()).getTime()}});bG.ready.promise=function(b2){if(!af){af=bG.Deferred();if(o.readyState==="complete"){setTimeout(bG.ready,1)}else{if(o.addEventListener){o.addEventListener("DOMContentLoaded",aF,false);a2.addEventListener("load",bG.ready,false)}else{o.attachEvent("onreadystatechange",aF);a2.attachEvent("onload",bG.ready);var b1=false;try{b1=a2.frameElement==null&&o.documentElement}catch(b0){}if(b1&&b1.doScroll){(function bZ(){if(!bG.isReady){try{b1.doScroll("left")}catch(b3){return setTimeout(bZ,50)}bG.ready()}})()}}}}return af.promise(b2)};bG.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(bZ,e){Z["[object "+e+"]"]=e.toLowerCase()});w=bG(o);var bU={};function ac(bZ){var e=bU[bZ]={};bG.each(bZ.split(aV),function(b1,b0){e[b0]=true});return e}bG.Callbacks=function(b8){b8=typeof b8==="string"?(bU[b8]||ac(b8)):bG.extend({},b8);var b1,e,b2,b0,b3,b4,b5=[],b6=!b8.once&&[],bZ=function(b9){b1=b8.memory&&b9;e=true;b4=b0||0;b0=0;b3=b5.length;b2=true;for(;b5&&b4<b3;b4++){if(b5[b4].apply(b9[0],b9[1])===false&&b8.stopOnFalse){b1=false;break}}b2=false;if(b5){if(b6){if(b6.length){bZ(b6.shift())}}else{if(b1){b5=[]}else{b7.disable()}}}},b7={add:function(){if(b5){var ca=b5.length;(function b9(cb){bG.each(cb,function(cd,cc){var ce=bG.type(cc);if(ce==="function"){if(!b8.unique||!b7.has(cc)){b5.push(cc)}}else{if(cc&&cc.length&&ce!=="string"){b9(cc)}}})})(arguments);if(b2){b3=b5.length}else{if(b1){b0=ca;bZ(b1)}}}return this},remove:function(){if(b5){bG.each(arguments,function(cb,b9){var ca;while((ca=bG.inArray(b9,b5,ca))>-1){b5.splice(ca,1);if(b2){if(ca<=b3){b3--}if(ca<=b4){b4--}}}})}return this},has:function(b9){return bG.inArray(b9,b5)>-1},empty:function(){b5=[];return this},disable:function(){b5=b6=b1=aB;return this},disabled:function(){return !b5},lock:function(){b6=aB;if(!b1){b7.disable()}return this},locked:function(){return !b6},fireWith:function(ca,b9){b9=b9||[];b9=[ca,b9.slice?b9.slice():b9];if(b5&&(!e||b6)){if(b2){b6.push(b9)}else{bZ(b9)}}return this},fire:function(){b7.fireWith(this,arguments);return this},fired:function(){return !!e}};return b7};bG.extend({Deferred:function(b0){var bZ=[["resolve","done",bG.Callbacks("once memory"),"resolved"],["reject","fail",bG.Callbacks("once memory"),"rejected"],["notify","progress",bG.Callbacks("memory")]],b1="pending",b2={state:function(){return b1},always:function(){e.done(arguments).fail(arguments);return this},then:function(){var b3=arguments;return bG.Deferred(function(b4){bG.each(bZ,function(b6,b5){var b8=b5[0],b7=b3[b6];e[b5[1]](bG.isFunction(b7)?function(){var b9=b7.apply(this,arguments);if(b9&&bG.isFunction(b9.promise)){b9.promise().done(b4.resolve).fail(b4.reject).progress(b4.notify)}else{b4[b8+"With"](this===e?b4:this,[b9])}}:b4[b8])});b3=null}).promise()},promise:function(b3){return b3!=null?bG.extend(b3,b2):b2}},e={};b2.pipe=b2.then;bG.each(bZ,function(b4,b3){var b6=b3[2],b5=b3[3];b2[b3[1]]=b6.add;if(b5){b6.add(function(){b1=b5},bZ[b4^1][2].disable,bZ[2][2].lock)}e[b3[0]]=b6.fire;e[b3[0]+"With"]=b6.fireWith});b2.promise(e);if(b0){b0.call(e,e)}return e},when:function(b2){var b0=0,b4=a4.call(arguments),e=b4.length,bZ=e!==1||(b2&&bG.isFunction(b2.promise))?e:0,b7=bZ===1?b2:bG.Deferred(),b1=function(b9,ca,b8){return function(cb){ca[b9]=this;b8[b9]=arguments.length>1?a4.call(arguments):cb;if(b8===b6){b7.notifyWith(ca,b8)}else{if(!(--bZ)){b7.resolveWith(ca,b8)}}}},b6,b3,b5;if(e>1){b6=new Array(e);b3=new Array(e);b5=new Array(e);for(;b0<e;b0++){if(b4[b0]&&bG.isFunction(b4[b0].promise)){b4[b0].promise().done(b1(b0,b5,b4)).fail(b7.reject).progress(b1(b0,b3,b6))}else{--bZ}}}if(!bZ){b7.resolveWith(b5,b4)}return b7.promise()}});bG.support=(function(){var cb,ca,b8,b9,b2,b7,b6,b4,b3,b1,bZ,b0=o.createElement("div");b0.setAttribute("className","t");b0.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";ca=b0.getElementsByTagName("*");b8=b0.getElementsByTagName("a")[0];if(!ca||!b8||!ca.length){return{}}b9=o.createElement("select");b2=b9.appendChild(o.createElement("option"));b7=b0.getElementsByTagName("input")[0];b8.style.cssText="top:1px;float:left;opacity:.5";cb={leadingWhitespace:(b0.firstChild.nodeType===3),tbody:!b0.getElementsByTagName("tbody").length,htmlSerialize:!!b0.getElementsByTagName("link").length,style:/top/.test(b8.getAttribute("style")),hrefNormalized:(b8.getAttribute("href")==="/a"),opacity:/^0.5/.test(b8.style.opacity),cssFloat:!!b8.style.cssFloat,checkOn:(b7.value==="on"),optSelected:b2.selected,getSetAttribute:b0.className!=="t",enctype:!!o.createElement("form").enctype,html5Clone:o.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",boxModel:(o.compatMode==="CSS1Compat"),submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true,boxSizingReliable:true,pixelPosition:false};b7.checked=true;cb.noCloneChecked=b7.cloneNode(true).checked;b9.disabled=true;cb.optDisabled=!b2.disabled;try{delete b0.test}catch(b5){cb.deleteExpando=false}if(!b0.addEventListener&&b0.attachEvent&&b0.fireEvent){b0.attachEvent("onclick",bZ=function(){cb.noCloneEvent=false});b0.cloneNode(true).fireEvent("onclick");b0.detachEvent("onclick",bZ)}b7=o.createElement("input");b7.value="t";b7.setAttribute("type","radio");cb.radioValue=b7.value==="t";b7.setAttribute("checked","checked");b7.setAttribute("name","t");b0.appendChild(b7);b6=o.createDocumentFragment();b6.appendChild(b0.lastChild);cb.checkClone=b6.cloneNode(true).cloneNode(true).lastChild.checked;cb.appendChecked=b7.checked;b6.removeChild(b7);b6.appendChild(b0);if(b0.attachEvent){for(b3 in {submit:true,change:true,focusin:true}){b4="on"+b3;b1=(b4 in b0);if(!b1){b0.setAttribute(b4,"return;");b1=(typeof b0[b4]==="function")}cb[b3+"Bubbles"]=b1}}bG(function(){var cc,cg,ce,cf,cd="padding:0;margin:0;border:0;display:block;overflow:hidden;",e=o.getElementsByTagName("body")[0];if(!e){return}cc=o.createElement("div");cc.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";e.insertBefore(cc,e.firstChild);cg=o.createElement("div");cc.appendChild(cg);cg.innerHTML="<table><tr><td></td><td>t</td></tr></table>";ce=cg.getElementsByTagName("td");ce[0].style.cssText="padding:0;margin:0;border:0;display:none";b1=(ce[0].offsetHeight===0);ce[0].style.display="";ce[1].style.display="none";cb.reliableHiddenOffsets=b1&&(ce[0].offsetHeight===0);cg.innerHTML="";cg.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%;";cb.boxSizing=(cg.offsetWidth===4);cb.doesNotIncludeMarginInBodyOffset=(e.offsetTop!==1);if(a2.getComputedStyle){cb.pixelPosition=(a2.getComputedStyle(cg,null)||{}).top!=="1%";cb.boxSizingReliable=(a2.getComputedStyle(cg,null)||{width:"4px"}).width==="4px";cf=o.createElement("div");cf.style.cssText=cg.style.cssText=cd;cf.style.marginRight=cf.style.width="0";cg.style.width="1px";cg.appendChild(cf);cb.reliableMarginRight=!parseFloat((a2.getComputedStyle(cf,null)||{}).marginRight)}if(typeof cg.style.zoom!=="undefined"){cg.innerHTML="";cg.style.cssText=cd+"width:1px;padding:1px;display:inline;zoom:1";cb.inlineBlockNeedsLayout=(cg.offsetWidth===3);cg.style.display="block";cg.style.overflow="visible";cg.innerHTML="<div></div>";cg.firstChild.style.width="5px";cb.shrinkWrapBlocks=(cg.offsetWidth!==3);cc.style.zoom=1}e.removeChild(cc);cc=cg=ce=cf=null});b6.removeChild(b0);ca=b8=b9=b2=b7=b6=b0=null;return cb})();var bt=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,aL=/([A-Z])/g;bG.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(bG.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},hasData:function(e){e=e.nodeType?bG.cache[e[bG.expando]]:e[bG.expando];return !!e&&!O(e)},data:function(b1,bZ,b3,b2){if(!bG.acceptData(b1)){return}var b4,b6,b7=bG.expando,b5=typeof bZ==="string",b8=b1.nodeType,e=b8?bG.cache:b1,b0=b8?b1[b7]:b1[b7]&&b7;if((!b0||!e[b0]||(!b2&&!e[b0].data))&&b5&&b3===aB){return}if(!b0){if(b8){b1[b7]=b0=bG.deletedIds.pop()||bG.guid++}else{b0=b7}}if(!e[b0]){e[b0]={};if(!b8){e[b0].toJSON=bG.noop}}if(typeof bZ==="object"||typeof bZ==="function"){if(b2){e[b0]=bG.extend(e[b0],bZ)}else{e[b0].data=bG.extend(e[b0].data,bZ)}}b4=e[b0];if(!b2){if(!b4.data){b4.data={}}b4=b4.data}if(b3!==aB){b4[bG.camelCase(bZ)]=b3}if(b5){b6=b4[bZ];if(b6==null){b6=b4[bG.camelCase(bZ)]}}else{b6=b4}return b6},removeData:function(b1,bZ,b2){if(!bG.acceptData(b1)){return}var b5,b4,b3,b6=b1.nodeType,e=b6?bG.cache:b1,b0=b6?b1[bG.expando]:bG.expando;if(!e[b0]){return}if(bZ){b5=b2?e[b0]:e[b0].data;if(b5){if(!bG.isArray(bZ)){if(bZ in b5){bZ=[bZ]}else{bZ=bG.camelCase(bZ);if(bZ in b5){bZ=[bZ]}else{bZ=bZ.split(" ")}}}for(b4=0,b3=bZ.length;b4<b3;b4++){delete b5[bZ[b4]]}if(!(b2?O:bG.isEmptyObject)(b5)){return}}}if(!b2){delete e[b0].data;if(!O(e[b0])){return}}if(b6){bG.cleanData([b1],true)}else{if(bG.support.deleteExpando||e!=e.window){delete e[b0]}else{e[b0]=null}}},_data:function(bZ,e,b0){return bG.data(bZ,e,b0,true)},acceptData:function(bZ){var e=bZ.nodeName&&bG.noData[bZ.nodeName.toLowerCase()];return !e||e!==true&&bZ.getAttribute("classid")===e}});bG.fn.extend({data:function(b7,b6){var b2,bZ,b5,e,b1,b0=this[0],b4=0,b3=null;if(b7===aB){if(this.length){b3=bG.data(b0);if(b0.nodeType===1&&!bG._data(b0,"parsedAttrs")){b5=b0.attributes;for(b1=b5.length;b4<b1;b4++){e=b5[b4].name;if(!e.indexOf("data-")){e=bG.camelCase(e.substring(5));bv(b0,e,b3[e])}}bG._data(b0,"parsedAttrs",true)}}return b3}if(typeof b7==="object"){return this.each(function(){bG.data(this,b7)})}b2=b7.split(".",2);b2[1]=b2[1]?"."+b2[1]:"";bZ=b2[1]+"!";return bG.access(this,function(b8){if(b8===aB){b3=this.triggerHandler("getData"+bZ,[b2[0]]);if(b3===aB&&b0){b3=bG.data(b0,b7);b3=bv(b0,b7,b3)}return b3===aB&&b2[1]?this.data(b2[0]):b3}b2[1]=b8;this.each(function(){var b9=bG(this);b9.triggerHandler("setData"+bZ,b2);bG.data(this,b7,b8);b9.triggerHandler("changeData"+bZ,b2)})},null,b6,arguments.length>1,null,false)},removeData:function(e){return this.each(function(){bG.removeData(this,e)})}});function bv(b1,b0,b2){if(b2===aB&&b1.nodeType===1){var bZ="data-"+b0.replace(aL,"-$1").toLowerCase();b2=b1.getAttribute(bZ);if(typeof b2==="string"){try{b2=b2==="true"?true:b2==="false"?false:b2==="null"?null:+b2+""===b2?+b2:bt.test(b2)?bG.parseJSON(b2):b2}catch(b3){}bG.data(b1,b0,b2)}else{b2=aB}}return b2}function O(bZ){var e;for(e in bZ){if(e==="data"&&bG.isEmptyObject(bZ[e])){continue}if(e!=="toJSON"){return false}}return true}bG.extend({queue:function(b0,bZ,b1){var e;if(b0){bZ=(bZ||"fx")+"queue";e=bG._data(b0,bZ);if(b1){if(!e||bG.isArray(b1)){e=bG._data(b0,bZ,bG.makeArray(b1))}else{e.push(b1)}}return e||[]}},dequeue:function(b3,b2){b2=b2||"fx";var bZ=bG.queue(b3,b2),b4=bZ.length,b1=bZ.shift(),e=bG._queueHooks(b3,b2),b0=function(){bG.dequeue(b3,b2)};if(b1==="inprogress"){b1=bZ.shift();b4--}if(b1){if(b2==="fx"){bZ.unshift("inprogress")}delete e.stop;b1.call(b3,b0,e)}if(!b4&&e){e.empty.fire()}},_queueHooks:function(b0,bZ){var e=bZ+"queueHooks";return bG._data(b0,e)||bG._data(b0,e,{empty:bG.Callbacks("once memory").add(function(){bG.removeData(b0,bZ+"queue",true);bG.removeData(b0,e,true)})})}});bG.fn.extend({queue:function(e,bZ){var b0=2;if(typeof e!=="string"){bZ=e;e="fx";b0--}if(arguments.length<b0){return bG.queue(this[0],e)}return bZ===aB?this:this.each(function(){var b1=bG.queue(this,e,bZ);bG._queueHooks(this,e);if(e==="fx"&&b1[0]!=="inprogress"){bG.dequeue(this,e)}})},dequeue:function(e){return this.each(function(){bG.dequeue(this,e)})},delay:function(bZ,e){bZ=bG.fx?bG.fx.speeds[bZ]||bZ:bZ;e=e||"fx";return this.queue(e,function(b1,b0){var b2=setTimeout(b1,bZ);b0.stop=function(){clearTimeout(b2)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(b0,b4){var bZ,b1=1,b5=bG.Deferred(),b3=this,e=this.length,b2=function(){if(!(--b1)){b5.resolveWith(b3,[b3])}};if(typeof b0!=="string"){b4=b0;b0=aB}b0=b0||"fx";while(e--){bZ=bG._data(b3[e],b0+"queueHooks");if(bZ&&bZ.empty){b1++;bZ.empty.add(b2)}}b2();return b5.promise(b4)}});var a7,bV,n,bJ=/[\t\r\n]/g,ai=/\r/g,j=/^(?:button|input)$/i,aA=/^(?:button|input|object|select|textarea)$/i,D=/^a(?:rea|)$/i,M=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,bL=bG.support.getSetAttribute;bG.fn.extend({attr:function(e,bZ){return bG.access(this,bG.attr,e,bZ,arguments.length>1)},removeAttr:function(e){return this.each(function(){bG.removeAttr(this,e)})},prop:function(e,bZ){return bG.access(this,bG.prop,e,bZ,arguments.length>1)},removeProp:function(e){e=bG.propFix[e]||e;return this.each(function(){try{this[e]=aB;delete this[e]}catch(bZ){}})},addClass:function(b2){var b4,b0,bZ,b1,b3,b5,e;if(bG.isFunction(b2)){return this.each(function(b6){bG(this).addClass(b2.call(this,b6,this.className))})}if(b2&&typeof b2==="string"){b4=b2.split(aV);for(b0=0,bZ=this.length;b0<bZ;b0++){b1=this[b0];if(b1.nodeType===1){if(!b1.className&&b4.length===1){b1.className=b2}else{b3=" "+b1.className+" ";for(b5=0,e=b4.length;b5<e;b5++){if(b3.indexOf(" "+b4[b5]+" ")<0){b3+=b4[b5]+" "}}b1.className=bG.trim(b3)}}}}return this},removeClass:function(b4){var b1,b2,b3,b5,bZ,b0,e;if(bG.isFunction(b4)){return this.each(function(b6){bG(this).removeClass(b4.call(this,b6,this.className))})}if((b4&&typeof b4==="string")||b4===aB){b1=(b4||"").split(aV);for(b0=0,e=this.length;b0<e;b0++){b3=this[b0];if(b3.nodeType===1&&b3.className){b2=(" "+b3.className+" ").replace(bJ," ");for(b5=0,bZ=b1.length;b5<bZ;b5++){while(b2.indexOf(" "+b1[b5]+" ")>=0){b2=b2.replace(" "+b1[b5]+" "," ")}}b3.className=b4?bG.trim(b2):""}}}return this},toggleClass:function(b1,bZ){var b0=typeof b1,e=typeof bZ==="boolean";if(bG.isFunction(b1)){return this.each(function(b2){bG(this).toggleClass(b1.call(this,b2,this.className,bZ),bZ)})}return this.each(function(){if(b0==="string"){var b4,b3=0,b2=bG(this),b5=bZ,b6=b1.split(aV);while((b4=b6[b3++])){b5=e?b5:!b2.hasClass(b4);b2[b5?"addClass":"removeClass"](b4)}}else{if(b0==="undefined"||b0==="boolean"){if(this.className){bG._data(this,"__className__",this.className)}this.className=this.className||b1===false?"":bG._data(this,"__className__")||""}}})},hasClass:function(e){var b1=" "+e+" ",b0=0,bZ=this.length;for(;b0<bZ;b0++){if(this[b0].nodeType===1&&(" "+this[b0].className+" ").replace(bJ," ").indexOf(b1)>=0){return true}}return false},val:function(b1){var e,bZ,b2,b0=this[0];if(!arguments.length){if(b0){e=bG.valHooks[b0.type]||bG.valHooks[b0.nodeName.toLowerCase()];if(e&&"get" in e&&(bZ=e.get(b0,"value"))!==aB){return bZ}bZ=b0.value;return typeof bZ==="string"?bZ.replace(ai,""):bZ==null?"":bZ}return}b2=bG.isFunction(b1);return this.each(function(b4){var b5,b3=bG(this);if(this.nodeType!==1){return}if(b2){b5=b1.call(this,b4,b3.val())}else{b5=b1}if(b5==null){b5=""}else{if(typeof b5==="number"){b5+=""}else{if(bG.isArray(b5)){b5=bG.map(b5,function(b6){return b6==null?"":b6+""})}}}e=bG.valHooks[this.type]||bG.valHooks[this.nodeName.toLowerCase()];if(!e||!("set" in e)||e.set(this,b5,"value")===aB){this.value=b5}})}});bG.extend({valHooks:{option:{get:function(e){var bZ=e.attributes.value;return !bZ||bZ.specified?e.value:e.text}},select:{get:function(e){var b4,b0,b6=e.options,b2=e.selectedIndex,b1=e.type==="select-one"||b2<0,b5=b1?null:[],b3=b1?b2+1:b6.length,bZ=b2<0?b3:b1?b2:0;for(;bZ<b3;bZ++){b0=b6[bZ];if((b0.selected||bZ===b2)&&(bG.support.optDisabled?!b0.disabled:b0.getAttribute("disabled")===null)&&(!b0.parentNode.disabled||!bG.nodeName(b0.parentNode,"optgroup"))){b4=bG(b0).val();if(b1){return b4}b5.push(b4)}}return b5},set:function(bZ,b0){var e=bG.makeArray(b0);bG(bZ).find("option").each(function(){this.selected=bG.inArray(bG(this).val(),e)>=0});if(!e.length){bZ.selectedIndex=-1}return e}}},attrFn:{},attr:function(b4,b1,b5,b3){var b0,e,b2,bZ=b4.nodeType;if(!b4||bZ===3||bZ===8||bZ===2){return}if(b3&&bG.isFunction(bG.fn[b1])){return bG(b4)[b1](b5)}if(typeof b4.getAttribute==="undefined"){return bG.prop(b4,b1,b5)}b2=bZ!==1||!bG.isXMLDoc(b4);if(b2){b1=b1.toLowerCase();e=bG.attrHooks[b1]||(M.test(b1)?bV:a7)}if(b5!==aB){if(b5===null){bG.removeAttr(b4,b1);return}else{if(e&&"set" in e&&b2&&(b0=e.set(b4,b5,b1))!==aB){return b0}else{b4.setAttribute(b1,b5+"");return b5}}}else{if(e&&"get" in e&&b2&&(b0=e.get(b4,b1))!==null){return b0}else{b0=b4.getAttribute(b1);return b0===null?aB:b0}}},removeAttr:function(b1,b3){var b2,b4,bZ,e,b0=0;if(b3&&b1.nodeType===1){b4=b3.split(aV);for(;b0<b4.length;b0++){bZ=b4[b0];if(bZ){b2=bG.propFix[bZ]||bZ;e=M.test(bZ);if(!e){bG.attr(b1,bZ,"")}b1.removeAttribute(bL?bZ:b2);if(e&&b2 in b1){b1[b2]=false}}}}},attrHooks:{type:{set:function(e,bZ){if(j.test(e.nodeName)&&e.parentNode){bG.error("type property can't be changed")}else{if(!bG.support.radioValue&&bZ==="radio"&&bG.nodeName(e,"input")){var b0=e.value;e.setAttribute("type",bZ);if(b0){e.value=b0}return bZ}}}},value:{get:function(bZ,e){if(a7&&bG.nodeName(bZ,"button")){return a7.get(bZ,e)}return e in bZ?bZ.value:null},set:function(bZ,b0,e){if(a7&&bG.nodeName(bZ,"button")){return a7.set(bZ,b0,e)}bZ.value=b0}}},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(b3,b1,b4){var b0,e,b2,bZ=b3.nodeType;if(!b3||bZ===3||bZ===8||bZ===2){return}b2=bZ!==1||!bG.isXMLDoc(b3);if(b2){b1=bG.propFix[b1]||b1;e=bG.propHooks[b1]}if(b4!==aB){if(e&&"set" in e&&(b0=e.set(b3,b4,b1))!==aB){return b0}else{return(b3[b1]=b4)}}else{if(e&&"get" in e&&(b0=e.get(b3,b1))!==null){return b0}else{return b3[b1]}}},propHooks:{tabIndex:{get:function(bZ){var e=bZ.getAttributeNode("tabindex");return e&&e.specified?parseInt(e.value,10):aA.test(bZ.nodeName)||D.test(bZ.nodeName)&&bZ.href?0:aB}}}});bV={get:function(bZ,e){var b1,b0=bG.prop(bZ,e);return b0===true||typeof b0!=="boolean"&&(b1=bZ.getAttributeNode(e))&&b1.nodeValue!==false?e.toLowerCase():aB},set:function(bZ,b1,e){var b0;if(b1===false){bG.removeAttr(bZ,e)}else{b0=bG.propFix[e]||e;if(b0 in bZ){bZ[b0]=true}bZ.setAttribute(e,e.toLowerCase())}return e}};if(!bL){n={name:true,id:true,coords:true};a7=bG.valHooks.button={get:function(b0,bZ){var e;e=b0.getAttributeNode(bZ);return e&&(n[bZ]?e.value!=="":e.specified)?e.value:aB},set:function(b0,b1,bZ){var e=b0.getAttributeNode(bZ);if(!e){e=o.createAttribute(bZ);b0.setAttributeNode(e)}return(e.value=b1+"")}};bG.each(["width","height"],function(bZ,e){bG.attrHooks[e]=bG.extend(bG.attrHooks[e],{set:function(b0,b1){if(b1===""){b0.setAttribute(e,"auto");return b1}}})});bG.attrHooks.contenteditable={get:a7.get,set:function(bZ,b0,e){if(b0===""){b0="false"}a7.set(bZ,b0,e)}}}if(!bG.support.hrefNormalized){bG.each(["href","src","width","height"],function(bZ,e){bG.attrHooks[e]=bG.extend(bG.attrHooks[e],{get:function(b1){var b0=b1.getAttribute(e,2);return b0===null?aB:b0}})})}if(!bG.support.style){bG.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||aB},set:function(e,bZ){return(e.style.cssText=bZ+"")}}}if(!bG.support.optSelected){bG.propHooks.selected=bG.extend(bG.propHooks.selected,{get:function(bZ){var e=bZ.parentNode;if(e){e.selectedIndex;if(e.parentNode){e.parentNode.selectedIndex}}return null}})}if(!bG.support.enctype){bG.propFix.enctype="encoding"}if(!bG.support.checkOn){bG.each(["radio","checkbox"],function(){bG.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}})}bG.each(["radio","checkbox"],function(){bG.valHooks[this]=bG.extend(bG.valHooks[this],{set:function(e,bZ){if(bG.isArray(bZ)){return(e.checked=bG.inArray(bG(e).val(),bZ)>=0)}}})});var bE=/^(?:textarea|input|select)$/i,br=/^([^\.]*|)(?:\.(.+)|)$/,ba=/(?:^|\s)hover(\.\S+|)\b/,a3=/^key/,bK=/^(?:mouse|contextmenu)|click/,by=/^(?:focusinfocus|focusoutblur)$/,aq=function(e){return bG.event.special.hover?e:e.replace(ba,"mouseenter$1 mouseleave$1")};bG.event={add:function(b1,b5,cc,b3,b2){var b6,b4,cd,cb,ca,b8,e,b9,bZ,b0,b7;if(b1.nodeType===3||b1.nodeType===8||!b5||!cc||!(b6=bG._data(b1))){return}if(cc.handler){bZ=cc;cc=bZ.handler;b2=bZ.selector}if(!cc.guid){cc.guid=bG.guid++}cd=b6.events;if(!cd){b6.events=cd={}}b4=b6.handle;if(!b4){b6.handle=b4=function(ce){return typeof bG!=="undefined"&&(!ce||bG.event.triggered!==ce.type)?bG.event.dispatch.apply(b4.elem,arguments):aB};b4.elem=b1}b5=bG.trim(aq(b5)).split(" ");for(cb=0;cb<b5.length;cb++){ca=br.exec(b5[cb])||[];b8=ca[1];e=(ca[2]||"").split(".").sort();b7=bG.event.special[b8]||{};b8=(b2?b7.delegateType:b7.bindType)||b8;b7=bG.event.special[b8]||{};b9=bG.extend({type:b8,origType:ca[1],data:b3,handler:cc,guid:cc.guid,selector:b2,needsContext:b2&&bG.expr.match.needsContext.test(b2),namespace:e.join(".")},bZ);b0=cd[b8];if(!b0){b0=cd[b8]=[];b0.delegateCount=0;if(!b7.setup||b7.setup.call(b1,b3,e,b4)===false){if(b1.addEventListener){b1.addEventListener(b8,b4,false)}else{if(b1.attachEvent){b1.attachEvent("on"+b8,b4)}}}}if(b7.add){b7.add.call(b1,b9);if(!b9.handler.guid){b9.handler.guid=cc.guid}}if(b2){b0.splice(b0.delegateCount++,0,b9)}else{b0.push(b9)}bG.event.global[b8]=true}b1=null},global:{},remove:function(b1,b6,cc,b2,b5){var cd,ce,b9,b0,bZ,b3,b4,cb,b8,e,ca,b7=bG.hasData(b1)&&bG._data(b1);if(!b7||!(cb=b7.events)){return}b6=bG.trim(aq(b6||"")).split(" ");for(cd=0;cd<b6.length;cd++){ce=br.exec(b6[cd])||[];b9=b0=ce[1];bZ=ce[2];if(!b9){for(b9 in cb){bG.event.remove(b1,b9+b6[cd],cc,b2,true)}continue}b8=bG.event.special[b9]||{};b9=(b2?b8.delegateType:b8.bindType)||b9;e=cb[b9]||[];b3=e.length;bZ=bZ?new RegExp("(^|\\.)"+bZ.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(b4=0;b4<e.length;b4++){ca=e[b4];if((b5||b0===ca.origType)&&(!cc||cc.guid===ca.guid)&&(!bZ||bZ.test(ca.namespace))&&(!b2||b2===ca.selector||b2==="**"&&ca.selector)){e.splice(b4--,1);if(ca.selector){e.delegateCount--}if(b8.remove){b8.remove.call(b1,ca)}}}if(e.length===0&&b3!==e.length){if(!b8.teardown||b8.teardown.call(b1,bZ,b7.handle)===false){bG.removeEvent(b1,b9,b7.handle)}delete cb[b9]}}if(bG.isEmptyObject(cb)){delete b7.handle;bG.removeData(b1,"events",true)}},customEvent:{getData:true,setData:true,changeData:true},trigger:function(bZ,b6,b4,cd){if(b4&&(b4.nodeType===3||b4.nodeType===8)){return}var e,b1,b7,cb,b3,b2,b9,b8,b5,cc,ca=bZ.type||bZ,b0=[];if(by.test(ca+bG.event.triggered)){return}if(ca.indexOf("!")>=0){ca=ca.slice(0,-1);b1=true}if(ca.indexOf(".")>=0){b0=ca.split(".");ca=b0.shift();b0.sort()}if((!b4||bG.event.customEvent[ca])&&!bG.event.global[ca]){return}bZ=typeof bZ==="object"?bZ[bG.expando]?bZ:new bG.Event(ca,bZ):new bG.Event(ca);bZ.type=ca;bZ.isTrigger=true;bZ.exclusive=b1;bZ.namespace=b0.join(".");bZ.namespace_re=bZ.namespace?new RegExp("(^|\\.)"+b0.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;b2=ca.indexOf(":")<0?"on"+ca:"";if(!b4){e=bG.cache;for(b7 in e){if(e[b7].events&&e[b7].events[ca]){bG.event.trigger(bZ,b6,e[b7].handle.elem,true)}}return}bZ.result=aB;if(!bZ.target){bZ.target=b4}b6=b6!=null?bG.makeArray(b6):[];b6.unshift(bZ);b9=bG.event.special[ca]||{};if(b9.trigger&&b9.trigger.apply(b4,b6)===false){return}b5=[[b4,b9.bindType||ca]];if(!cd&&!b9.noBubble&&!bG.isWindow(b4)){cc=b9.delegateType||ca;cb=by.test(cc+ca)?b4:b4.parentNode;for(b3=b4;cb;cb=cb.parentNode){b5.push([cb,cc]);b3=cb}if(b3===(b4.ownerDocument||o)){b5.push([b3.defaultView||b3.parentWindow||a2,cc])}}for(b7=0;b7<b5.length&&!bZ.isPropagationStopped();b7++){cb=b5[b7][0];bZ.type=b5[b7][1];b8=(bG._data(cb,"events")||{})[bZ.type]&&bG._data(cb,"handle");if(b8){b8.apply(cb,b6)}b8=b2&&cb[b2];if(b8&&bG.acceptData(cb)&&b8.apply&&b8.apply(cb,b6)===false){bZ.preventDefault()}}bZ.type=ca;if(!cd&&!bZ.isDefaultPrevented()){if((!b9._default||b9._default.apply(b4.ownerDocument,b6)===false)&&!(ca==="click"&&bG.nodeName(b4,"a"))&&bG.acceptData(b4)){if(b2&&b4[ca]&&((ca!=="focus"&&ca!=="blur")||bZ.target.offsetWidth!==0)&&!bG.isWindow(b4)){b3=b4[b2];if(b3){b4[b2]=null}bG.event.triggered=ca;b4[ca]();bG.event.triggered=aB;if(b3){b4[b2]=b3}}}}return bZ.result},dispatch:function(e){e=bG.event.fix(e||a2.event);var b5,b4,ce,b8,b7,bZ,b6,cc,b1,cd,b2=((bG._data(this,"events")||{})[e.type]||[]),b3=b2.delegateCount,ca=a4.call(arguments),b0=!e.exclusive&&!e.namespace,b9=bG.event.special[e.type]||{},cb=[];ca[0]=e;e.delegateTarget=this;if(b9.preDispatch&&b9.preDispatch.call(this,e)===false){return}if(b3&&!(e.button&&e.type==="click")){for(ce=e.target;ce!=this;ce=ce.parentNode||this){if(ce.disabled!==true||e.type!=="click"){b7={};b6=[];for(b5=0;b5<b3;b5++){cc=b2[b5];b1=cc.selector;if(b7[b1]===aB){b7[b1]=cc.needsContext?bG(b1,this).index(ce)>=0:bG.find(b1,this,null,[ce]).length}if(b7[b1]){b6.push(cc)}}if(b6.length){cb.push({elem:ce,matches:b6})}}}}if(b2.length>b3){cb.push({elem:this,matches:b2.slice(b3)})}for(b5=0;b5<cb.length&&!e.isPropagationStopped();b5++){bZ=cb[b5];e.currentTarget=bZ.elem;for(b4=0;b4<bZ.matches.length&&!e.isImmediatePropagationStopped();b4++){cc=bZ.matches[b4];if(b0||(!e.namespace&&!cc.namespace)||e.namespace_re&&e.namespace_re.test(cc.namespace)){e.data=cc.data;e.handleObj=cc;b8=((bG.event.special[cc.origType]||{}).handle||cc.handler).apply(bZ.elem,ca);if(b8!==aB){e.result=b8;if(b8===false){e.preventDefault();e.stopPropagation()}}}}}if(b9.postDispatch){b9.postDispatch.call(this,e)}return e.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(bZ,e){if(bZ.which==null){bZ.which=e.charCode!=null?e.charCode:e.keyCode}return bZ}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(b1,b0){var b2,b3,e,bZ=b0.button,b4=b0.fromElement;if(b1.pageX==null&&b0.clientX!=null){b2=b1.target.ownerDocument||o;b3=b2.documentElement;e=b2.body;b1.pageX=b0.clientX+(b3&&b3.scrollLeft||e&&e.scrollLeft||0)-(b3&&b3.clientLeft||e&&e.clientLeft||0);b1.pageY=b0.clientY+(b3&&b3.scrollTop||e&&e.scrollTop||0)-(b3&&b3.clientTop||e&&e.clientTop||0)}if(!b1.relatedTarget&&b4){b1.relatedTarget=b4===b1.target?b0.toElement:b4}if(!b1.which&&bZ!==aB){b1.which=(bZ&1?1:(bZ&2?3:(bZ&4?2:0)))}return b1}},fix:function(b0){if(b0[bG.expando]){return b0}var bZ,b3,e=b0,b1=bG.event.fixHooks[b0.type]||{},b2=b1.props?this.props.concat(b1.props):this.props;b0=bG.Event(e);for(bZ=b2.length;bZ;){b3=b2[--bZ];b0[b3]=e[b3]}if(!b0.target){b0.target=e.srcElement||o}if(b0.target.nodeType===3){b0.target=b0.target.parentNode}b0.metaKey=!!b0.metaKey;return b1.filter?b1.filter(b0,e):b0},special:{load:{noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(b0,bZ,e){if(bG.isWindow(this)){this.onbeforeunload=e}},teardown:function(bZ,e){if(this.onbeforeunload===e){this.onbeforeunload=null}}}},simulate:function(b0,b2,b1,bZ){var b3=bG.extend(new bG.Event(),b1,{type:b0,isSimulated:true,originalEvent:{}});if(bZ){bG.event.trigger(b3,null,b2)}else{bG.event.dispatch.call(b2,b3)}if(b3.isDefaultPrevented()){b1.preventDefault()}}};bG.event.handle=bG.event.dispatch;bG.removeEvent=o.removeEventListener?function(bZ,e,b0){if(bZ.removeEventListener){bZ.removeEventListener(e,b0,false)}}:function(b0,bZ,b1){var e="on"+bZ;if(b0.detachEvent){if(typeof b0[e]==="undefined"){b0[e]=null}b0.detachEvent(e,b1)}};bG.Event=function(bZ,e){if(!(this instanceof bG.Event)){return new bG.Event(bZ,e)}if(bZ&&bZ.type){this.originalEvent=bZ;this.type=bZ.type;this.isDefaultPrevented=(bZ.defaultPrevented||bZ.returnValue===false||bZ.getPreventDefault&&bZ.getPreventDefault())?R:X}else{this.type=bZ}if(e){bG.extend(this,e)}this.timeStamp=bZ&&bZ.timeStamp||bG.now();this[bG.expando]=true};function X(){return false}function R(){return true}bG.Event.prototype={preventDefault:function(){this.isDefaultPrevented=R;var bZ=this.originalEvent;if(!bZ){return}if(bZ.preventDefault){bZ.preventDefault()}else{bZ.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=R;var bZ=this.originalEvent;if(!bZ){return}if(bZ.stopPropagation){bZ.stopPropagation()}bZ.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=R;this.stopPropagation()},isDefaultPrevented:X,isPropagationStopped:X,isImmediatePropagationStopped:X};bG.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(bZ,e){bG.event.special[bZ]={delegateType:e,bindType:e,handle:function(b3){var b1,b5=this,b4=b3.relatedTarget,b2=b3.handleObj,b0=b2.selector;if(!b4||(b4!==b5&&!bG.contains(b5,b4))){b3.type=b2.origType;b1=b2.handler.apply(this,arguments);b3.type=e}return b1}}});if(!bG.support.submitBubbles){bG.event.special.submit={setup:function(){if(bG.nodeName(this,"form")){return false}bG.event.add(this,"click._submit keypress._submit",function(b1){var b0=b1.target,bZ=bG.nodeName(b0,"input")||bG.nodeName(b0,"button")?b0.form:aB;if(bZ&&!bG._data(bZ,"_submit_attached")){bG.event.add(bZ,"submit._submit",function(e){e._submit_bubble=true});bG._data(bZ,"_submit_attached",true)}})},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;if(this.parentNode&&!e.isTrigger){bG.event.simulate("submit",this.parentNode,e,true)}}},teardown:function(){if(bG.nodeName(this,"form")){return false}bG.event.remove(this,"._submit")}}}if(!bG.support.changeBubbles){bG.event.special.change={setup:function(){if(bE.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){bG.event.add(this,"propertychange._change",function(e){if(e.originalEvent.propertyName==="checked"){this._just_changed=true}});bG.event.add(this,"click._change",function(e){if(this._just_changed&&!e.isTrigger){this._just_changed=false}bG.event.simulate("change",this,e,true)})}return false}bG.event.add(this,"beforeactivate._change",function(b0){var bZ=b0.target;if(bE.test(bZ.nodeName)&&!bG._data(bZ,"_change_attached")){bG.event.add(bZ,"change._change",function(e){if(this.parentNode&&!e.isSimulated&&!e.isTrigger){bG.event.simulate("change",this.parentNode,e,true)}});bG._data(bZ,"_change_attached",true)}})},handle:function(bZ){var e=bZ.target;if(this!==e||bZ.isSimulated||bZ.isTrigger||(e.type!=="radio"&&e.type!=="checkbox")){return bZ.handleObj.handler.apply(this,arguments)}},teardown:function(){bG.event.remove(this,"._change");return !bE.test(this.nodeName)}}}if(!bG.support.focusinBubbles){bG.each({focus:"focusin",blur:"focusout"},function(b1,e){var bZ=0,b0=function(b2){bG.event.simulate(e,b2.target,bG.event.fix(b2),true)};bG.event.special[e]={setup:function(){if(bZ++===0){o.addEventListener(b1,b0,true)}},teardown:function(){if(--bZ===0){o.removeEventListener(b1,b0,true)}}}})}bG.fn.extend({on:function(b0,e,b3,b2,bZ){var b4,b1;if(typeof b0==="object"){if(typeof e!=="string"){b3=b3||e;e=aB}for(b1 in b0){this.on(b1,e,b3,b0[b1],bZ)}return this}if(b3==null&&b2==null){b2=e;b3=e=aB}else{if(b2==null){if(typeof e==="string"){b2=b3;b3=aB}else{b2=b3;b3=e;e=aB}}}if(b2===false){b2=X}else{if(!b2){return this}}if(bZ===1){b4=b2;b2=function(b5){bG().off(b5);return b4.apply(this,arguments)};b2.guid=b4.guid||(b4.guid=bG.guid++)}return this.each(function(){bG.event.add(this,b0,b2,b3,e)})},one:function(bZ,e,b1,b0){return this.on(bZ,e,b1,b0,1)},off:function(b0,e,b2){var bZ,b1;if(b0&&b0.preventDefault&&b0.handleObj){bZ=b0.handleObj;bG(b0.delegateTarget).off(bZ.namespace?bZ.origType+"."+bZ.namespace:bZ.origType,bZ.selector,bZ.handler);return this}if(typeof b0==="object"){for(b1 in b0){this.off(b1,e,b0[b1])}return this}if(e===false||typeof e==="function"){b2=e;e=aB}if(b2===false){b2=X}return this.each(function(){bG.event.remove(this,b0,b2,e)})},bind:function(e,b0,bZ){return this.on(e,null,b0,bZ)},unbind:function(e,bZ){return this.off(e,null,bZ)},live:function(e,b0,bZ){bG(this.context).on(e,this.selector,b0,bZ);return this},die:function(e,bZ){bG(this.context).off(e,this.selector||"**",bZ);return this},delegate:function(e,bZ,b1,b0){return this.on(bZ,e,b1,b0)},undelegate:function(e,bZ,b0){return arguments.length===1?this.off(e,"**"):this.off(bZ,e||"**",b0)},trigger:function(e,bZ){return this.each(function(){bG.event.trigger(e,bZ,this)})},triggerHandler:function(e,bZ){if(this[0]){return bG.event.trigger(e,bZ,this[0],true)}},toggle:function(b1){var bZ=arguments,e=b1.guid||bG.guid++,b0=0,b2=function(b3){var b4=(bG._data(this,"lastToggle"+b1.guid)||0)%b0;bG._data(this,"lastToggle"+b1.guid,b4+1);b3.preventDefault();return bZ[b4].apply(this,arguments)||false};b2.guid=e;while(b0<bZ.length){bZ[b0++].guid=e}return this.click(b2)},hover:function(e,bZ){return this.mouseenter(e).mouseleave(bZ||e)}});bG.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(bZ,e){bG.fn[e]=function(b1,b0){if(b0==null){b0=b1;b1=null}return arguments.length>0?this.on(e,null,b1,b0):this.trigger(e)};if(a3.test(e)){bG.event.fixHooks[e]=bG.event.keyHooks}if(bK.test(e)){bG.event.fixHooks[e]=bG.event.mouseHooks}}); /* * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function(cS,ch){var cX,ca,cL,b0,cm,cA,cd,cg,cc,cJ,b9=true,cu="undefined",cZ=("sizcache"+Math.random()).replace(".",""),b4=String,b8=cS.document,cb=b8.documentElement,cr=0,cf=0,cE=[].pop,cW=[].push,cl=[].slice,co=[].indexOf||function(c8){var c7=0,e=this.length;for(;c7<e;c7++){if(this[c7]===c8){return c7}}return -1},c1=function(e,c7){e[cZ]=c7==null||c7;return e},c5=function(){var e={},c7=[];return c1(function(c8,c9){if(c7.push(c8)>cL.cacheLength){delete e[c7.shift()]}return(e[c8+" "]=c9)},e)},cU=c5(),cV=c5(),cn=c5(),cy="[\\x20\\t\\r\\n\\f]",ck="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",ci=ck.replace("w","w#"),c4="([*^$|!~]?=)",cP="\\["+cy+"*("+ck+")"+cy+"*(?:"+c4+cy+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+ci+")|)|)"+cy+"*\\]",c6=":("+ck+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+cP+")|[^:]|\\\\.)*|.*))\\)|)",cz=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+cy+"*((?:-\\d)?\\d*)"+cy+"*\\)|)(?=[^-]|$)",cT=new RegExp("^"+cy+"+|((?:^|[^\\\\])(?:\\\\.)*)"+cy+"+$","g"),b5=new RegExp("^"+cy+"*,"+cy+"*"),cH=new RegExp("^"+cy+"*([\\x20\\t\\r\\n\\f>+~])"+cy+"*"),cM=new RegExp(c6),cO=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,cD=/^:not/,cR=/[\x20\t\r\n\f]*[+~]/,c0=/:not\($/,cs=/h\d/i,cN=/input|select|textarea|button/i,ct=/\\(?!\\)/g,cG={ID:new RegExp("^#("+ck+")"),CLASS:new RegExp("^\\.("+ck+")"),NAME:new RegExp("^\\[name=['\"]?("+ck+")['\"]?\\]"),TAG:new RegExp("^("+ck.replace("w","w*")+")"),ATTR:new RegExp("^"+cP),PSEUDO:new RegExp("^"+c6),POS:new RegExp(cz,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+cy+"*(even|odd|(([+-]|)(\\d*)n|)"+cy+"*(?:([+-]|)"+cy+"*(\\d+)|))"+cy+"*\\)|)","i"),needsContext:new RegExp("^"+cy+"*[>+~]|"+cz,"i")},cK=function(c7){var c9=b8.createElement("div");try{return c7(c9)}catch(c8){return false}finally{c9=null}},b7=cK(function(e){e.appendChild(b8.createComment(""));return !e.getElementsByTagName("*").length}),cC=cK(function(e){e.innerHTML="<a href='#'></a>";return e.firstChild&&typeof e.firstChild.getAttribute!==cu&&e.firstChild.getAttribute("href")==="#"}),cq=cK(function(c7){c7.innerHTML="<select></select>";var e=typeof c7.lastChild.getAttribute("multiple");return e!=="boolean"&&e!=="string"}),cB=cK(function(e){e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>";if(!e.getElementsByClassName||!e.getElementsByClassName("e").length){return false}e.lastChild.className="e";return e.getElementsByClassName("e").length===2}),bZ=cK(function(c7){c7.id=cZ+0;c7.innerHTML="<a name='"+cZ+"'></a><div name='"+cZ+"'></div>";cb.insertBefore(c7,cb.firstChild);var e=b8.getElementsByName&&b8.getElementsByName(cZ).length===2+b8.getElementsByName(cZ+0).length;ca=!b8.getElementById(cZ);cb.removeChild(c7);return e});try{cl.call(cb.childNodes,0)[0].nodeType}catch(c3){cl=function(c7){var c8,e=[];for(;(c8=this[c7]);c7++){e.push(c8)}return e}}function cQ(c9,e,db,de){db=db||[];e=e||b8;var dc,c7,dd,c8,da=e.nodeType;if(!c9||typeof c9!=="string"){return db}if(da!==1&&da!==9){return[]}dd=cm(e);if(!dd&&!de){if((dc=cO.exec(c9))){if((c8=dc[1])){if(da===9){c7=e.getElementById(c8);if(c7&&c7.parentNode){if(c7.id===c8){db.push(c7);return db}}else{return db}}else{if(e.ownerDocument&&(c7=e.ownerDocument.getElementById(c8))&&cA(e,c7)&&c7.id===c8){db.push(c7);return db}}}else{if(dc[2]){cW.apply(db,cl.call(e.getElementsByTagName(c9),0));return db}else{if((c8=dc[3])&&cB&&e.getElementsByClassName){cW.apply(db,cl.call(e.getElementsByClassName(c8),0));return db}}}}}return cY(c9.replace(cT,"$1"),e,db,de,dd)}cQ.matches=function(c7,e){return cQ(c7,null,null,e)};cQ.matchesSelector=function(e,c7){return cQ(c7,null,null,[e]).length>0};function cI(e){return function(c8){var c7=c8.nodeName.toLowerCase();return c7==="input"&&c8.type===e}}function b3(e){return function(c8){var c7=c8.nodeName.toLowerCase();return(c7==="input"||c7==="button")&&c8.type===e}}function cF(e){return c1(function(c7){c7=+c7;return c1(function(c8,dc){var da,c9=e([],c8.length,c7),db=c9.length;while(db--){if(c8[(da=c9[db])]){c8[da]=!(dc[da]=c8[da])}}})})}b0=cQ.getText=function(da){var c9,c7="",c8=0,e=da.nodeType;if(e){if(e===1||e===9||e===11){if(typeof da.textContent==="string"){return da.textContent}else{for(da=da.firstChild;da;da=da.nextSibling){c7+=b0(da)}}}else{if(e===3||e===4){return da.nodeValue}}}else{for(;(c9=da[c8]);c8++){c7+=b0(c9)}}return c7};cm=cQ.isXML=function(e){var c7=e&&(e.ownerDocument||e).documentElement;return c7?c7.nodeName!=="HTML":false};cA=cQ.contains=cb.contains?function(c7,e){var c9=c7.nodeType===9?c7.documentElement:c7,c8=e&&e.parentNode;return c7===c8||!!(c8&&c8.nodeType===1&&c9.contains&&c9.contains(c8))}:cb.compareDocumentPosition?function(c7,e){return e&&!!(c7.compareDocumentPosition(e)&16)}:function(c7,e){while((e=e.parentNode)){if(e===c7){return true}}return false};cQ.attr=function(c8,c7){var c9,e=cm(c8);if(!e){c7=c7.toLowerCase()}if((c9=cL.attrHandle[c7])){return c9(c8)}if(e||cq){return c8.getAttribute(c7)}c9=c8.getAttributeNode(c7);return c9?typeof c8[c7]==="boolean"?c8[c7]?c7:null:c9.specified?c9.value:null:null};cL=cQ.selectors={cacheLength:50,createPseudo:c1,match:cG,attrHandle:cC?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:ca?function(c9,c8,c7){if(typeof c8.getElementById!==cu&&!c7){var e=c8.getElementById(c9);return e&&e.parentNode?[e]:[]}}:function(c9,c8,c7){if(typeof c8.getElementById!==cu&&!c7){var e=c8.getElementById(c9);return e?e.id===c9||typeof e.getAttributeNode!==cu&&e.getAttributeNode("id").value===c9?[e]:ch:[]}},TAG:b7?function(e,c7){if(typeof c7.getElementsByTagName!==cu){return c7.getElementsByTagName(e)}}:function(e,da){var c9=da.getElementsByTagName(e);if(e==="*"){var db,c8=[],c7=0;for(;(db=c9[c7]);c7++){if(db.nodeType===1){c8.push(db)}}return c8}return c9},NAME:bZ&&function(e,c7){if(typeof c7.getElementsByName!==cu){return c7.getElementsByName(name)}},CLASS:cB&&function(c8,c7,e){if(typeof c7.getElementsByClassName!==cu&&!e){return c7.getElementsByClassName(c8)}}},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(ct,"");e[3]=(e[4]||e[5]||"").replace(ct,"");if(e[2]==="~="){e[3]=" "+e[3]+" "}return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if(e[1]==="nth"){if(!e[2]){cQ.error(e[0])}e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd"));e[4]=+((e[6]+e[7])||e[2]==="odd")}else{if(e[2]){cQ.error(e[0])}}return e},PSEUDO:function(c7){var c8,e;if(cG.CHILD.test(c7[0])){return null}if(c7[3]){c7[2]=c7[3]}else{if((c8=c7[4])){if(cM.test(c8)&&(e=b1(c8,true))&&(e=c8.indexOf(")",c8.length-e)-c8.length)){c8=c8.slice(0,e);c7[0]=c7[0].slice(0,e)}c7[2]=c8}}return c7.slice(0,3)}},filter:{ID:ca?function(e){e=e.replace(ct,"");return function(c7){return c7.getAttribute("id")===e}}:function(e){e=e.replace(ct,"");return function(c8){var c7=typeof c8.getAttributeNode!==cu&&c8.getAttributeNode("id");return c7&&c7.value===e}},TAG:function(e){if(e==="*"){return function(){return true}}e=e.replace(ct,"").toLowerCase();return function(c7){return c7.nodeName&&c7.nodeName.toLowerCase()===e}},CLASS:function(e){var c7=cU[cZ][e+" "];return c7||(c7=new RegExp("(^|"+cy+")"+e+"("+cy+"|$)"))&&cU(e,function(c8){return c7.test(c8.className||(typeof c8.getAttribute!==cu&&c8.getAttribute("class"))||"")})},ATTR:function(c8,c7,e){return function(db,da){var c9=cQ.attr(db,c8);if(c9==null){return c7==="!="}if(!c7){return true}c9+="";return c7==="="?c9===e:c7==="!="?c9!==e:c7==="^="?e&&c9.indexOf(e)===0:c7==="*="?e&&c9.indexOf(e)>-1:c7==="$="?e&&c9.substr(c9.length-e.length)===e:c7==="~="?(" "+c9+" ").indexOf(e)>-1:c7==="|="?c9===e||c9.substr(0,e.length+1)===e+"-":false}},CHILD:function(e,c8,c9,c7){if(e==="nth"){return function(dc){var db,dd,da=dc.parentNode;if(c9===1&&c7===0){return true}if(da){dd=0;for(db=da.firstChild;db;db=db.nextSibling){if(db.nodeType===1){dd++;if(dc===db){break}}}}dd-=c7;return dd===c9||(dd%c9===0&&dd/c9>=0)}}return function(db){var da=db;switch(e){case"only":case"first":while((da=da.previousSibling)){if(da.nodeType===1){return false}}if(e==="first"){return true}da=db;case"last":while((da=da.nextSibling)){if(da.nodeType===1){return false}}return true}}},PSEUDO:function(c9,c8){var e,c7=cL.pseudos[c9]||cL.setFilters[c9.toLowerCase()]||cQ.error("unsupported pseudo: "+c9);if(c7[cZ]){return c7(c8)}if(c7.length>1){e=[c9,c9,"",c8];return cL.setFilters.hasOwnProperty(c9.toLowerCase())?c1(function(dc,de){var db,da=c7(dc,c8),dd=da.length;while(dd--){db=co.call(dc,da[dd]);dc[db]=!(de[db]=da[dd])}}):function(da){return c7(da,0,e)}}return c7}},pseudos:{not:c1(function(e){var c7=[],c8=[],c9=cd(e.replace(cT,"$1"));return c9[cZ]?c1(function(db,dg,de,dc){var df,da=c9(db,null,dc,[]),dd=db.length;while(dd--){if((df=da[dd])){db[dd]=!(dg[dd]=df)}}}):function(dc,db,da){c7[0]=dc;c9(c7,null,da,c8);return !c8.pop()}}),has:c1(function(e){return function(c7){return cQ(e,c7).length>0}}),contains:c1(function(e){return function(c7){return(c7.textContent||c7.innerText||b0(c7)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===false},disabled:function(e){return e.disabled===true},checked:function(e){var c7=e.nodeName.toLowerCase();return(c7==="input"&&!!e.checked)||(c7==="option"&&!!e.selected)},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},parent:function(e){return !cL.pseudos.empty(e)},empty:function(c7){var e;c7=c7.firstChild;while(c7){if(c7.nodeName>"@"||(e=c7.nodeType)===3||e===4){return false}c7=c7.nextSibling}return true},header:function(e){return cs.test(e.nodeName)},text:function(c8){var c7,e;return c8.nodeName.toLowerCase()==="input"&&(c7=c8.type)==="text"&&((e=c8.getAttribute("type"))==null||e.toLowerCase()===c7)},radio:cI("radio"),checkbox:cI("checkbox"),file:cI("file"),password:cI("password"),image:cI("image"),submit:b3("submit"),reset:b3("reset"),button:function(c7){var e=c7.nodeName.toLowerCase();return e==="input"&&c7.type==="button"||e==="button"},input:function(e){return cN.test(e.nodeName)},focus:function(e){var c7=e.ownerDocument;return e===c7.activeElement&&(!c7.hasFocus||c7.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:cF(function(){return[0]}),last:cF(function(e,c7){return[c7-1]}),eq:cF(function(e,c8,c7){return[c7<0?c7+c8:c7]}),even:cF(function(e,c8){for(var c7=0;c7<c8;c7+=2){e.push(c7)}return e}),odd:cF(function(e,c8){for(var c7=1;c7<c8;c7+=2){e.push(c7)}return e}),lt:cF(function(e,c9,c8){for(var c7=c8<0?c8+c9:c8;--c7>=0;){e.push(c7)}return e}),gt:cF(function(e,c9,c8){for(var c7=c8<0?c8+c9:c8;++c7<c9;){e.push(c7)}return e})}};function b2(c7,e,c8){if(c7===e){return c8}var c9=c7.nextSibling;while(c9){if(c9===e){return -1}c9=c9.nextSibling}return 1}cg=cb.compareDocumentPosition?function(c7,e){if(c7===e){cc=true;return 0}return(!c7.compareDocumentPosition||!e.compareDocumentPosition?c7.compareDocumentPosition:c7.compareDocumentPosition(e)&4)?-1:1}:function(de,dd){if(de===dd){cc=true;return 0}else{if(de.sourceIndex&&dd.sourceIndex){return de.sourceIndex-dd.sourceIndex}}var db,c7,c8=[],e=[],da=de.parentNode,dc=dd.parentNode,df=da;if(da===dc){return b2(de,dd)}else{if(!da){return -1}else{if(!dc){return 1}}}while(df){c8.unshift(df);df=df.parentNode}df=dc;while(df){e.unshift(df);df=df.parentNode}db=c8.length;c7=e.length;for(var c9=0;c9<db&&c9<c7;c9++){if(c8[c9]!==e[c9]){return b2(c8[c9],e[c9])}}return c9===db?b2(de,e[c9],-1):b2(c8[c9],dd,1)};[0,0].sort(cg);b9=!cc;cQ.uniqueSort=function(c8){var c9,da=[],c7=1,e=0;cc=b9;c8.sort(cg);if(cc){for(;(c9=c8[c7]);c7++){if(c9===c8[c7-1]){e=da.push(c7)}}while(e--){c8.splice(da[e],1)}}return c8};cQ.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};function b1(da,df){var c7,db,dd,de,dc,c8,e,c9=cV[cZ][da+" "];if(c9){return df?0:c9.slice(0)}dc=da;c8=[];e=cL.preFilter;while(dc){if(!c7||(db=b5.exec(dc))){if(db){dc=dc.slice(db[0].length)||dc}c8.push(dd=[])}c7=false;if((db=cH.exec(dc))){dd.push(c7=new b4(db.shift()));dc=dc.slice(c7.length);c7.type=db[0].replace(cT," ")}for(de in cL.filter){if((db=cG[de].exec(dc))&&(!e[de]||(db=e[de](db)))){dd.push(c7=new b4(db.shift()));dc=dc.slice(c7.length);c7.type=de;c7.matches=db}}if(!c7){break}}return df?dc.length:dc?cQ.error(da):cV(da,c8).slice(0)}function cw(da,c8,c9){var e=c8.dir,db=c9&&c8.dir==="parentNode",c7=cf++;return c8.first?function(de,dd,dc){while((de=de[e])){if(db||de.nodeType===1){return da(de,dd,dc)}}}:function(df,de,dd){if(!dd){var dc,dg=cr+" "+c7+" ",dh=dg+cX;while((df=df[e])){if(db||df.nodeType===1){if((dc=df[cZ])===dh){return df.sizset}else{if(typeof dc==="string"&&dc.indexOf(dg)===0){if(df.sizset){return df}}else{df[cZ]=dh;if(da(df,de,dd)){df.sizset=true;return df}df.sizset=false}}}}}else{while((df=df[e])){if(db||df.nodeType===1){if(da(df,de,dd)){return df}}}}}}function ce(e){return e.length>1?function(da,c9,c7){var c8=e.length;while(c8--){if(!e[c8](da,c9,c7)){return false}}return true}:e[0]}function cv(e,c7,c8,c9,dc){var da,df=[],db=0,dd=e.length,de=c7!=null;for(;db<dd;db++){if((da=e[db])){if(!c8||c8(da,c9,dc)){df.push(da);if(de){c7.push(db)}}}}return df}function c2(c8,c7,da,c9,db,e){if(c9&&!c9[cZ]){c9=c2(c9)}if(db&&!db[cZ]){db=c2(db,e)}return c1(function(dm,dj,de,dl){var dp,dk,dg,df=[],dn=[],dd=dj.length,dc=dm||cp(c7||"*",de.nodeType?[de]:de,[]),dh=c8&&(dm||!c7)?cv(dc,df,c8,de,dl):dc,di=da?db||(dm?c8:dd||c9)?[]:dj:dh;if(da){da(dh,di,de,dl)}if(c9){dp=cv(di,dn);c9(dp,[],de,dl);dk=dp.length;while(dk--){if((dg=dp[dk])){di[dn[dk]]=!(dh[dn[dk]]=dg)}}}if(dm){if(db||c8){if(db){dp=[];dk=di.length;while(dk--){if((dg=di[dk])){dp.push((dh[dk]=dg))}}db(null,(di=[]),dp,dl)}dk=di.length;while(dk--){if((dg=di[dk])&&(dp=db?co.call(dm,dg):df[dk])>-1){dm[dp]=!(dj[dp]=dg)}}}}else{di=cv(di===dj?di.splice(dd,di.length):di);if(db){db(null,dj,di,dl)}else{cW.apply(dj,di)}}})}function cx(dc){var c7,da,c8,db=dc.length,df=cL.relative[dc[0].type],dg=df||cL.relative[" "],c9=df?1:0,dd=cw(function(dh){return dh===c7},dg,true),de=cw(function(dh){return co.call(c7,dh)>-1},dg,true),e=[function(dj,di,dh){return(!df&&(dh||di!==cJ))||((c7=di).nodeType?dd(dj,di,dh):de(dj,di,dh))}];for(;c9<db;c9++){if((da=cL.relative[dc[c9].type])){e=[cw(ce(e),da)]}else{da=cL.filter[dc[c9].type].apply(null,dc[c9].matches);if(da[cZ]){c8=++c9;for(;c8<db;c8++){if(cL.relative[dc[c8].type]){break}}return c2(c9>1&&ce(e),c9>1&&dc.slice(0,c9-1).join("").replace(cT,"$1"),da,c9<c8&&cx(dc.slice(c9,c8)),c8<db&&cx((dc=dc.slice(c8))),c8<db&&dc.join(""))}e.push(da)}}return ce(e)}function b6(c9,c8){var e=c8.length>0,da=c9.length>0,c7=function(dk,de,dj,di,dr){var df,dg,dl,dq=[],dp=0,dh="0",db=dk&&[],dm=dr!=null,dn=cJ,dd=dk||da&&cL.find.TAG("*",dr&&de.parentNode||de),dc=(cr+=dn==null?1:Math.E);if(dm){cJ=de!==b8&&de;cX=c7.el}for(;(df=dd[dh])!=null;dh++){if(da&&df){for(dg=0;(dl=c9[dg]);dg++){if(dl(df,de,dj)){di.push(df);break}}if(dm){cr=dc;cX=++c7.el}}if(e){if((df=!dl&&df)){dp--}if(dk){db.push(df)}}}dp+=dh;if(e&&dh!==dp){for(dg=0;(dl=c8[dg]);dg++){dl(db,dq,de,dj)}if(dk){if(dp>0){while(dh--){if(!(db[dh]||dq[dh])){dq[dh]=cE.call(di)}}}dq=cv(dq)}cW.apply(di,dq);if(dm&&!dk&&dq.length>0&&(dp+c8.length)>1){cQ.uniqueSort(di)}}if(dm){cr=dc;cJ=dn}return db};c7.el=0;return e?c1(c7):c7}cd=cQ.compile=function(e,db){var c8,c7=[],da=[],c9=cn[cZ][e+" "];if(!c9){if(!db){db=b1(e)}c8=db.length;while(c8--){c9=cx(db[c8]);if(c9[cZ]){c7.push(c9)}else{da.push(c9)}}c9=cn(e,b6(da,c7))}return c9};function cp(c7,da,c9){var c8=0,e=da.length;for(;c8<e;c8++){cQ(c7,da[c8],c9)}return c9}function cY(c8,e,da,de,dd){var db,dh,c7,dg,df,dc=b1(c8),c9=dc.length;if(!de){if(dc.length===1){dh=dc[0]=dc[0].slice(0);if(dh.length>2&&(c7=dh[0]).type==="ID"&&e.nodeType===9&&!dd&&cL.relative[dh[1].type]){e=cL.find.ID(c7.matches[0].replace(ct,""),e,dd)[0];if(!e){return da}c8=c8.slice(dh.shift().length)}for(db=cG.POS.test(c8)?-1:dh.length-1;db>=0;db--){c7=dh[db];if(cL.relative[(dg=c7.type)]){break}if((df=cL.find[dg])){if((de=df(c7.matches[0].replace(ct,""),cR.test(dh[0].type)&&e.parentNode||e,dd))){dh.splice(db,1);c8=de.length&&dh.join("");if(!c8){cW.apply(da,cl.call(de,0));return da}break}}}}}cd(c8,dc)(de,e,dd,da,cR.test(c8));return da}if(b8.querySelectorAll){(function(){var db,dc=cY,da=/'|\\/g,c8=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,c7=[":focus"],e=[":active"],c9=cb.matchesSelector||cb.mozMatchesSelector||cb.webkitMatchesSelector||cb.oMatchesSelector||cb.msMatchesSelector;cK(function(dd){dd.innerHTML="<select><option selected=''></option></select>";if(!dd.querySelectorAll("[selected]").length){c7.push("\\["+cy+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)")}if(!dd.querySelectorAll(":checked").length){c7.push(":checked")}});cK(function(dd){dd.innerHTML="<p test=''></p>";if(dd.querySelectorAll("[test^='']").length){c7.push("[*^$]="+cy+"*(?:\"\"|'')")}dd.innerHTML="<input type='hidden'/>";if(!dd.querySelectorAll(":enabled").length){c7.push(":enabled",":disabled")}});c7=new RegExp(c7.join("|"));cY=function(dj,de,dl,dp,dn){if(!dp&&!dn&&!c7.test(dj)){var dh,dm,dg=true,dd=cZ,df=de,dk=de.nodeType===9&&dj;if(de.nodeType===1&&de.nodeName.toLowerCase()!=="object"){dh=b1(dj);if((dg=de.getAttribute("id"))){dd=dg.replace(da,"\\$&")}else{de.setAttribute("id",dd)}dd="[id='"+dd+"'] ";dm=dh.length;while(dm--){dh[dm]=dd+dh[dm].join("")}df=cR.test(dj)&&de.parentNode||de;dk=dh.join(",")}if(dk){try{cW.apply(dl,cl.call(df.querySelectorAll(dk),0));return dl}catch(di){}finally{if(!dg){de.removeAttribute("id")}}}}return dc(dj,de,dl,dp,dn)};if(c9){cK(function(de){db=c9.call(de,"div");try{c9.call(de,"[test!='']:sizzle");e.push("!=",c6)}catch(dd){}});e=new RegExp(e.join("|"));cQ.matchesSelector=function(de,dg){dg=dg.replace(c8,"='$1']");if(!cm(de)&&!e.test(dg)&&!c7.test(dg)){try{var dd=c9.call(de,dg);if(dd||db||de.document&&de.document.nodeType!==11){return dd}}catch(df){}}return cQ(dg,null,null,[de]).length>0}}})()}cL.pseudos.nth=cL.pseudos.eq;function cj(){}cL.filters=cj.prototype=cL.pseudos;cL.setFilters=new cj();cQ.attr=bG.attr;bG.find=cQ;bG.expr=cQ.selectors;bG.expr[":"]=bG.expr.pseudos;bG.unique=cQ.uniqueSort;bG.text=cQ.getText;bG.isXMLDoc=cQ.isXML;bG.contains=cQ.contains})(a2);var ag=/Until$/,bq=/^(?:parents|prev(?:Until|All))/,al=/^.[^:#\[\.,]*$/,y=bG.expr.match.needsContext,bu={children:true,contents:true,next:true,prev:true};bG.fn.extend({find:function(e){var b2,bZ,b4,b5,b3,b1,b0=this;if(typeof e!=="string"){return bG(e).filter(function(){for(b2=0,bZ=b0.length;b2<bZ;b2++){if(bG.contains(b0[b2],this)){return true}}})}b1=this.pushStack("","find",e);for(b2=0,bZ=this.length;b2<bZ;b2++){b4=b1.length;bG.find(e,this[b2],b1);if(b2>0){for(b5=b4;b5<b1.length;b5++){for(b3=0;b3<b4;b3++){if(b1[b3]===b1[b5]){b1.splice(b5--,1);break}}}}}return b1},has:function(b1){var b0,bZ=bG(b1,this),e=bZ.length;return this.filter(function(){for(b0=0;b0<e;b0++){if(bG.contains(this,bZ[b0])){return true}}})},not:function(e){return this.pushStack(aM(this,e,false),"not",e)},filter:function(e){return this.pushStack(aM(this,e,true),"filter",e)},is:function(e){return !!e&&(typeof e==="string"?y.test(e)?bG(e,this.context).index(this[0])>=0:bG.filter(e,this).length>0:this.filter(e).length>0)},closest:function(b2,b1){var b3,b0=0,e=this.length,bZ=[],b4=y.test(b2)||typeof b2!=="string"?bG(b2,b1||this.context):0;for(;b0<e;b0++){b3=this[b0];while(b3&&b3.ownerDocument&&b3!==b1&&b3.nodeType!==11){if(b4?b4.index(b3)>-1:bG.find.matchesSelector(b3,b2)){bZ.push(b3);break}b3=b3.parentNode}}bZ=bZ.length>1?bG.unique(bZ):bZ;return this.pushStack(bZ,"closest",b2)},index:function(e){if(!e){return(this[0]&&this[0].parentNode)?this.prevAll().length:-1}if(typeof e==="string"){return bG.inArray(this[0],bG(e))}return bG.inArray(e.jquery?e[0]:e,this)},add:function(e,bZ){var b1=typeof e==="string"?bG(e,bZ):bG.makeArray(e&&e.nodeType?[e]:e),b0=bG.merge(this.get(),b1);return this.pushStack(aR(b1[0])||aR(b0[0])?b0:bG.unique(b0))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}});bG.fn.andSelf=bG.fn.addBack;function aR(e){return !e||!e.parentNode||e.parentNode.nodeType===11}function aY(bZ,e){do{bZ=bZ[e]}while(bZ&&bZ.nodeType!==1);return bZ}bG.each({parent:function(bZ){var e=bZ.parentNode;return e&&e.nodeType!==11?e:null},parents:function(e){return bG.dir(e,"parentNode")},parentsUntil:function(bZ,e,b0){return bG.dir(bZ,"parentNode",b0)},next:function(e){return aY(e,"nextSibling")},prev:function(e){return aY(e,"previousSibling")},nextAll:function(e){return bG.dir(e,"nextSibling")},prevAll:function(e){return bG.dir(e,"previousSibling")},nextUntil:function(bZ,e,b0){return bG.dir(bZ,"nextSibling",b0)},prevUntil:function(bZ,e,b0){return bG.dir(bZ,"previousSibling",b0)},siblings:function(e){return bG.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return bG.sibling(e.firstChild)},contents:function(e){return bG.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:bG.merge([],e.childNodes)}},function(e,bZ){bG.fn[e]=function(b2,b0){var b1=bG.map(this,bZ,b2);if(!ag.test(e)){b0=b2}if(b0&&typeof b0==="string"){b1=bG.filter(b0,b1)}b1=this.length>1&&!bu[e]?bG.unique(b1):b1;if(this.length>1&&bq.test(e)){b1=b1.reverse()}return this.pushStack(b1,e,a4.call(arguments).join(","))}});bG.extend({filter:function(b0,e,bZ){if(bZ){b0=":not("+b0+")"}return e.length===1?bG.find.matchesSelector(e[0],b0)?[e[0]]:[]:bG.find.matches(b0,e)},dir:function(b0,bZ,b2){var e=[],b1=b0[bZ];while(b1&&b1.nodeType!==9&&(b2===aB||b1.nodeType!==1||!bG(b1).is(b2))){if(b1.nodeType===1){e.push(b1)}b1=b1[bZ]}return e},sibling:function(b0,bZ){var e=[];for(;b0;b0=b0.nextSibling){if(b0.nodeType===1&&b0!==bZ){e.push(b0)}}return e}});function aM(b1,b0,e){b0=b0||0;if(bG.isFunction(b0)){return bG.grep(b1,function(b3,b2){var b4=!!b0.call(b3,b2,b3);return b4===e})}else{if(b0.nodeType){return bG.grep(b1,function(b3,b2){return(b3===b0)===e})}else{if(typeof b0==="string"){var bZ=bG.grep(b1,function(b2){return b2.nodeType===1});if(al.test(b0)){return bG.filter(b0,bZ,!e)}else{b0=bG.filter(b0,bZ)}}}}return bG.grep(b1,function(b3,b2){return(bG.inArray(b3,b0)>=0)===e})}function A(e){var b0=c.split("|"),bZ=e.createDocumentFragment();if(bZ.createElement){while(b0.length){bZ.createElement(b0.pop())}}return bZ}var c="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",av=/ jQuery\d+="(?:null|\d+)"/g,bY=/^\s+/,ay=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,p=/<([\w:]+)/,bT=/<tbody/i,J=/<|&#?\w+;/,aj=/<(?:script|style|link)/i,ap=/<(?:script|object|embed|option|style)/i,K=new RegExp("<(?:"+c+")[\\s/>]","i"),aE=/^(?:checkbox|radio)$/,bR=/checked\s*(?:[^=]|=\s*.checked.)/i,bw=/\/(java|ecma)script/i,aH=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,T={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,"",""]},aQ=A(o),l=aQ.appendChild(o.createElement("div"));T.optgroup=T.option;T.tbody=T.tfoot=T.colgroup=T.caption=T.thead;T.th=T.td;if(!bG.support.htmlSerialize){T._default=[1,"X<div>","</div>"]}bG.fn.extend({text:function(e){return bG.access(this,function(bZ){return bZ===aB?bG.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(bZ))},null,e,arguments.length)},wrapAll:function(e){if(bG.isFunction(e)){return this.each(function(b0){bG(this).wrapAll(e.call(this,b0))})}if(this[0]){var bZ=bG(e,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){bZ.insertBefore(this[0])}bZ.map(function(){var b0=this;while(b0.firstChild&&b0.firstChild.nodeType===1){b0=b0.firstChild}return b0}).append(this)}return this},wrapInner:function(e){if(bG.isFunction(e)){return this.each(function(bZ){bG(this).wrapInner(e.call(this,bZ))})}return this.each(function(){var bZ=bG(this),b0=bZ.contents();if(b0.length){b0.wrapAll(e)}else{bZ.append(e)}})},wrap:function(e){var bZ=bG.isFunction(e);return this.each(function(b0){bG(this).wrapAll(bZ?e.call(this,b0):e)})},unwrap:function(){return this.parent().each(function(){if(!bG.nodeName(this,"body")){bG(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1||this.nodeType===11){this.appendChild(e)}})},prepend:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1||this.nodeType===11){this.insertBefore(e,this.firstChild)}})},before:function(){if(!aR(this[0])){return this.domManip(arguments,false,function(bZ){this.parentNode.insertBefore(bZ,this)})}if(arguments.length){var e=bG.clean(arguments);return this.pushStack(bG.merge(e,this),"before",this.selector)}},after:function(){if(!aR(this[0])){return this.domManip(arguments,false,function(bZ){this.parentNode.insertBefore(bZ,this.nextSibling)})}if(arguments.length){var e=bG.clean(arguments);return this.pushStack(bG.merge(this,e),"after",this.selector)}},remove:function(e,b1){var b0,bZ=0;for(;(b0=this[bZ])!=null;bZ++){if(!e||bG.filter(e,[b0]).length){if(!b1&&b0.nodeType===1){bG.cleanData(b0.getElementsByTagName("*"));bG.cleanData([b0])}if(b0.parentNode){b0.parentNode.removeChild(b0)}}}return this},empty:function(){var bZ,e=0;for(;(bZ=this[e])!=null;e++){if(bZ.nodeType===1){bG.cleanData(bZ.getElementsByTagName("*"))}while(bZ.firstChild){bZ.removeChild(bZ.firstChild)}}return this},clone:function(bZ,e){bZ=bZ==null?false:bZ;e=e==null?bZ:e;return this.map(function(){return bG.clone(this,bZ,e)})},html:function(e){return bG.access(this,function(b2){var b1=this[0]||{},b0=0,bZ=this.length;if(b2===aB){return b1.nodeType===1?b1.innerHTML.replace(av,""):aB}if(typeof b2==="string"&&!aj.test(b2)&&(bG.support.htmlSerialize||!K.test(b2))&&(bG.support.leadingWhitespace||!bY.test(b2))&&!T[(p.exec(b2)||["",""])[1].toLowerCase()]){b2=b2.replace(ay,"<$1></$2>");try{for(;b0<bZ;b0++){b1=this[b0]||{};if(b1.nodeType===1){bG.cleanData(b1.getElementsByTagName("*"));b1.innerHTML=b2}}b1=0}catch(b3){}}if(b1){this.empty().append(b2)}},null,e,arguments.length)},replaceWith:function(e){if(!aR(this[0])){if(bG.isFunction(e)){return this.each(function(b1){var b0=bG(this),bZ=b0.html();b0.replaceWith(e.call(this,b1,bZ))})}if(typeof e!=="string"){e=bG(e).detach()}return this.each(function(){var b0=this.nextSibling,bZ=this.parentNode;bG(this).remove();if(b0){bG(b0).before(e)}else{bG(bZ).append(e)}})}return this.length?this.pushStack(bG(bG.isFunction(e)?e():e),"replaceWith",e):this},detach:function(e){return this.remove(e,true)},domManip:function(b4,b8,b7){b4=[].concat.apply([],b4);var b0,b2,b3,b6,b1=0,b5=b4[0],bZ=[],e=this.length;if(!bG.support.checkClone&&e>1&&typeof b5==="string"&&bR.test(b5)){return this.each(function(){bG(this).domManip(b4,b8,b7)})}if(bG.isFunction(b5)){return this.each(function(ca){var b9=bG(this);b4[0]=b5.call(this,ca,b8?b9.html():aB);b9.domManip(b4,b8,b7)})}if(this[0]){b0=bG.buildFragment(b4,this,bZ);b3=b0.fragment;b2=b3.firstChild;if(b3.childNodes.length===1){b3=b2}if(b2){b8=b8&&bG.nodeName(b2,"tr");for(b6=b0.cacheable||e-1;b1<e;b1++){b7.call(b8&&bG.nodeName(this[b1],"table")?x(this[b1],"tbody"):this[b1],b1===b6?b3:bG.clone(b3,true,true))}}b3=b2=null;if(bZ.length){bG.each(bZ,function(b9,ca){if(ca.src){if(bG.ajax){bG.ajax({url:ca.src,type:"GET",dataType:"script",async:false,global:false,"throws":true})}else{bG.error("no ajax")}}else{bG.globalEval((ca.text||ca.textContent||ca.innerHTML||"").replace(aH,""))}if(ca.parentNode){ca.parentNode.removeChild(ca)}})}}return this}});function x(bZ,e){return bZ.getElementsByTagName(e)[0]||bZ.appendChild(bZ.ownerDocument.createElement(e))}function ao(b5,bZ){if(bZ.nodeType!==1||!bG.hasData(b5)){return}var b2,b1,e,b4=bG._data(b5),b3=bG._data(bZ,b4),b0=b4.events;if(b0){delete b3.handle;b3.events={};for(b2 in b0){for(b1=0,e=b0[b2].length;b1<e;b1++){bG.event.add(bZ,b2,b0[b2][b1])}}}if(b3.data){b3.data=bG.extend({},b3.data)}}function F(bZ,e){var b0;if(e.nodeType!==1){return}if(e.clearAttributes){e.clearAttributes()}if(e.mergeAttributes){e.mergeAttributes(bZ)}b0=e.nodeName.toLowerCase();if(b0==="object"){if(e.parentNode){e.outerHTML=bZ.outerHTML}if(bG.support.html5Clone&&(bZ.innerHTML&&!bG.trim(e.innerHTML))){e.innerHTML=bZ.innerHTML}}else{if(b0==="input"&&aE.test(bZ.type)){e.defaultChecked=e.checked=bZ.checked;if(e.value!==bZ.value){e.value=bZ.value}}else{if(b0==="option"){e.selected=bZ.defaultSelected}else{if(b0==="input"||b0==="textarea"){e.defaultValue=bZ.defaultValue}else{if(b0==="script"&&e.text!==bZ.text){e.text=bZ.text}}}}}e.removeAttribute(bG.expando)}bG.buildFragment=function(b1,b2,bZ){var b0,e,b3,b4=b1[0];b2=b2||o;b2=!b2.nodeType&&b2[0]||b2;b2=b2.ownerDocument||b2;if(b1.length===1&&typeof b4==="string"&&b4.length<512&&b2===o&&b4.charAt(0)==="<"&&!ap.test(b4)&&(bG.support.checkClone||!bR.test(b4))&&(bG.support.html5Clone||!K.test(b4))){e=true;b0=bG.fragments[b4];b3=b0!==aB}if(!b0){b0=b2.createDocumentFragment();bG.clean(b1,b2,b0,bZ);if(e){bG.fragments[b4]=b3&&b0}}return{fragment:b0,cacheable:e}};bG.fragments={};bG.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,bZ){bG.fn[e]=function(b0){var b2,b4=0,b3=[],b6=bG(b0),b1=b6.length,b5=this.length===1&&this[0].parentNode;if((b5==null||b5&&b5.nodeType===11&&b5.childNodes.length===1)&&b1===1){b6[bZ](this[0]);return this}else{for(;b4<b1;b4++){b2=(b4>0?this.clone(true):this).get();bG(b6[b4])[bZ](b2);b3=b3.concat(b2)}return this.pushStack(b3,e,b6.selector)}}});function m(e){if(typeof e.getElementsByTagName!=="undefined"){return e.getElementsByTagName("*")}else{if(typeof e.querySelectorAll!=="undefined"){return e.querySelectorAll("*")}else{return[]}}}function bS(e){if(aE.test(e.type)){e.defaultChecked=e.checked}}bG.extend({clone:function(b2,b4,b0){var e,bZ,b1,b3;if(bG.support.html5Clone||bG.isXMLDoc(b2)||!K.test("<"+b2.nodeName+">")){b3=b2.cloneNode(true)}else{l.innerHTML=b2.outerHTML;l.removeChild(b3=l.firstChild)}if((!bG.support.noCloneEvent||!bG.support.noCloneChecked)&&(b2.nodeType===1||b2.nodeType===11)&&!bG.isXMLDoc(b2)){F(b2,b3);e=m(b2);bZ=m(b3);for(b1=0;e[b1];++b1){if(bZ[b1]){F(e[b1],bZ[b1])}}}if(b4){ao(b2,b3);if(b0){e=m(b2);bZ=m(b3);for(b1=0;e[b1];++b1){ao(e[b1],bZ[b1])}}}e=bZ=null;return b3},clean:function(cb,b0,e,b1){var b8,b7,ca,cf,b4,ce,b5,b2,bZ,b9,cd,b6,b3=b0===o&&aQ,cc=[];if(!b0||typeof b0.createDocumentFragment==="undefined"){b0=o}for(b8=0;(ca=cb[b8])!=null;b8++){if(typeof ca==="number"){ca+=""}if(!ca){continue}if(typeof ca==="string"){if(!J.test(ca)){ca=b0.createTextNode(ca)}else{b3=b3||A(b0);b5=b0.createElement("div");b3.appendChild(b5);ca=ca.replace(ay,"<$1></$2>");cf=(p.exec(ca)||["",""])[1].toLowerCase();b4=T[cf]||T._default;ce=b4[0];b5.innerHTML=b4[1]+ca+b4[2];while(ce--){b5=b5.lastChild}if(!bG.support.tbody){b2=bT.test(ca);bZ=cf==="table"&&!b2?b5.firstChild&&b5.firstChild.childNodes:b4[1]==="<table>"&&!b2?b5.childNodes:[];for(b7=bZ.length-1;b7>=0;--b7){if(bG.nodeName(bZ[b7],"tbody")&&!bZ[b7].childNodes.length){bZ[b7].parentNode.removeChild(bZ[b7])}}}if(!bG.support.leadingWhitespace&&bY.test(ca)){b5.insertBefore(b0.createTextNode(bY.exec(ca)[0]),b5.firstChild)}ca=b5.childNodes;b5.parentNode.removeChild(b5)}}if(ca.nodeType){cc.push(ca)}else{bG.merge(cc,ca)}}if(b5){ca=b5=b3=null}if(!bG.support.appendChecked){for(b8=0;(ca=cc[b8])!=null;b8++){if(bG.nodeName(ca,"input")){bS(ca)}else{if(typeof ca.getElementsByTagName!=="undefined"){bG.grep(ca.getElementsByTagName("input"),bS)}}}}if(e){cd=function(cg){if(!cg.type||bw.test(cg.type)){return b1?b1.push(cg.parentNode?cg.parentNode.removeChild(cg):cg):e.appendChild(cg)}};for(b8=0;(ca=cc[b8])!=null;b8++){if(!(bG.nodeName(ca,"script")&&cd(ca))){e.appendChild(ca);if(typeof ca.getElementsByTagName!=="undefined"){b6=bG.grep(bG.merge([],ca.getElementsByTagName("script")),cd);cc.splice.apply(cc,[b8+1,0].concat(b6));b8+=b6.length}}}}return cc},cleanData:function(bZ,b7){var b2,b0,b1,b6,b3=0,b8=bG.expando,e=bG.cache,b4=bG.support.deleteExpando,b5=bG.event.special;for(;(b1=bZ[b3])!=null;b3++){if(b7||bG.acceptData(b1)){b0=b1[b8];b2=b0&&e[b0];if(b2){if(b2.events){for(b6 in b2.events){if(b5[b6]){bG.event.remove(b1,b6)}else{bG.removeEvent(b1,b6,b2.handle)}}}if(e[b0]){delete e[b0];if(b4){delete b1[b8]}else{if(b1.removeAttribute){b1.removeAttribute(b8)}else{b1[b8]=null}}bG.deletedIds.push(b0)}}}}}});(function(){var e,bZ;bG.uaMatch=function(b1){b1=b1.toLowerCase();var b0=/(chrome)[ \/]([\w.]+)/.exec(b1)||/(webkit)[ \/]([\w.]+)/.exec(b1)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(b1)||/(msie) ([\w.]+)/.exec(b1)||b1.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(b1)||[];return{browser:b0[1]||"",version:b0[2]||"0"}};e=bG.uaMatch(d.userAgent);bZ={};if(e.browser){bZ[e.browser]=true;bZ.version=e.version}if(bZ.chrome){bZ.webkit=true}else{if(bZ.webkit){bZ.safari=true}}bG.browser=bZ;bG.sub=function(){function b0(b3,b4){return new b0.fn.init(b3,b4)}bG.extend(true,b0,this);b0.superclass=this;b0.fn=b0.prototype=this();b0.fn.constructor=b0;b0.sub=this.sub;b0.fn.init=function b2(b3,b4){if(b4&&b4 instanceof bG&&!(b4 instanceof b0)){b4=b0(b4)}return bG.fn.init.call(this,b3,b4,b1)};b0.fn.init.prototype=b0.fn;var b1=b0(o);return b0}})();var E,az,aW,be=/alpha\([^)]*\)/i,aS=/opacity=([^)]*)/,bk=/^(top|right|bottom|left)$/,G=/^(none|table(?!-c[ea]).+)/,aZ=/^margin/,a8=new RegExp("^("+bx+")(.*)$","i"),W=new RegExp("^("+bx+")(?!px)[a-z%]+$","i"),S=new RegExp("^([-+])=("+bx+")","i"),bh={BODY:"block"},a9={position:"absolute",visibility:"hidden",display:"block"},bA={letterSpacing:0,fontWeight:400},bQ=["Top","Right","Bottom","Left"],ar=["Webkit","O","Moz","ms"],aJ=bG.fn.toggle;function b(b1,bZ){if(bZ in b1){return bZ}var b2=bZ.charAt(0).toUpperCase()+bZ.slice(1),e=bZ,b0=ar.length;while(b0--){bZ=ar[b0]+b2;if(bZ in b1){return bZ}}return e}function Q(bZ,e){bZ=e||bZ;return bG.css(bZ,"display")==="none"||!bG.contains(bZ.ownerDocument,bZ)}function s(b3,e){var b2,b4,bZ=[],b0=0,b1=b3.length;for(;b0<b1;b0++){b2=b3[b0];if(!b2.style){continue}bZ[b0]=bG._data(b2,"olddisplay");if(e){if(!bZ[b0]&&b2.style.display==="none"){b2.style.display=""}if(b2.style.display===""&&Q(b2)){bZ[b0]=bG._data(b2,"olddisplay",bC(b2.nodeName))}}else{b4=E(b2,"display");if(!bZ[b0]&&b4!=="none"){bG._data(b2,"olddisplay",b4)}}}for(b0=0;b0<b1;b0++){b2=b3[b0];if(!b2.style){continue}if(!e||b2.style.display==="none"||b2.style.display===""){b2.style.display=e?bZ[b0]||"":"none"}}return b3}bG.fn.extend({css:function(e,bZ){return bG.access(this,function(b1,b0,b2){return b2!==aB?bG.style(b1,b0,b2):bG.css(b1,b0)},e,bZ,arguments.length>1)},show:function(){return s(this,true)},hide:function(){return s(this)},toggle:function(b0,bZ){var e=typeof b0==="boolean";if(bG.isFunction(b0)&&bG.isFunction(bZ)){return aJ.apply(this,arguments)}return this.each(function(){if(e?b0:Q(this)){bG(this).show()}else{bG(this).hide()}})}});bG.extend({cssHooks:{opacity:{get:function(b0,bZ){if(bZ){var e=E(b0,"opacity");return e===""?"1":e}}}},cssNumber:{fillOpacity:true,fontWeight:true,lineHeight:true,opacity:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":bG.support.cssFloat?"cssFloat":"styleFloat"},style:function(b1,b0,b7,b2){if(!b1||b1.nodeType===3||b1.nodeType===8||!b1.style){return}var b5,b6,b8,b3=bG.camelCase(b0),bZ=b1.style;b0=bG.cssProps[b3]||(bG.cssProps[b3]=b(bZ,b3));b8=bG.cssHooks[b0]||bG.cssHooks[b3];if(b7!==aB){b6=typeof b7;if(b6==="string"&&(b5=S.exec(b7))){b7=(b5[1]+1)*b5[2]+parseFloat(bG.css(b1,b0));b6="number"}if(b7==null||b6==="number"&&isNaN(b7)){return}if(b6==="number"&&!bG.cssNumber[b3]){b7+="px"}if(!b8||!("set" in b8)||(b7=b8.set(b1,b7,b2))!==aB){try{bZ[b0]=b7}catch(b4){}}}else{if(b8&&"get" in b8&&(b5=b8.get(b1,false,b2))!==aB){return b5}return bZ[b0]}},css:function(b4,b2,b3,bZ){var b5,b1,e,b0=bG.camelCase(b2);b2=bG.cssProps[b0]||(bG.cssProps[b0]=b(b4.style,b0));e=bG.cssHooks[b2]||bG.cssHooks[b0];if(e&&"get" in e){b5=e.get(b4,true,bZ)}if(b5===aB){b5=E(b4,b2)}if(b5==="normal"&&b2 in bA){b5=bA[b2]}if(b3||bZ!==aB){b1=parseFloat(b5);return b3||bG.isNumeric(b1)?b1||0:b5}return b5},swap:function(b2,b1,b3){var b0,bZ,e={};for(bZ in b1){e[bZ]=b2.style[bZ];b2.style[bZ]=b1[bZ]}b0=b3.call(b2);for(bZ in b1){b2.style[bZ]=e[bZ]}return b0}});if(a2.getComputedStyle){E=function(b5,bZ){var e,b2,b1,b4,b3=a2.getComputedStyle(b5,null),b0=b5.style;if(b3){e=b3.getPropertyValue(bZ)||b3[bZ];if(e===""&&!bG.contains(b5.ownerDocument,b5)){e=bG.style(b5,bZ)}if(W.test(e)&&aZ.test(bZ)){b2=b0.width;b1=b0.minWidth;b4=b0.maxWidth;b0.minWidth=b0.maxWidth=b0.width=e;e=b3.width;b0.width=b2;b0.minWidth=b1;b0.maxWidth=b4}}return e}}else{if(o.documentElement.currentStyle){E=function(b2,b0){var b3,e,bZ=b2.currentStyle&&b2.currentStyle[b0],b1=b2.style;if(bZ==null&&b1&&b1[b0]){bZ=b1[b0]}if(W.test(bZ)&&!bk.test(b0)){b3=b1.left;e=b2.runtimeStyle&&b2.runtimeStyle.left;if(e){b2.runtimeStyle.left=b2.currentStyle.left}b1.left=b0==="fontSize"?"1em":bZ;bZ=b1.pixelLeft+"px";b1.left=b3;if(e){b2.runtimeStyle.left=e}}return bZ===""?"auto":bZ}}}function aG(e,b0,b1){var bZ=a8.exec(b0);return bZ?Math.max(0,bZ[1]-(b1||0))+(bZ[2]||"px"):b0}function at(b1,bZ,e,b3){var b0=e===(b3?"border":"content")?4:bZ==="width"?1:0,b2=0;for(;b0<4;b0+=2){if(e==="margin"){b2+=bG.css(b1,e+bQ[b0],true)}if(b3){if(e==="content"){b2-=parseFloat(E(b1,"padding"+bQ[b0]))||0}if(e!=="margin"){b2-=parseFloat(E(b1,"border"+bQ[b0]+"Width"))||0}}else{b2+=parseFloat(E(b1,"padding"+bQ[b0]))||0;if(e!=="padding"){b2+=parseFloat(E(b1,"border"+bQ[b0]+"Width"))||0}}}return b2}function u(b1,bZ,e){var b2=bZ==="width"?b1.offsetWidth:b1.offsetHeight,b0=true,b3=bG.support.boxSizing&&bG.css(b1,"boxSizing")==="border-box";if(b2<=0||b2==null){b2=E(b1,bZ);if(b2<0||b2==null){b2=b1.style[bZ]}if(W.test(b2)){return b2}b0=b3&&(bG.support.boxSizingReliable||b2===b1.style[bZ]);b2=parseFloat(b2)||0}return(b2+at(b1,bZ,e||(b3?"border":"content"),b0))+"px"}function bC(b0){if(bh[b0]){return bh[b0]}var e=bG("<"+b0+">").appendTo(o.body),bZ=e.css("display");e.remove();if(bZ==="none"||bZ===""){az=o.body.appendChild(az||bG.extend(o.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!aW||!az.createElement){aW=(az.contentWindow||az.contentDocument).document;aW.write("<!doctype html><html><body>");aW.close()}e=aW.body.appendChild(aW.createElement(b0));bZ=E(e,"display");o.body.removeChild(az)}bh[b0]=bZ;return bZ}bG.each(["height","width"],function(bZ,e){bG.cssHooks[e]={get:function(b2,b1,b0){if(b1){if(b2.offsetWidth===0&&G.test(E(b2,"display"))){return bG.swap(b2,a9,function(){return u(b2,e,b0)})}else{return u(b2,e,b0)}}},set:function(b1,b2,b0){return aG(b1,b2,b0?at(b1,e,b0,bG.support.boxSizing&&bG.css(b1,"boxSizing")==="border-box"):0)}}});if(!bG.support.opacity){bG.cssHooks.opacity={get:function(bZ,e){return aS.test((e&&bZ.currentStyle?bZ.currentStyle.filter:bZ.style.filter)||"")?(0.01*parseFloat(RegExp.$1))+"":e?"1":""},set:function(b2,b3){var b1=b2.style,bZ=b2.currentStyle,e=bG.isNumeric(b3)?"alpha(opacity="+b3*100+")":"",b0=bZ&&bZ.filter||b1.filter||"";b1.zoom=1;if(b3>=1&&bG.trim(b0.replace(be,""))===""&&b1.removeAttribute){b1.removeAttribute("filter");if(bZ&&!bZ.filter){return}}b1.filter=be.test(b0)?b0.replace(be,e):b0+" "+e}}}bG(function(){if(!bG.support.reliableMarginRight){bG.cssHooks.marginRight={get:function(bZ,e){return bG.swap(bZ,{display:"inline-block"},function(){if(e){return E(bZ,"marginRight")}})}}}if(!bG.support.pixelPosition&&bG.fn.position){bG.each(["top","left"],function(e,bZ){bG.cssHooks[bZ]={get:function(b2,b1){if(b1){var b0=E(b2,bZ);return W.test(b0)?bG(b2).position()[bZ]+"px":b0}}}})}});if(bG.expr&&bG.expr.filters){bG.expr.filters.hidden=function(e){return(e.offsetWidth===0&&e.offsetHeight===0)||(!bG.support.reliableHiddenOffsets&&((e.style&&e.style.display)||E(e,"display"))==="none")};bG.expr.filters.visible=function(e){return !bG.expr.filters.hidden(e)}}bG.each({margin:"",padding:"",border:"Width"},function(e,bZ){bG.cssHooks[e+bZ]={expand:function(b2){var b1,b3=typeof b2==="string"?b2.split(" "):[b2],b0={};for(b1=0;b1<4;b1++){b0[e+bQ[b1]+bZ]=b3[b1]||b3[b1-2]||b3[0]}return b0}};if(!aZ.test(e)){bG.cssHooks[e+bZ].set=aG}});var bs=/%20/g,aP=/\[\]$/,U=/\r?\n/g,bz=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,aD=/^(?:select|textarea)/i;bG.fn.extend({serialize:function(){return bG.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?bG.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||aD.test(this.nodeName)||bz.test(this.type))}).map(function(e,bZ){var b0=bG(this).val();return b0==null?null:bG.isArray(b0)?bG.map(b0,function(b2,b1){return{name:bZ.name,value:b2.replace(U,"\r\n")}}):{name:bZ.name,value:b0.replace(U,"\r\n")}}).get()}});bG.param=function(e,b0){var b1,bZ=[],b2=function(b3,b4){b4=bG.isFunction(b4)?b4():(b4==null?"":b4);bZ[bZ.length]=encodeURIComponent(b3)+"="+encodeURIComponent(b4)};if(b0===aB){b0=bG.ajaxSettings&&bG.ajaxSettings.traditional}if(bG.isArray(e)||(e.jquery&&!bG.isPlainObject(e))){bG.each(e,function(){b2(this.name,this.value)})}else{for(b1 in e){k(b1,e[b1],b0,b2)}}return bZ.join("&").replace(bs,"+")};function k(b0,b2,bZ,b1){var e;if(bG.isArray(b2)){bG.each(b2,function(b4,b3){if(bZ||aP.test(b0)){b1(b0,b3)}else{k(b0+"["+(typeof b3==="object"?b4:"")+"]",b3,bZ,b1)}})}else{if(!bZ&&bG.type(b2)==="object"){for(e in b2){k(b0+"["+e+"]",b2[e],bZ,b1)}}else{b1(b0,b2)}}}var bX,Y,an=/#.*$/,ad=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,B=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,r=/^(?:GET|HEAD)$/,aC=/^\/\//,bN=/\?/,g=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,P=/([?&])_=[^&]*/,aT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,bW=bG.fn.load,v={},a6={},aX=["*/"]+["*"];try{Y=aI.href}catch(bd){Y=o.createElement("a");Y.href="";Y=Y.href}bX=aT.exec(Y.toLowerCase())||[];function bI(e){return function(b2,b4){if(typeof b2!=="string"){b4=b2;b2="*"}var bZ,b5,b6,b1=b2.toLowerCase().split(aV),b0=0,b3=b1.length;if(bG.isFunction(b4)){for(;b0<b3;b0++){bZ=b1[b0];b6=/^\+/.test(bZ);if(b6){bZ=bZ.substr(1)||"*"}b5=e[bZ]=e[bZ]||[];b5[b6?"unshift":"push"](b4)}}}}function q(bZ,b8,b3,b6,b5,b1){b5=b5||b8.dataTypes[0];b1=b1||{};b1[b5]=true;var b7,b4=bZ[b5],b0=0,e=b4?b4.length:0,b2=(bZ===v);for(;b0<e&&(b2||!b7);b0++){b7=b4[b0](b8,b3,b6);if(typeof b7==="string"){if(!b2||b1[b7]){b7=aB}else{b8.dataTypes.unshift(b7);b7=q(bZ,b8,b3,b6,b7,b1)}}}if((b2||!b7)&&!b1["*"]){b7=q(bZ,b8,b3,b6,"*",b1)}return b7}function t(b0,b1){var bZ,e,b2=bG.ajaxSettings.flatOptions||{};for(bZ in b1){if(b1[bZ]!==aB){(b2[bZ]?b0:(e||(e={})))[bZ]=b1[bZ]}}if(e){bG.extend(true,b0,e)}}bG.fn.load=function(b1,b4,b5){if(typeof b1!=="string"&&bW){return bW.apply(this,arguments)}if(!this.length){return this}var e,b2,b0,bZ=this,b3=b1.indexOf(" ");if(b3>=0){e=b1.slice(b3,b1.length);b1=b1.slice(0,b3)}if(bG.isFunction(b4)){b5=b4;b4=aB}else{if(b4&&typeof b4==="object"){b2="POST"}}bG.ajax({url:b1,type:b2,dataType:"html",data:b4,complete:function(b7,b6){if(b5){bZ.each(b5,b0||[b7.responseText,b6,b7])}}}).done(function(b6){b0=arguments;bZ.html(e?bG("<div>").append(b6.replace(g,"")).find(e):b6)});return this};bG.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,bZ){bG.fn[bZ]=function(b0){return this.on(bZ,b0)}});bG.each(["get","post"],function(e,bZ){bG[bZ]=function(b0,b2,b3,b1){if(bG.isFunction(b2)){b1=b1||b3;b3=b2;b2=aB}return bG.ajax({type:bZ,url:b0,data:b2,success:b3,dataType:b1})}});bG.extend({getScript:function(e,bZ){return bG.get(e,aB,bZ,"script")},getJSON:function(e,bZ,b0){return bG.get(e,bZ,b0,"json")},ajaxSetup:function(bZ,e){if(e){t(bZ,bG.ajaxSettings)}else{e=bZ;bZ=bG.ajaxSettings}t(bZ,e);return bZ},ajaxSettings:{url:Y,isLocal:B.test(bX[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":aX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a2.String,"text html":true,"text json":bG.parseJSON,"text xml":bG.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:bI(v),ajaxTransport:bI(a6),ajax:function(b4,b1){if(typeof b4==="object"){b1=b4;b4=aB}b1=b1||{};var b7,cl,b2,cg,b9,cd,b0,cf,b8=bG.ajaxSetup({},b1),cn=b8.context||b8,cb=cn!==b8&&(cn.nodeType||cn instanceof bG)?bG(cn):bG.event,cm=bG.Deferred(),ci=bG.Callbacks("once memory"),b5=b8.statusCode||{},cc={},cj={},b3=0,b6="canceled",ce={readyState:0,setRequestHeader:function(co,cp){if(!b3){var e=co.toLowerCase();co=cj[e]=cj[e]||co;cc[co]=cp}return this},getAllResponseHeaders:function(){return b3===2?cl:null},getResponseHeader:function(co){var e;if(b3===2){if(!b2){b2={};while((e=ad.exec(cl))){b2[e[1].toLowerCase()]=e[2]}}e=b2[co.toLowerCase()]}return e===aB?null:e},overrideMimeType:function(e){if(!b3){b8.mimeType=e}return this},abort:function(e){e=e||b6;if(cg){cg.abort(e)}ca(0,e);return this}};function ca(cs,co,ct,cq){var e,cw,cu,cr,cv,cp=co;if(b3===2){return}b3=2;if(b9){clearTimeout(b9)}cg=aB;cl=cq||"";ce.readyState=cs>0?4:0;if(ct){cr=h(b8,ce,ct)}if(cs>=200&&cs<300||cs===304){if(b8.ifModified){cv=ce.getResponseHeader("Last-Modified");if(cv){bG.lastModified[b7]=cv}cv=ce.getResponseHeader("Etag");if(cv){bG.etag[b7]=cv}}if(cs===304){cp="notmodified";e=true}else{e=ae(b8,cr);cp=e.state;cw=e.data;cu=e.error;e=!cu}}else{cu=cp;if(!cp||cs){cp="error";if(cs<0){cs=0}}}ce.status=cs;ce.statusText=(co||cp)+"";if(e){cm.resolveWith(cn,[cw,cp,ce])}else{cm.rejectWith(cn,[ce,cp,cu])}ce.statusCode(b5);b5=aB;if(b0){cb.trigger("ajax"+(e?"Success":"Error"),[ce,b8,e?cw:cu])}ci.fireWith(cn,[ce,cp]);if(b0){cb.trigger("ajaxComplete",[ce,b8]);if(!(--bG.active)){bG.event.trigger("ajaxStop")}}}cm.promise(ce);ce.success=ce.done;ce.error=ce.fail;ce.complete=ci.add;ce.statusCode=function(co){if(co){var e;if(b3<2){for(e in co){b5[e]=[b5[e],co[e]]}}else{e=co[ce.status];ce.always(e)}}return this};b8.url=((b4||b8.url)+"").replace(an,"").replace(aC,bX[1]+"//");b8.dataTypes=bG.trim(b8.dataType||"*").toLowerCase().split(aV);if(b8.crossDomain==null){cd=aT.exec(b8.url.toLowerCase());b8.crossDomain=!!(cd&&(cd[1]!==bX[1]||cd[2]!==bX[2]||(cd[3]||(cd[1]==="http:"?80:443))!=(bX[3]||(bX[1]==="http:"?80:443))))}if(b8.data&&b8.processData&&typeof b8.data!=="string"){b8.data=bG.param(b8.data,b8.traditional)}q(v,b8,b1,ce);if(b3===2){return ce}b0=b8.global;b8.type=b8.type.toUpperCase();b8.hasContent=!r.test(b8.type);if(b0&&bG.active++===0){bG.event.trigger("ajaxStart")}if(!b8.hasContent){if(b8.data){b8.url+=(bN.test(b8.url)?"&":"?")+b8.data;delete b8.data}b7=b8.url;if(b8.cache===false){var bZ=bG.now(),ck=b8.url.replace(P,"$1_="+bZ);b8.url=ck+((ck===b8.url)?(bN.test(b8.url)?"&":"?")+"_="+bZ:"")}}if(b8.data&&b8.hasContent&&b8.contentType!==false||b1.contentType){ce.setRequestHeader("Content-Type",b8.contentType)}if(b8.ifModified){b7=b7||b8.url;if(bG.lastModified[b7]){ce.setRequestHeader("If-Modified-Since",bG.lastModified[b7])}if(bG.etag[b7]){ce.setRequestHeader("If-None-Match",bG.etag[b7])}}ce.setRequestHeader("Accept",b8.dataTypes[0]&&b8.accepts[b8.dataTypes[0]]?b8.accepts[b8.dataTypes[0]]+(b8.dataTypes[0]!=="*"?", "+aX+"; q=0.01":""):b8.accepts["*"]);for(cf in b8.headers){ce.setRequestHeader(cf,b8.headers[cf])}if(b8.beforeSend&&(b8.beforeSend.call(cn,ce,b8)===false||b3===2)){return ce.abort()}b6="abort";for(cf in {success:1,error:1,complete:1}){ce[cf](b8[cf])}cg=q(a6,b8,b1,ce);if(!cg){ca(-1,"No Transport")}else{ce.readyState=1;if(b0){cb.trigger("ajaxSend",[ce,b8])}if(b8.async&&b8.timeout>0){b9=setTimeout(function(){ce.abort("timeout")},b8.timeout)}try{b3=1;cg.send(cc,ca)}catch(ch){if(b3<2){ca(-1,ch)}else{throw ch}}}return ce},active:0,lastModified:{},etag:{}});function h(b7,b6,b3){var b2,b4,b1,e,bZ=b7.contents,b5=b7.dataTypes,b0=b7.responseFields;for(b4 in b0){if(b4 in b3){b6[b0[b4]]=b3[b4]}}while(b5[0]==="*"){b5.shift();if(b2===aB){b2=b7.mimeType||b6.getResponseHeader("content-type")}}if(b2){for(b4 in bZ){if(bZ[b4]&&bZ[b4].test(b2)){b5.unshift(b4);break}}}if(b5[0] in b3){b1=b5[0]}else{for(b4 in b3){if(!b5[0]||b7.converters[b4+" "+b5[0]]){b1=b4;break}if(!e){e=b4}}b1=b1||e}if(b1){if(b1!==b5[0]){b5.unshift(b1)}return b3[b1]}}function ae(b9,b1){var b7,bZ,b5,b3,b6=b9.dataTypes.slice(),b0=b6[0],b8={},b2=0;if(b9.dataFilter){b1=b9.dataFilter(b1,b9.dataType)}if(b6[1]){for(b7 in b9.converters){b8[b7.toLowerCase()]=b9.converters[b7]}}for(;(b5=b6[++b2]);){if(b5!=="*"){if(b0!=="*"&&b0!==b5){b7=b8[b0+" "+b5]||b8["* "+b5];if(!b7){for(bZ in b8){b3=bZ.split(" ");if(b3[1]===b5){b7=b8[b0+" "+b3[0]]||b8["* "+b3[0]];if(b7){if(b7===true){b7=b8[bZ]}else{if(b8[bZ]!==true){b5=b3[0];b6.splice(b2--,0,b5)}}break}}}}if(b7!==true){if(b7&&b9["throws"]){b1=b7(b1)}else{try{b1=b7(b1)}catch(b4){return{state:"parsererror",error:b7?b4:"No conversion from "+b0+" to "+b5}}}}}b0=b5}}return{state:"success",data:b1}}var bp=[],aw=/\?/,a5=/(=)\?(?=&|$)|\?\?/,bl=bG.now();bG.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=bp.pop()||(bG.expando+"_"+(bl++));this[e]=true;return e}});bG.ajaxPrefilter("json jsonp",function(b8,b3,b7){var b6,e,b5,b1=b8.data,bZ=b8.url,b0=b8.jsonp!==false,b4=b0&&a5.test(bZ),b2=b0&&!b4&&typeof b1==="string"&&!(b8.contentType||"").indexOf("application/x-www-form-urlencoded")&&a5.test(b1);if(b8.dataTypes[0]==="jsonp"||b4||b2){b6=b8.jsonpCallback=bG.isFunction(b8.jsonpCallback)?b8.jsonpCallback():b8.jsonpCallback;e=a2[b6];if(b4){b8.url=bZ.replace(a5,"$1"+b6)}else{if(b2){b8.data=b1.replace(a5,"$1"+b6)}else{if(b0){b8.url+=(aw.test(bZ)?"&":"?")+b8.jsonp+"="+b6}}}b8.converters["script json"]=function(){if(!b5){bG.error(b6+" was not called")}return b5[0]};b8.dataTypes[0]="json";a2[b6]=function(){b5=arguments};b7.always(function(){a2[b6]=e;if(b8[b6]){b8.jsonpCallback=b3.jsonpCallback;bp.push(b6)}if(b5&&bG.isFunction(e)){e(b5[0])}b5=e=aB});return"script"}});bG.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){bG.globalEval(e);return e}}});bG.ajaxPrefilter("script",function(e){if(e.cache===aB){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});bG.ajaxTransport("script",function(b0){if(b0.crossDomain){var e,bZ=o.head||o.getElementsByTagName("head")[0]||o.documentElement;return{send:function(b1,b2){e=o.createElement("script");e.async="async";if(b0.scriptCharset){e.charset=b0.scriptCharset}e.src=b0.url;e.onload=e.onreadystatechange=function(b4,b3){if(b3||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;if(bZ&&e.parentNode){bZ.removeChild(e)}e=aB;if(!b3){b2(200,"success")}}};bZ.insertBefore(e,bZ.firstChild)},abort:function(){if(e){e.onload(0,1)}}}}});var ah,aN=a2.ActiveXObject?function(){for(var e in ah){ah[e](0,1)}}:false,au=0;function bB(){try{return new a2.XMLHttpRequest()}catch(bZ){}}function bb(){try{return new a2.ActiveXObject("Microsoft.XMLHTTP")}catch(bZ){}}bG.ajaxSettings.xhr=a2.ActiveXObject?function(){return !this.isLocal&&bB()||bb()}:bB;(function(e){bG.extend(bG.support,{ajax:!!e,cors:!!e&&("withCredentials" in e)})})(bG.ajaxSettings.xhr());if(bG.support.ajax){bG.ajaxTransport(function(e){if(!e.crossDomain||bG.support.cors){var bZ;return{send:function(b5,b0){var b3,b2,b4=e.xhr();if(e.username){b4.open(e.type,e.url,e.async,e.username,e.password)}else{b4.open(e.type,e.url,e.async)}if(e.xhrFields){for(b2 in e.xhrFields){b4[b2]=e.xhrFields[b2]}}if(e.mimeType&&b4.overrideMimeType){b4.overrideMimeType(e.mimeType)}if(!e.crossDomain&&!b5["X-Requested-With"]){b5["X-Requested-With"]="XMLHttpRequest"}try{for(b2 in b5){b4.setRequestHeader(b2,b5[b2])}}catch(b1){}b4.send((e.hasContent&&e.data)||null);bZ=function(ce,b8){var b9,b7,b6,cc,cb;try{if(bZ&&(b8||b4.readyState===4)){bZ=aB;if(b3){b4.onreadystatechange=bG.noop;if(aN){delete ah[b3]}}if(b8){if(b4.readyState!==4){b4.abort()}}else{b9=b4.status;b6=b4.getAllResponseHeaders();cc={};cb=b4.responseXML;if(cb&&cb.documentElement){cc.xml=cb}try{cc.text=b4.responseText}catch(cd){}try{b7=b4.statusText}catch(cd){b7=""}if(!b9&&e.isLocal&&!e.crossDomain){b9=cc.text?200:404}else{if(b9===1223){b9=204}}}}}catch(ca){if(!b8){b0(-1,ca)}}if(cc){b0(b9,b7,cc,b6)}};if(!e.async){bZ()}else{if(b4.readyState===4){setTimeout(bZ,0)}else{b3=++au;if(aN){if(!ah){ah={};bG(a2).unload(aN)}ah[b3]=bZ}b4.onreadystatechange=bZ}}},abort:function(){if(bZ){bZ(0,1)}}}}})}var L,ab,bO=/^(?:toggle|show|hide)$/,bH=new RegExp("^(?:([-+])=|)("+bx+")([a-z%]*)$","i"),bM=/queueHooks$/,ax=[i],a1={"*":[function(e,b5){var b1,b6,b7=this.createTween(e,b5),b2=bH.exec(b5),b3=b7.cur(),bZ=+b3||0,b0=1,b4=20;if(b2){b1=+b2[2];b6=b2[3]||(bG.cssNumber[e]?"":"px");if(b6!=="px"&&bZ){bZ=bG.css(b7.elem,e,true)||b1||1;do{b0=b0||".5";bZ=bZ/b0;bG.style(b7.elem,e,bZ+b6)}while(b0!==(b0=b7.cur()/b3)&&b0!==1&&--b4)}b7.unit=b6;b7.start=bZ;b7.end=b2[1]?bZ+(b2[1]+1)*b1:b1}return b7}]};function bj(){setTimeout(function(){L=aB},0);return(L=bG.now())}function bc(bZ,e){bG.each(e,function(b4,b2){var b3=(a1[b4]||[]).concat(a1["*"]),b0=0,b1=b3.length;for(;b0<b1;b0++){if(b3[b0].call(bZ,b4,b2)){return}}})}function f(b0,b4,b7){var b8,b3=0,e=0,bZ=ax.length,b6=bG.Deferred().always(function(){delete b2.elem}),b2=function(){var ce=L||bj(),cb=Math.max(0,b1.startTime+b1.duration-ce),b9=cb/b1.duration||0,cd=1-b9,ca=0,cc=b1.tweens.length;for(;ca<cc;ca++){b1.tweens[ca].run(cd)}b6.notifyWith(b0,[b1,cd,cb]);if(cd<1&&cc){return cb}else{b6.resolveWith(b0,[b1]);return false}},b1=b6.promise({elem:b0,props:bG.extend({},b4),opts:bG.extend(true,{specialEasing:{}},b7),originalProperties:b4,originalOptions:b7,startTime:L||bj(),duration:b7.duration,tweens:[],createTween:function(cc,b9,cb){var ca=bG.Tween(b0,b1.opts,cc,b9,b1.opts.specialEasing[cc]||b1.opts.easing);b1.tweens.push(ca);return ca},stop:function(ca){var b9=0,cb=ca?b1.tweens.length:0;for(;b9<cb;b9++){b1.tweens[b9].run(1)}if(ca){b6.resolveWith(b0,[b1,ca])}else{b6.rejectWith(b0,[b1,ca])}return this}}),b5=b1.props;ak(b5,b1.opts.specialEasing);for(;b3<bZ;b3++){b8=ax[b3].call(b1,b0,b5,b1.opts);if(b8){return b8}}bc(b1,b5);if(bG.isFunction(b1.opts.start)){b1.opts.start.call(b0,b1)}bG.fx.timer(bG.extend(b2,{anim:b1,queue:b1.opts.queue,elem:b0}));return b1.progress(b1.opts.progress).done(b1.opts.done,b1.opts.complete).fail(b1.opts.fail).always(b1.opts.always)}function ak(b1,b3){var b0,bZ,b4,b2,e;for(b0 in b1){bZ=bG.camelCase(b0);b4=b3[bZ];b2=b1[b0];if(bG.isArray(b2)){b4=b2[1];b2=b1[b0]=b2[0]}if(b0!==bZ){b1[bZ]=b2;delete b1[b0]}e=bG.cssHooks[bZ];if(e&&"expand" in e){b2=e.expand(b2);delete b1[bZ];for(b0 in b2){if(!(b0 in b1)){b1[b0]=b2[b0];b3[b0]=b4}}}else{b3[bZ]=b4}}}bG.Animation=bG.extend(f,{tweener:function(bZ,b2){if(bG.isFunction(bZ)){b2=bZ;bZ=["*"]}else{bZ=bZ.split(" ")}var b1,e=0,b0=bZ.length;for(;e<b0;e++){b1=bZ[e];a1[b1]=a1[b1]||[];a1[b1].unshift(b2)}},prefilter:function(bZ,e){if(e){ax.unshift(bZ)}else{ax.push(bZ)}}});function i(b2,b8,e){var b7,b0,ca,b1,ce,b4,cd,cc,cb,b3=this,bZ=b2.style,b9={},b6=[],b5=b2.nodeType&&Q(b2);if(!e.queue){cc=bG._queueHooks(b2,"fx");if(cc.unqueued==null){cc.unqueued=0;cb=cc.empty.fire;cc.empty.fire=function(){if(!cc.unqueued){cb()}}}cc.unqueued++;b3.always(function(){b3.always(function(){cc.unqueued--;if(!bG.queue(b2,"fx").length){cc.empty.fire()}})})}if(b2.nodeType===1&&("height" in b8||"width" in b8)){e.overflow=[bZ.overflow,bZ.overflowX,bZ.overflowY];if(bG.css(b2,"display")==="inline"&&bG.css(b2,"float")==="none"){if(!bG.support.inlineBlockNeedsLayout||bC(b2.nodeName)==="inline"){bZ.display="inline-block"}else{bZ.zoom=1}}}if(e.overflow){bZ.overflow="hidden";if(!bG.support.shrinkWrapBlocks){b3.done(function(){bZ.overflow=e.overflow[0];bZ.overflowX=e.overflow[1];bZ.overflowY=e.overflow[2]})}}for(b7 in b8){ca=b8[b7];if(bO.exec(ca)){delete b8[b7];b4=b4||ca==="toggle";if(ca===(b5?"hide":"show")){continue}b6.push(b7)}}b1=b6.length;if(b1){ce=bG._data(b2,"fxshow")||bG._data(b2,"fxshow",{});if("hidden" in ce){b5=ce.hidden}if(b4){ce.hidden=!b5}if(b5){bG(b2).show()}else{b3.done(function(){bG(b2).hide()})}b3.done(function(){var cf;bG.removeData(b2,"fxshow",true);for(cf in b9){bG.style(b2,cf,b9[cf])}});for(b7=0;b7<b1;b7++){b0=b6[b7];cd=b3.createTween(b0,b5?ce[b0]:0);b9[b0]=ce[b0]||bG.style(b2,b0);if(!(b0 in ce)){ce[b0]=cd.start;if(b5){cd.end=cd.start;cd.start=b0==="width"||b0==="height"?1:0}}}}}function H(b0,bZ,b2,e,b1){return new H.prototype.init(b0,bZ,b2,e,b1)}bG.Tween=H;H.prototype={constructor:H,init:function(b1,bZ,b3,e,b2,b0){this.elem=b1;this.prop=b3;this.easing=b2||"swing";this.options=bZ;this.start=this.now=this.cur();this.end=e;this.unit=b0||(bG.cssNumber[b3]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(b0){var bZ,e=H.propHooks[this.prop];if(this.options.duration){this.pos=bZ=bG.easing[this.easing](b0,this.options.duration*b0,0,1,this.options.duration)}else{this.pos=bZ=b0}this.now=(this.end-this.start)*bZ+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(e&&e.set){e.set(this)}else{H.propHooks._default.set(this)}return this}};H.prototype.init.prototype=H.prototype;H.propHooks={_default:{get:function(bZ){var e;if(bZ.elem[bZ.prop]!=null&&(!bZ.elem.style||bZ.elem.style[bZ.prop]==null)){return bZ.elem[bZ.prop]}e=bG.css(bZ.elem,bZ.prop,false,"");return !e||e==="auto"?0:e},set:function(e){if(bG.fx.step[e.prop]){bG.fx.step[e.prop](e)}else{if(e.elem.style&&(e.elem.style[bG.cssProps[e.prop]]!=null||bG.cssHooks[e.prop])){bG.style(e.elem,e.prop,e.now+e.unit)}else{e.elem[e.prop]=e.now}}}}};H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){if(e.elem.nodeType&&e.elem.parentNode){e.elem[e.prop]=e.now}}};bG.each(["toggle","show","hide"],function(bZ,e){var b0=bG.fn[e];bG.fn[e]=function(b1,b3,b2){return b1==null||typeof b1==="boolean"||(!bZ&&bG.isFunction(b1)&&bG.isFunction(b3))?b0.apply(this,arguments):this.animate(bF(e,true),b1,b3,b2)}});bG.fn.extend({fadeTo:function(e,b1,b0,bZ){return this.filter(Q).css("opacity",0).show().end().animate({opacity:b1},e,b0,bZ)},animate:function(b4,b1,b3,b2){var b0=bG.isEmptyObject(b4),e=bG.speed(b1,b3,b2),bZ=function(){var b5=f(this,bG.extend({},b4),e);if(b0){b5.stop(true)}};return b0||e.queue===false?this.each(bZ):this.queue(e.queue,bZ)},stop:function(b0,bZ,e){var b1=function(b2){var b3=b2.stop;delete b2.stop;b3(e)};if(typeof b0!=="string"){e=bZ;bZ=b0;b0=aB}if(bZ&&b0!==false){this.queue(b0||"fx",[])}return this.each(function(){var b5=true,b2=b0!=null&&b0+"queueHooks",b4=bG.timers,b3=bG._data(this);if(b2){if(b3[b2]&&b3[b2].stop){b1(b3[b2])}}else{for(b2 in b3){if(b3[b2]&&b3[b2].stop&&bM.test(b2)){b1(b3[b2])}}}for(b2=b4.length;b2--;){if(b4[b2].elem===this&&(b0==null||b4[b2].queue===b0)){b4[b2].anim.stop(e);b5=false;b4.splice(b2,1)}}if(b5||!e){bG.dequeue(this,b0)}})}});function bF(b0,b2){var b1,e={height:b0},bZ=0;b2=b2?1:0;for(;bZ<4;bZ+=2-b2){b1=bQ[bZ];e["margin"+b1]=e["padding"+b1]=b0}if(b2){e.opacity=e.width=b0}return e}bG.each({slideDown:bF("show"),slideUp:bF("hide"),slideToggle:bF("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,bZ){bG.fn[e]=function(b0,b2,b1){return this.animate(bZ,b0,b2,b1)}});bG.speed=function(b0,b1,bZ){var e=b0&&typeof b0==="object"?bG.extend({},b0):{complete:bZ||!bZ&&b1||bG.isFunction(b0)&&b0,duration:b0,easing:bZ&&b1||b1&&!bG.isFunction(b1)&&b1};e.duration=bG.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in bG.fx.speeds?bG.fx.speeds[e.duration]:bG.fx.speeds._default;if(e.queue==null||e.queue===true){e.queue="fx"}e.old=e.complete;e.complete=function(){if(bG.isFunction(e.old)){e.old.call(this)}if(e.queue){bG.dequeue(this,e.queue)}};return e};bG.easing={linear:function(e){return e},swing:function(e){return 0.5-Math.cos(e*Math.PI)/2}};bG.timers=[];bG.fx=H.prototype.init;bG.fx.tick=function(){var b0,bZ=bG.timers,e=0;L=bG.now();for(;e<bZ.length;e++){b0=bZ[e];if(!b0()&&bZ[e]===b0){bZ.splice(e--,1)}}if(!bZ.length){bG.fx.stop()}L=aB};bG.fx.timer=function(e){if(e()&&bG.timers.push(e)&&!ab){ab=setInterval(bG.fx.tick,bG.fx.interval)}};bG.fx.interval=13;bG.fx.stop=function(){clearInterval(ab);ab=null};bG.fx.speeds={slow:600,fast:200,_default:400};bG.fx.step={};if(bG.expr&&bG.expr.filters){bG.expr.filters.animated=function(e){return bG.grep(bG.timers,function(bZ){return e===bZ.elem}).length}}var bm=/^(?:body|html)$/i;bG.fn.offset=function(b8){if(arguments.length){return b8===aB?this:this.each(function(b9){bG.offset.setOffset(this,b8,b9)})}var bZ,b4,b5,b2,b6,e,b1,b3={top:0,left:0},b0=this[0],b7=b0&&b0.ownerDocument;if(!b7){return}if((b4=b7.body)===b0){return bG.offset.bodyOffset(b0)}bZ=b7.documentElement;if(!bG.contains(bZ,b0)){return b3}if(typeof b0.getBoundingClientRect!=="undefined"){b3=b0.getBoundingClientRect()}b5=bn(b7);b2=bZ.clientTop||b4.clientTop||0;b6=bZ.clientLeft||b4.clientLeft||0;e=b5.pageYOffset||bZ.scrollTop;b1=b5.pageXOffset||bZ.scrollLeft;return{top:b3.top+e-b2,left:b3.left+b1-b6}};bG.offset={bodyOffset:function(e){var b0=e.offsetTop,bZ=e.offsetLeft;if(bG.support.doesNotIncludeMarginInBodyOffset){b0+=parseFloat(bG.css(e,"marginTop"))||0;bZ+=parseFloat(bG.css(e,"marginLeft"))||0}return{top:b0,left:bZ}},setOffset:function(b1,ca,b4){var b5=bG.css(b1,"position");if(b5==="static"){b1.style.position="relative"}var b3=bG(b1),bZ=b3.offset(),e=bG.css(b1,"top"),b8=bG.css(b1,"left"),b9=(b5==="absolute"||b5==="fixed")&&bG.inArray("auto",[e,b8])>-1,b7={},b6={},b0,b2;if(b9){b6=b3.position();b0=b6.top;b2=b6.left}else{b0=parseFloat(e)||0;b2=parseFloat(b8)||0}if(bG.isFunction(ca)){ca=ca.call(b1,b4,bZ)}if(ca.top!=null){b7.top=(ca.top-bZ.top)+b0}if(ca.left!=null){b7.left=(ca.left-bZ.left)+b2}if("using" in ca){ca.using.call(b1,b7)}else{b3.css(b7)}}};bG.fn.extend({position:function(){if(!this[0]){return}var b0=this[0],bZ=this.offsetParent(),b1=this.offset(),e=bm.test(bZ[0].nodeName)?{top:0,left:0}:bZ.offset();b1.top-=parseFloat(bG.css(b0,"marginTop"))||0;b1.left-=parseFloat(bG.css(b0,"marginLeft"))||0;e.top+=parseFloat(bG.css(bZ[0],"borderTopWidth"))||0;e.left+=parseFloat(bG.css(bZ[0],"borderLeftWidth"))||0;return{top:b1.top-e.top,left:b1.left-e.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.body;while(e&&(!bm.test(e.nodeName)&&bG.css(e,"position")==="static")){e=e.offsetParent}return e||o.body})}});bG.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b0,bZ){var e=/Y/.test(bZ);bG.fn[b0]=function(b1){return bG.access(this,function(b2,b5,b4){var b3=bn(b2);if(b4===aB){return b3?(bZ in b3)?b3[bZ]:b3.document.documentElement[b5]:b2[b5]}if(b3){b3.scrollTo(!e?b4:bG(b3).scrollLeft(),e?b4:bG(b3).scrollTop())}else{b2[b5]=b4}},b0,b1,arguments.length,null)}});function bn(e){return bG.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}bG.each({Height:"height",Width:"width"},function(e,bZ){bG.each({padding:"inner"+e,content:bZ,"":"outer"+e},function(b0,b1){bG.fn[b1]=function(b5,b4){var b3=arguments.length&&(b0||typeof b5!=="boolean"),b2=b0||(b5===true||b4===true?"margin":"border");return bG.access(this,function(b7,b6,b8){var b9;if(bG.isWindow(b7)){return b7.document.documentElement["client"+e]}if(b7.nodeType===9){b9=b7.documentElement;return Math.max(b7.body["scroll"+e],b9["scroll"+e],b7.body["offset"+e],b9["offset"+e],b9["client"+e])}return b8===aB?bG.css(b7,b6,b8,b2):bG.style(b7,b6,b8,b2)},bZ,b3?b5:aB,b3,null)}})});a2.jQuery=a2.$=bG;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return bG})}})(window); /* THIS FILE HAS BEEN MODIFIED BY ATLASSIAN. See https://ecosystem.atlassian.net/browse/AUI-1535 for details. Modified lines are marked below, search "ATLASSIAN" */ (function(i){var e="0.3.4",j="hasOwnProperty",b=/[\.\/]/,a="*",g=function(){},f=function(m,l){return m-l},d,h,k={n:{}},c=function(m,C){var v=k,s=h,w=Array.prototype.slice.call(arguments,2),y=c.listeners(m),x=0,u=false,p,o=[],t={},q=[],n=d,A=[];d=m;h=0;for(var r=0,B=y.length;r<B;r++){if("zIndex" in y[r]){o.push(y[r].zIndex);if(y[r].zIndex<0){t[y[r].zIndex]=y[r]}}}o.sort(f);while(o[x]<0){p=t[o[x++]];q.push(p.apply(C,w));if(h){h=s;return q}}for(r=0;r<B;r++){p=y[r];if("zIndex" in p){if(p.zIndex==o[x]){q.push(p.apply(C,w));if(h){break}do{x++;p=t[o[x]];p&&q.push(p.apply(C,w));if(h){break}}while(p)}else{t[p.zIndex]=p}}else{q.push(p.apply(C,w));if(h){break}}}h=s;d=n;return q.length?q:null};c.listeners=function(l){var t=l.split(b),r=k,x,s,m,p,w,o,q,u,v=[r],n=[];for(p=0,w=t.length;p<w;p++){u=[];for(o=0,q=v.length;o<q;o++){r=v[o].n;s=[r[t[p]],r[a]];m=2;while(m--){x=s[m];if(x){u.push(x);n=n.concat(x.f||[])}}}v=u}return n};c.on=function(l,o){var q=l.split(b),p=k;for(var m=0,n=q.length;m<n;m++){p=p.n;!p[q[m]]&&(p[q[m]]={n:{}});p=p[q[m]]}p.f=p.f||[];for(m=0,n=p.f.length;m<n;m++){if(p.f[m]==o){return g}}p.f.push(o);return function(r){if(+r==+r){o.zIndex=+r}}};c.stop=function(){h=1};c.nt=function(l){if(l){return new RegExp("(?:\\.|\\/|^)"+l+"(?:\\.|\\/|$)").test(d)}return d};c.off=c.unbind=function(m,r){var t=m.split(b),s,v,n,p,w,o,q,u=[k];for(p=0,w=t.length;p<w;p++){for(o=0;o<u.length;o+=n.length-2){n=[o,1];s=u[o].n;if(t[p]!=a){if(s[t[p]]){n.push(s[t[p]])}}else{for(v in s){if(s[j](v)){n.push(s[v])}}}u.splice.apply(u,n)}}for(p=0,w=u.length;p<w;p++){s=u[p];while(s.n){if(r){if(s.f){for(o=0,q=s.f.length;o<q;o++){if(s.f[o]==r){s.f.splice(o,1);break}}!s.f.length&&delete s.f}for(v in s.n){if(s.n[j](v)&&s.n[v].f){var l=s.n[v].f;for(o=0,q=l.length;o<q;o++){if(l[o]==r){l.splice(o,1);break}}!l.length&&delete s.n[v].f}}}else{delete s.f;for(v in s.n){if(s.n[j](v)&&s.n[v].f){delete s.n[v].f}}}s=s.n}}};c.once=function(l,m){var n=function(){var o=m.apply(this,arguments);c.unbind(l,n);return o};return c.on(l,n)};c.version=e;c.toString=function(){return"You are running Eve "+e};(typeof module!="undefined"&&module.exports)?(module.exports=c):(typeof define!="undefined"?(define("eve",[],function(){return c})):(i.eve=c))})(this);(function(){function aR(g){if(aR.is(g,"function")){return ao?g():eve.on("raphael.DOMload",g)}else{if(aR.is(g,bd)){return aR._engine.create[bG](aR,g.splice(0,3+aR.is(g[0],aL))).add(g)}else{var b=Array.prototype.slice.call(arguments,0);if(aR.is(b[b.length-1],"function")){var d=b.pop();return ao?d.call(aR._engine.create[bG](aR,b)):eve.on("raphael.DOMload",function(){d.call(aR._engine.create[bG](aR,b))})}else{return aR._engine.create[bG](aR,arguments)}}}}aR.version="2.1.0";aR.eve=eve;var ao,a=/[, ]+/,bw={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},br=/\{(\d+)\}/g,bJ="prototype",ak="hasOwnProperty",aA={doc:document,win:window},s={was:Object.prototype[ak].call(aA.win,"Raphael"),is:aA.win.Raphael},bF=function(){this.ca=this.customAttributes={}},a4,bo="appendChild",bG="apply",bE="concat",Z="createTouch" in aA.doc,aX="",aQ=" ",bH=String,F="split",Q="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[F](aQ),bx={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},bK=bH.prototype.toLowerCase,au=Math,m=au.max,bm=au.min,aw=au.abs,bp=au.pow,aV=au.PI,aL="number",aj="string",bd="array",a5="toString",a9="fill",a1=Object.prototype.toString,bz={},j="push",f=aR._ISURL=/^url\(['"]?([^\)]+?)['"]?\)$/i,A=/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,av={"NaN":1,"Infinity":1,"-Infinity":1},c=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,ah=au.round,z="setAttribute",an=parseFloat,U=parseInt,bt=bH.prototype.toUpperCase,r=aR._availableAttrs={"arrow-end":"none","arrow-start":"none",blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/","letter-spacing":0,opacity:1,path:"M0,0",r:0,rx:0,ry:0,src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",transform:"",width:0,x:0,y:0},ar=aR._availableAnimAttrs={blur:aL,"clip-rect":"csv",cx:aL,cy:aL,fill:"colour","fill-opacity":aL,"font-size":aL,height:aL,opacity:aL,path:"path",r:aL,rx:aL,ry:aL,stroke:"colour","stroke-opacity":aL,"stroke-width":aL,transform:"transform",width:aL,x:aL,y:aL},ac=/[\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]/g,bi=/[\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]*,[\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]*/,n={hs:1,rg:1},bg=/,?([achlmqrstvxz]),?/gi,a0=/([achlmrqstvz])[\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,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\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]*,?[\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]*)+)/ig,ai=/([rstm])[\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,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\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]*,?[\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]*)+)/ig,aP=/(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\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]*,?[\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]*/ig,aW=aR._radial_gradient=/^r(?:\(([^,]+?)[\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]*,[\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]*([^\)]+?)\))?/,aU={},bq=function(g,d){return g.key-d.key},u=function(g,d){return an(g)-an(d)},I=function(){},bB=function(b){return b},az=aR._rectPath=function(b,E,d,g,i){if(i){return[["M",b+i,E],["l",d-i*2,0],["a",i,i,0,0,1,i,i],["l",0,g-i*2],["a",i,i,0,0,1,-i,i],["l",i*2-d,0],["a",i,i,0,0,1,-i,-i],["l",0,i*2-g],["a",i,i,0,0,1,i,-i],["z"]]}return[["M",b,E],["l",d,0],["l",0,g],["l",-d,0],["z"]]},K=function(b,i,g,d){if(d==null){d=g}return[["M",b,i],["m",0,-d],["a",g,d,0,1,1,0,2*d],["a",g,d,0,1,1,0,-2*d],["z"]]},N=aR._getPath={path:function(b){return b.attr("path")},circle:function(d){var b=d.attrs;return K(b.cx,b.cy,b.r)},ellipse:function(d){var b=d.attrs;return K(b.cx,b.cy,b.rx,b.ry)},rect:function(d){var b=d.attrs;return az(b.x,b.y,b.width,b.height,b.r)},image:function(d){var b=d.attrs;return az(b.x,b.y,b.width,b.height)},text:function(b){var d=b._getBBox();return az(d.x,d.y,d.width,d.height)}},L=aR.mapPath=function(bN,S){if(!S){return bN}var bL,R,g,b,bM,E,d;bN=W(bN);for(g=0,bM=bN.length;g<bM;g++){d=bN[g];for(b=1,E=d.length;b<E;b+=2){bL=S.x(d[b],d[b+1]);R=S.y(d[b],d[b+1]);d[b]=bL;d[b+1]=R}}return bN};aR._g=aA;aR.type=(aA.win.SVGAngle||aA.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML");if(aR.type=="VML"){var aE=aA.doc.createElement("div"),aH;aE.innerHTML='<v:shape adj="1"/>';aH=aE.firstChild;aH.style.behavior="url(#default#VML)";if(!(aH&&typeof aH.adj=="object")){return(aR.type=aX)}aE=null}aR.svg=!(aR.vml=aR.type=="VML");aR._Paper=bF;aR.fn=a4=bF.prototype=aR.prototype;aR._id=0;aR._oid=0;aR.is=function(d,b){b=bK.call(b);if(b=="finite"){return !av[ak](+d)}if(b=="array"){return d instanceof Array}return(b=="null"&&d===null)||(b==typeof d&&d!==null)||(b=="object"&&d===Object(d))||(b=="array"&&Array.isArray&&Array.isArray(d))||a1.call(d).slice(8,-1).toLowerCase()==b};function X(g){if(Object(g)!==g){return g}var d=new g.constructor;for(var b in g){if(g[ak](b)){d[b]=X(g[b])}}return d}aR.angle=function(E,S,g,R,d,i){if(d==null){var b=E-g,bL=S-R;if(!b&&!bL){return 0}return(180+au.atan2(-bL,-b)*180/aV+360)%360}else{return aR.angle(E,S,d,i)-aR.angle(g,R,d,i)}};aR.rad=function(b){return b%360*aV/180};aR.deg=function(b){return b*180/aV%360};aR.snapTo=function(d,E,b){b=aR.is(b,"finite")?b:10;if(aR.is(d,bd)){var g=d.length;while(g--){if(aw(d[g]-E)<=b){return d[g]}}}else{d=+d;var R=E%d;if(R<b){return E-R}if(R>d-b){return E-R+d}}return E};var h=aR.createUUID=(function(b,d){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(b,d).toUpperCase()}})(/[xy]/g,function(g){var d=au.random()*16|0,b=g=="x"?d:(d&3|8);return b.toString(16)});aR.setWindow=function(b){eve("raphael.setWindow",aR,aA.win,b);aA.win=b;aA.doc=aA.win.document;if(aR._engine.initWin){aR._engine.initWin(aA.win)}};var bf=function(g){if(aR.vml){var b=/^\s+|\s+$/g;var R;try{var S=new ActiveXObject("htmlfile");S.write("<body>");S.close();R=S.body}catch(bL){R=createPopup().document.body}var d=R.createTextRange();bf=aG(function(i){try{R.style.color=bH(i).replace(b,aX);var bM=d.queryCommandValue("ForeColor");bM=((bM&255)<<16)|(bM&65280)|((bM&16711680)>>>16);return"#"+("000000"+bM.toString(16)).slice(-6)}catch(bN){return"none"}})}else{var E=aA.doc.createElement("i");E.title="Rapha\xebl Colour Picker";E.style.display="none";aA.doc.body.appendChild(E);bf=aG(function(i){E.style.color=i;return aA.doc.defaultView.getComputedStyle(E,aX).getPropertyValue("color")})}return bf(g)},aI=function(){return"hsb("+[this.h,this.s,this.b]+")"},M=function(){return"hsl("+[this.h,this.s,this.l]+")"},x=function(){return this.hex},aY=function(R,E,d){if(E==null&&aR.is(R,"object")&&"r" in R&&"g" in R&&"b" in R){d=R.b;E=R.g;R=R.r}if(E==null&&aR.is(R,aj)){var i=aR.getRGB(R);R=i.r;E=i.g;d=i.b}if(R>1||E>1||d>1){R/=255;E/=255;d/=255}return[R,E,d]},a2=function(R,E,d,S){R*=255;E*=255;d*=255;var i={r:R,g:E,b:d,hex:aR.rgb(R,E,d),toString:x};aR.is(S,"finite")&&(i.opacity=S);return i};aR.color=function(b){var d;if(aR.is(b,"object")&&"h" in b&&"s" in b&&"b" in b){d=aR.hsb2rgb(b);b.r=d.r;b.g=d.g;b.b=d.b;b.hex=d.hex}else{if(aR.is(b,"object")&&"h" in b&&"s" in b&&"l" in b){d=aR.hsl2rgb(b);b.r=d.r;b.g=d.g;b.b=d.b;b.hex=d.hex}else{if(aR.is(b,"string")){b=aR.getRGB(b)}if(aR.is(b,"object")&&"r" in b&&"g" in b&&"b" in b){d=aR.rgb2hsl(b);b.h=d.h;b.s=d.s;b.l=d.l;d=aR.rgb2hsb(b);b.v=d.b}else{b={hex:"none"};b.r=b.g=b.b=b.h=b.s=b.v=b.l=-1}}}b.toString=x;return b};aR.hsb2rgb=function(S,bN,bL,i){if(this.is(S,"object")&&"h" in S&&"s" in S&&"b" in S){bL=S.b;bN=S.s;S=S.h;i=S.o}S*=360;var E,bM,d,g,b;S=(S%360)/60;b=bL*bN;g=b*(1-aw(S%2-1));E=bM=d=bL-b;S=~~S;E+=[b,g,0,0,g,b][S];bM+=[g,b,b,g,0,0][S];d+=[0,0,g,b,b,g][S];return a2(E,bM,d,i)};aR.hsl2rgb=function(bL,bN,E,i){if(this.is(bL,"object")&&"h" in bL&&"s" in bL&&"l" in bL){E=bL.l;bN=bL.s;bL=bL.h}if(bL>1||bN>1||E>1){bL/=360;bN/=100;E/=100}bL*=360;var S,bM,d,g,b;bL=(bL%360)/60;b=2*bN*(E<0.5?E:1-E);g=b*(1-aw(bL%2-1));S=bM=d=E-b/2;bL=~~bL;S+=[b,g,0,0,g,b][bL];bM+=[g,b,b,g,0,0][bL];d+=[0,0,g,b,b,g][bL];return a2(S,bM,d,i)};aR.rgb2hsb=function(bM,bL,d){d=aY(bM,bL,d);bM=d[0];bL=d[1];d=d[2];var R,E,i,bN;i=m(bM,bL,d);bN=i-bm(bM,bL,d);R=(bN==0?null:i==bM?(bL-d)/bN:i==bL?(d-bM)/bN+2:(bM-bL)/bN+4);R=((R+360)%6)*60/360;E=bN==0?0:bN/i;return{h:R,s:E,b:i,toString:aI}};aR.rgb2hsl=function(d,bL,bO){bO=aY(d,bL,bO);d=bO[0];bL=bO[1];bO=bO[2];var bP,R,bN,bM,E,i;bM=m(d,bL,bO);E=bm(d,bL,bO);i=bM-E;bP=(i==0?null:bM==d?(bL-bO)/i:bM==bL?(bO-d)/i+2:(d-bL)/i+4);bP=((bP+360)%6)*60/360;bN=(bM+E)/2;R=(i==0?0:bN<0.5?i/(2*bN):i/(2-2*bN));return{h:bP,s:R,l:bN,toString:M}};aR._path2string=function(){return this.join(",").replace(bg,"$1")};function bk(E,g){for(var b=0,d=E.length;b<d;b++){if(E[b]===g){return E.push(E.splice(b,1)[0])}}}function aG(i,d,b){function g(){var E=Array.prototype.slice.call(arguments,0),S=E.join("\u2400"),R=g.cache=g.cache||{},bL=g.count=g.count||[];if(R[ak](S)){bk(bL,S);return b?b(R[S]):R[S]}bL.length>=1000&&delete R[bL.shift()];bL.push(S);R[S]=i[bG](d,E);return b?b(R[S]):R[S]}return g}var bv=aR._preload=function(g,d){var b=aA.doc.createElement("img");b.style.cssText="position:absolute;left:-9999em;top:-9999em";b.onload=function(){d.call(this);this.onload=null;aA.doc.body.removeChild(this)};b.onerror=function(){aA.doc.body.removeChild(this)};aA.doc.body.appendChild(b);b.src=g};function aq(){return this.hex}aR.getRGB=aG(function(b){if(!b||!!((b=bH(b)).indexOf("-")+1)){return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:aq}}if(b=="none"){return{r:-1,g:-1,b:-1,hex:"none",toString:aq}}!(n[ak](b.toLowerCase().substring(0,2))||b.charAt()=="#")&&(b=bf(b));var E,d,g,S,i,bM,bL,R=b.match(A);if(R){if(R[2]){S=U(R[2].substring(5),16);g=U(R[2].substring(3,5),16);d=U(R[2].substring(1,3),16)}if(R[3]){S=U((bM=R[3].charAt(3))+bM,16);g=U((bM=R[3].charAt(2))+bM,16);d=U((bM=R[3].charAt(1))+bM,16)}if(R[4]){bL=R[4][F](bi);d=an(bL[0]);bL[0].slice(-1)=="%"&&(d*=2.55);g=an(bL[1]);bL[1].slice(-1)=="%"&&(g*=2.55);S=an(bL[2]);bL[2].slice(-1)=="%"&&(S*=2.55);R[1].toLowerCase().slice(0,4)=="rgba"&&(i=an(bL[3]));bL[3]&&bL[3].slice(-1)=="%"&&(i/=100)}if(R[5]){bL=R[5][F](bi);d=an(bL[0]);bL[0].slice(-1)=="%"&&(d*=2.55);g=an(bL[1]);bL[1].slice(-1)=="%"&&(g*=2.55);S=an(bL[2]);bL[2].slice(-1)=="%"&&(S*=2.55);(bL[0].slice(-3)=="deg"||bL[0].slice(-1)=="\xb0")&&(d/=360);R[1].toLowerCase().slice(0,4)=="hsba"&&(i=an(bL[3]));bL[3]&&bL[3].slice(-1)=="%"&&(i/=100);return aR.hsb2rgb(d,g,S,i)}if(R[6]){bL=R[6][F](bi);d=an(bL[0]);bL[0].slice(-1)=="%"&&(d*=2.55);g=an(bL[1]);bL[1].slice(-1)=="%"&&(g*=2.55);S=an(bL[2]);bL[2].slice(-1)=="%"&&(S*=2.55);(bL[0].slice(-3)=="deg"||bL[0].slice(-1)=="\xb0")&&(d/=360);R[1].toLowerCase().slice(0,4)=="hsla"&&(i=an(bL[3]));bL[3]&&bL[3].slice(-1)=="%"&&(i/=100);return aR.hsl2rgb(d,g,S,i)}R={r:d,g:g,b:S,toString:aq};R.hex="#"+(16777216|S|(g<<8)|(d<<16)).toString(16).slice(1);aR.is(i,"finite")&&(R.opacity=i);return R}return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:aq}},aR);aR.hsb=aG(function(i,g,d){return aR.hsb2rgb(i,g,d).hex});aR.hsl=aG(function(g,d,b){return aR.hsl2rgb(g,d,b).hex});aR.rgb=aG(function(E,i,d){return"#"+(16777216|d|(i<<8)|(E<<16)).toString(16).slice(1)});aR.getColor=function(d){var g=this.getColor.start=this.getColor.start||{h:0,s:1,b:d||0.75},b=this.hsb2rgb(g.h,g.s,g.b);g.h+=0.075;if(g.h>1){g.h=0;g.s-=0.2;g.s<=0&&(this.getColor.start={h:0,s:1,b:g.b})}return b.hex};aR.getColor.reset=function(){delete this.start};function bb(E,bL){var S=[];for(var g=0,b=E.length;b-2*!bL>g;g+=2){var R=[{x:+E[g-2],y:+E[g-1]},{x:+E[g],y:+E[g+1]},{x:+E[g+2],y:+E[g+3]},{x:+E[g+4],y:+E[g+5]}];if(bL){if(!g){R[0]={x:+E[b-2],y:+E[b-1]}}else{if(b-4==g){R[3]={x:+E[0],y:+E[1]}}else{if(b-2==g){R[2]={x:+E[0],y:+E[1]};R[3]={x:+E[2],y:+E[3]}}}}}else{if(b-4==g){R[3]=R[2]}else{if(!g){R[0]={x:+E[g],y:+E[g+1]}}}}S.push(["C",(-R[0].x+6*R[1].x+R[2].x)/6,(-R[0].y+6*R[1].y+R[2].y)/6,(R[1].x+6*R[2].x-R[3].x)/6,(R[1].y+6*R[2].y-R[3].y)/6,R[2].x,R[2].y])}return S}aR.parsePathString=function(b){if(!b){return null}var g=Y(b);if(g.arr){return aZ(g.arr)}var i={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},d=[];if(aR.is(b,bd)&&aR.is(b[0],bd)){d=aZ(b)}if(!d.length){bH(b).replace(a0,function(R,E,bM){var bL=[],S=E.toLowerCase();bM.replace(aP,function(bO,bN){bN&&bL.push(+bN)});if(S=="m"&&bL.length>2){d.push([E][bE](bL.splice(0,2)));S="l";E=E=="m"?"l":"L"}if(S=="r"){d.push([E][bE](bL))}else{while(bL.length>=i[S]){d.push([E][bE](bL.splice(0,i[S])));if(!i[S]){break}}}})}d.toString=aR._path2string;g.arr=aZ(d);return d};aR.parseTransformString=aG(function(d){if(!d){return null}var g={r:3,s:4,t:2,m:6},b=[];if(aR.is(d,bd)&&aR.is(d[0],bd)){b=aZ(d)}if(!b.length){bH(d).replace(ai,function(E,i,bL){var S=[],R=bK.call(i);bL.replace(aP,function(bN,bM){bM&&S.push(+bM)});b.push([i][bE](S))})}b.toString=aR._path2string;return b});var Y=function(d){var b=Y.ps=Y.ps||{};if(b[d]){b[d].sleep=100}else{b[d]={sleep:100}}setTimeout(function(){for(var g in b){if(b[ak](g)&&g!=d){b[g].sleep--;!b[g].sleep&&delete b[g]}}});return b[d]};aR.findDotsAtSegment=function(d,b,b2,b0,S,E,bN,bL,bV){var bS=1-bV,bX=bp(bS,3),bY=bp(bS,2),bP=bV*bV,bM=bP*bV,bR=bX*d+bY*3*bV*b2+bS*3*bV*bV*S+bM*bN,bO=bX*b+bY*3*bV*b0+bS*3*bV*bV*E+bM*bL,bW=d+2*bV*(b2-d)+bP*(S-2*b2+d),bU=b+2*bV*(b0-b)+bP*(E-2*b0+b),b1=b2+2*bV*(S-b2)+bP*(bN-2*S+b2),bZ=b0+2*bV*(E-b0)+bP*(bL-2*E+b0),bT=bS*d+bV*b2,bQ=bS*b+bV*b0,i=bS*S+bV*bN,g=bS*E+bV*bL,R=(90-au.atan2(bW-b1,bU-bZ)*180/aV);(bW>b1||bU<bZ)&&(R+=180);return{x:bR,y:bO,m:{x:bW,y:bU},n:{x:b1,y:bZ},start:{x:bT,y:bQ},end:{x:i,y:g},alpha:R}};aR.bezierBBox=function(d,b,i,g,bM,S,R,E){if(!aR.is(d,"array")){d=[d,b,i,g,bM,S,R,E]}var bL=ba.apply(null,d);return{x:bL.min.x,y:bL.min.y,x2:bL.max.x,y2:bL.max.y,width:bL.max.x-bL.min.x,height:bL.max.y-bL.min.y}};aR.isPointInsideBBox=function(d,b,g){return b>=d.x&&b<=d.x2&&g>=d.y&&g<=d.y2};aR.isBBoxIntersect=function(g,d){var b=aR.isPointInsideBBox;return b(d,g.x,g.y)||b(d,g.x2,g.y)||b(d,g.x,g.y2)||b(d,g.x2,g.y2)||b(g,d.x,d.y)||b(g,d.x2,d.y)||b(g,d.x,d.y2)||b(g,d.x2,d.y2)||(g.x<d.x2&&g.x>d.x||d.x<g.x2&&d.x>g.x)&&(g.y<d.y2&&g.y>d.y||d.y<g.y2&&d.y>g.y)};function bj(b,S,R,E,i){var g=-3*S+9*R-9*E+3*i,d=b*g+6*S-12*R+6*E;return b*d-3*S+3*R}function q(bW,R,bV,g,bU,d,bR,b,bO){if(bO==null){bO=1}bO=bO>1?1:bO<0?0:bO;var bP=bO/2,bQ=12,bL=[-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816],bT=[0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472],E=0;for(var bS=0;bS<bQ;bS++){var bM=bP*bL[bS]+bP,bN=bj(bM,bW,bV,bU,bR),bX=bj(bM,R,g,d,b),S=bN*bN+bX*bX;E+=bT[bS]*au.sqrt(S)}return bP*E}function C(g,bP,d,bO,b,bM,bR,bL,bN){if(bN<0||q(g,bP,d,bO,b,bM,bR,bL)<bN){return}var bQ=1,i=bQ/2,R=bQ-i,E,S=0.01;E=q(g,bP,d,bO,b,bM,bR,bL,R);while(aw(E-bN)>S){i/=2;R+=(E<bN?1:-1)*i;E=q(g,bP,d,bO,b,bM,bR,bL,R)}return R}function O(i,bQ,g,bO,b,bN,bS,bM){if(m(i,g)<bm(b,bS)||bm(i,g)>m(b,bS)||m(bQ,bO)<bm(bN,bM)||bm(bQ,bO)>m(bN,bM)){return}var bL=(i*bO-bQ*g)*(b-bS)-(i-g)*(b*bM-bN*bS),S=(i*bO-bQ*g)*(bN-bM)-(bQ-bO)*(b*bM-bN*bS),E=(i-g)*(bN-bM)-(bQ-bO)*(b-bS);if(!E){return}var bR=bL/E,bP=S/E,R=+bR.toFixed(2),d=+bP.toFixed(2);if(R<+bm(i,g).toFixed(2)||R>+m(i,g).toFixed(2)||R<+bm(b,bS).toFixed(2)||R>+m(b,bS).toFixed(2)||d<+bm(bQ,bO).toFixed(2)||d>+m(bQ,bO).toFixed(2)||d<+bm(bN,bM).toFixed(2)||d>+m(bN,bM).toFixed(2)){return}return{x:bR,y:bP}}function ay(d,b){return af(d,b)}function t(d,b){return af(d,b,1)}function af(b2,b1,b0){var E=aR.bezierBBox(b2),d=aR.bezierBBox(b1);if(!aR.isBBoxIntersect(E,d)){return b0?0:[]}var bV=q.apply(0,b2),bU=q.apply(0,b1),bM=~~(bV/5),bL=~~(bU/5),bS=[],bR=[],g={},b3=b0?0:[];for(var bX=0;bX<bM+1;bX++){var bT=aR.findDotsAtSegment.apply(aR,b2.concat(bX/bM));bS.push({x:bT.x,y:bT.y,t:bX/bM})}for(bX=0;bX<bL+1;bX++){bT=aR.findDotsAtSegment.apply(aR,b1.concat(bX/bL));bR.push({x:bT.x,y:bT.y,t:bX/bL})}for(bX=0;bX<bM;bX++){for(var bW=0;bW<bL;bW++){var bZ=bS[bX],b=bS[bX+1],bY=bR[bW],S=bR[bW+1],bQ=aw(b.x-bZ.x)<0.001?"y":"x",bP=aw(S.x-bY.x)<0.001?"y":"x",R=O(bZ.x,bZ.y,b.x,b.y,bY.x,bY.y,S.x,S.y);if(R){if(g[R.x.toFixed(4)]==R.y.toFixed(4)){continue}g[R.x.toFixed(4)]=R.y.toFixed(4);var bO=bZ.t+aw((R[bQ]-bZ[bQ])/(b[bQ]-bZ[bQ]))*(b.t-bZ.t),bN=bY.t+aw((R[bP]-bY[bP])/(S[bP]-bY[bP]))*(S.t-bY.t);if(bO>=0&&bO<=1&&bN>=0&&bN<=1){if(b0){b3++}else{b3.push({x:R.x,y:R.y,t1:bO,t2:bN})}}}}}return b3}aR.pathIntersection=function(d,b){return D(d,b)};aR.pathIntersectionNumber=function(d,b){return D(d,b,1)};function D(g,b,bW){g=aR._path2curve(g);b=aR._path2curve(b);var bU,S,bT,E,bR,bL,d,bO,b0,bZ,b1=bW?0:[];for(var bS=0,bM=g.length;bS<bM;bS++){var bY=g[bS];if(bY[0]=="M"){bU=bR=bY[1];S=bL=bY[2]}else{if(bY[0]=="C"){b0=[bU,S].concat(bY.slice(1));bU=b0[6];S=b0[7]}else{b0=[bU,S,bU,S,bR,bL,bR,bL];bU=bR;S=bL}for(var bQ=0,bV=b.length;bQ<bV;bQ++){var bX=b[bQ];if(bX[0]=="M"){bT=d=bX[1];E=bO=bX[2]}else{if(bX[0]=="C"){bZ=[bT,E].concat(bX.slice(1));bT=bZ[6];E=bZ[7]}else{bZ=[bT,E,bT,E,d,bO,d,bO];bT=d;E=bO}var bN=af(b0,bZ,bW);if(bW){b1+=bN}else{for(var bP=0,R=bN.length;bP<R;bP++){bN[bP].segment1=bS;bN[bP].segment2=bQ;bN[bP].bez1=b0;bN[bP].bez2=bZ}b1=b1.concat(bN)}}}}}return b1}aR.isPointInsidePath=function(d,b,i){var g=aR.pathBBox(d);return aR.isPointInsideBBox(g,b,i)&&D(d,[["M",b,i],["H",g.x2+10]],1)%2==1};aR._removedFactory=function(b){return function(){eve("raphael.log",null,"Rapha\xebl: you are calling to method \u201c"+b+"\u201d of removed object",b)}};var am=aR.pathBBox=function(bT){var bN=Y(bT);if(bN.bbox){return bN.bbox}if(!bT){return{x:0,y:0,width:0,height:0,x2:0,y2:0}}bT=W(bT);var bQ=0,bP=0,R=[],d=[],g;for(var bL=0,bS=bT.length;bL<bS;bL++){g=bT[bL];if(g[0]=="M"){bQ=g[1];bP=g[2];R.push(bQ);d.push(bP)}else{var bM=ba(bQ,bP,g[1],g[2],g[3],g[4],g[5],g[6]);R=R[bE](bM.min.x,bM.max.x);d=d[bE](bM.min.y,bM.max.y);bQ=g[5];bP=g[6]}}var b=bm[bG](0,R),bR=bm[bG](0,d),S=m[bG](0,R),E=m[bG](0,d),bO={x:b,y:bR,x2:S,y2:E,width:S-b,height:E-bR};bN.bbox=X(bO);return bO},aZ=function(d){var b=X(d);b.toString=aR._path2string;return b},aC=aR._pathToRelative=function(E){var bM=Y(E);if(bM.rel){return aZ(bM.rel)}if(!aR.is(E,bd)||!aR.is(E&&E[0],bd)){E=aR.parsePathString(E)}var bP=[],bR=0,bQ=0,bU=0,bT=0,g=0;if(E[0][0]=="M"){bR=E[0][1];bQ=E[0][2];bU=bR;bT=bQ;g++;bP.push(["M",bR,bQ])}for(var bL=g,bV=E.length;bL<bV;bL++){var b=bP[bL]=[],bS=E[bL];if(bS[0]!=bK.call(bS[0])){b[0]=bK.call(bS[0]);switch(b[0]){case"a":b[1]=bS[1];b[2]=bS[2];b[3]=bS[3];b[4]=bS[4];b[5]=bS[5];b[6]=+(bS[6]-bR).toFixed(3);b[7]=+(bS[7]-bQ).toFixed(3);break;case"v":b[1]=+(bS[1]-bQ).toFixed(3);break;case"m":bU=bS[1];bT=bS[2];default:for(var S=1,bN=bS.length;S<bN;S++){b[S]=+(bS[S]-((S%2)?bR:bQ)).toFixed(3)}}}else{b=bP[bL]=[];if(bS[0]=="m"){bU=bS[1]+bR;bT=bS[2]+bQ}for(var R=0,d=bS.length;R<d;R++){bP[bL][R]=bS[R]}}var bO=bP[bL].length;switch(bP[bL][0]){case"z":bR=bU;bQ=bT;break;case"h":bR+=+bP[bL][bO-1];break;case"v":bQ+=+bP[bL][bO-1];break;default:bR+=+bP[bL][bO-2];bQ+=+bP[bL][bO-1]}}bP.toString=aR._path2string;bM.rel=aZ(bP);return bP},w=aR._pathToAbsolute=function(bQ){var g=Y(bQ);if(g.abs){return aZ(g.abs)}if(!aR.is(bQ,bd)||!aR.is(bQ&&bQ[0],bd)){bQ=aR.parsePathString(bQ)}if(!bQ||!bQ.length){return[["M",0,0]]}var bW=[],bL=0,S=0,bO=0,bN=0,E=0;if(bQ[0][0]=="M"){bL=+bQ[0][1];S=+bQ[0][2];bO=bL;bN=S;E++;bW[0]=["M",bL,S]}var bV=bQ.length==3&&bQ[0][0]=="M"&&bQ[1][0].toUpperCase()=="R"&&bQ[2][0].toUpperCase()=="Z";for(var bP,b,bT=E,bM=bQ.length;bT<bM;bT++){bW.push(bP=[]);b=bQ[bT];if(b[0]!=bt.call(b[0])){bP[0]=bt.call(b[0]);switch(bP[0]){case"A":bP[1]=b[1];bP[2]=b[2];bP[3]=b[3];bP[4]=b[4];bP[5]=b[5];bP[6]=+(b[6]+bL);bP[7]=+(b[7]+S);break;case"V":bP[1]=+b[1]+S;break;case"H":bP[1]=+b[1]+bL;break;case"R":var R=[bL,S][bE](b.slice(1));for(var bS=2,bU=R.length;bS<bU;bS++){R[bS]=+R[bS]+bL;R[++bS]=+R[bS]+S}bW.pop();bW=bW[bE](bb(R,bV));break;case"M":bO=+b[1]+bL;bN=+b[2]+S;default:for(bS=1,bU=b.length;bS<bU;bS++){bP[bS]=+b[bS]+((bS%2)?bL:S)}}}else{if(b[0]=="R"){R=[bL,S][bE](b.slice(1));bW.pop();bW=bW[bE](bb(R,bV));bP=["R"][bE](b.slice(-2))}else{for(var bR=0,d=b.length;bR<d;bR++){bP[bR]=b[bR]}}}switch(bP[0]){case"Z":bL=bO;S=bN;break;case"H":bL=bP[1];break;case"V":S=bP[1];break;case"M":bO=bP[bP.length-2];bN=bP[bP.length-1];default:bL=bP[bP.length-2];S=bP[bP.length-1]}}bW.toString=aR._path2string;g.abs=aZ(bW);return bW},bI=function(d,i,b,g){return[d,i,b,g,b,g]},bn=function(d,i,S,E,b,g){var R=1/3,bL=2/3;return[R*d+bL*S,R*i+bL*E,R*b+bL*S,R*g+bL*E,b,g]},ae=function(bS,cn,b1,bZ,bT,bN,E,bR,cm,bU){var bY=aV*120/180,b=aV/180*(+bT||0),b5=[],b2,cj=aG(function(co,cr,i){var cq=co*au.cos(i)-cr*au.sin(i),cp=co*au.sin(i)+cr*au.cos(i);return{x:cq,y:cp}});if(!bU){b2=cj(bS,cn,-b);bS=b2.x;cn=b2.y;b2=cj(bR,cm,-b);bR=b2.x;cm=b2.y;var d=au.cos(aV/180*bT),bP=au.sin(aV/180*bT),b7=(bS-bR)/2,b6=(cn-cm)/2;var ch=(b7*b7)/(b1*b1)+(b6*b6)/(bZ*bZ);if(ch>1){ch=au.sqrt(ch);b1=ch*b1;bZ=ch*bZ}var g=b1*b1,ca=bZ*bZ,cc=(bN==E?-1:1)*au.sqrt(aw((g*ca-g*b6*b6-ca*b7*b7)/(g*b6*b6+ca*b7*b7))),bW=cc*b1*b6/bZ+(bS+bR)/2,bV=cc*-bZ*b7/b1+(cn+cm)/2,bM=au.asin(((cn-bV)/bZ).toFixed(9)),bL=au.asin(((cm-bV)/bZ).toFixed(9));bM=bS<bW?aV-bM:bM;bL=bR<bW?aV-bL:bL;bM<0&&(bM=aV*2+bM);bL<0&&(bL=aV*2+bL);if(E&&bM>bL){bM=bM-aV*2}if(!E&&bL>bM){bL=bL-aV*2}}else{bM=bU[0];bL=bU[1];bW=bU[2];bV=bU[3]}var bQ=bL-bM;if(aw(bQ)>bY){var bX=bL,b0=bR,bO=cm;bL=bM+bY*(E&&bL>bM?1:-1);bR=bW+b1*au.cos(bL);cm=bV+bZ*au.sin(bL);b5=ae(bR,cm,b1,bZ,bT,0,E,b0,bO,[bL,bX,bW,bV])}bQ=bL-bM;var S=au.cos(bM),cl=au.sin(bM),R=au.cos(bL),ck=au.sin(bL),b8=au.tan(bQ/4),cb=4/3*b1*b8,b9=4/3*bZ*b8,ci=[bS,cn],cg=[bS+cb*cl,cn-b9*S],cf=[bR+cb*ck,cm-b9*R],cd=[bR,cm];cg[0]=2*ci[0]-cg[0];cg[1]=2*ci[1]-cg[1];if(bU){return[cg,cf,cd][bE](b5)}else{b5=[cg,cf,cd][bE](b5).join()[F](",");var b3=[];for(var ce=0,b4=b5.length;ce<b4;ce++){b3[ce]=ce%2?cj(b5[ce-1],b5[ce],b).y:cj(b5[ce],b5[ce+1],b).x}return b3}},ag=function(d,b,i,g,bM,bL,S,R,bN){var E=1-bN;return{x:bp(E,3)*d+bp(E,2)*3*bN*i+E*3*bN*bN*bM+bp(bN,3)*S,y:bp(E,3)*b+bp(E,2)*3*bN*g+E*3*bN*bN*bL+bp(bN,3)*R}},ba=aG(function(i,d,R,E,bU,bT,bQ,bN){var bS=(bU-2*R+i)-(bQ-2*bU+R),bP=2*(R-i)-2*(bU-R),bM=i-R,bL=(-bP+au.sqrt(bP*bP-4*bS*bM))/2/bS,S=(-bP-au.sqrt(bP*bP-4*bS*bM))/2/bS,bO=[d,bN],bR=[i,bQ],g;aw(bL)>"1e12"&&(bL=0.5);aw(S)>"1e12"&&(S=0.5);if(bL>0&&bL<1){g=ag(i,d,R,E,bU,bT,bQ,bN,bL);bR.push(g.x);bO.push(g.y)}if(S>0&&S<1){g=ag(i,d,R,E,bU,bT,bQ,bN,S);bR.push(g.x);bO.push(g.y)}bS=(bT-2*E+d)-(bN-2*bT+E);bP=2*(E-d)-2*(bT-E);bM=d-E;bL=(-bP+au.sqrt(bP*bP-4*bS*bM))/2/bS;S=(-bP-au.sqrt(bP*bP-4*bS*bM))/2/bS;aw(bL)>"1e12"&&(bL=0.5);aw(S)>"1e12"&&(S=0.5);if(bL>0&&bL<1){g=ag(i,d,R,E,bU,bT,bQ,bN,bL);bR.push(g.x);bO.push(g.y)}if(S>0&&S<1){g=ag(i,d,R,E,bU,bT,bQ,bN,S);bR.push(g.x);bO.push(g.y)}return{min:{x:bm[bG](0,bR),y:bm[bG](0,bO)},max:{x:m[bG](0,bR),y:m[bG](0,bO)}}}),W=aR._path2curve=aG(function(bU,bP){var bN=!bP&&Y(bU);if(!bP&&bN.curve){return aZ(bN.curve)}var E=w(bU),bQ=bP&&w(bP),bR={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},d={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},S=function(bV,bW){var i,bX;if(!bV){return["C",bW.x,bW.y,bW.x,bW.y,bW.x,bW.y]}!(bV[0] in {T:1,Q:1})&&(bW.qx=bW.qy=null);switch(bV[0]){case"M":bW.X=bV[1];bW.Y=bV[2];break;case"A":bV=["C"][bE](ae[bG](0,[bW.x,bW.y][bE](bV.slice(1))));break;case"S":i=bW.x+(bW.x-(bW.bx||bW.x));bX=bW.y+(bW.y-(bW.by||bW.y));bV=["C",i,bX][bE](bV.slice(1));break;case"T":bW.qx=bW.x+(bW.x-(bW.qx||bW.x));bW.qy=bW.y+(bW.y-(bW.qy||bW.y));bV=["C"][bE](bn(bW.x,bW.y,bW.qx,bW.qy,bV[1],bV[2]));break;case"Q":bW.qx=bV[1];bW.qy=bV[2];bV=["C"][bE](bn(bW.x,bW.y,bV[1],bV[2],bV[3],bV[4]));break;case"L":bV=["C"][bE](bI(bW.x,bW.y,bV[1],bV[2]));break;case"H":bV=["C"][bE](bI(bW.x,bW.y,bV[1],bW.y));break;case"V":bV=["C"][bE](bI(bW.x,bW.y,bW.x,bV[1]));break;case"Z":bV=["C"][bE](bI(bW.x,bW.y,bW.X,bW.Y));break}return bV},b=function(bV,bW){if(bV[bW].length>7){bV[bW].shift();var bX=bV[bW];while(bX.length){bV.splice(bW++,0,["C"][bE](bX.splice(0,6)))}bV.splice(bW,1);bS=m(E.length,bQ&&bQ.length||0)}},g=function(bZ,bY,bW,bV,bX){if(bZ&&bY&&bZ[bX][0]=="M"&&bY[bX][0]!="M"){bY.splice(bX,0,["M",bV.x,bV.y]);bW.bx=0;bW.by=0;bW.x=bZ[bX][1];bW.y=bZ[bX][2];bS=m(E.length,bQ&&bQ.length||0)}};for(var bM=0,bS=m(E.length,bQ&&bQ.length||0);bM<bS;bM++){E[bM]=S(E[bM],bR);b(E,bM);bQ&&(bQ[bM]=S(bQ[bM],d));bQ&&b(bQ,bM);g(E,bQ,bR,d,bM);g(bQ,E,d,bR,bM);var bL=E[bM],bT=bQ&&bQ[bM],R=bL.length,bO=bQ&&bT.length;bR.x=bL[R-2];bR.y=bL[R-1];bR.bx=an(bL[R-4])||bR.x;bR.by=an(bL[R-3])||bR.y;d.bx=bQ&&(an(bT[bO-4])||d.x);d.by=bQ&&(an(bT[bO-3])||d.y);d.x=bQ&&bT[bO-2];d.y=bQ&&bT[bO-1]}if(!bQ){bN.curve=aZ(E)}return bQ?[E,bQ]:E},null,aZ),v=aR._parseDots=aG(function(bO){var bN=[];for(var S=0,bP=bO.length;S<bP;S++){var b={},bM=bO[S].match(/^([^:]*):?([\d\.]*)/);b.color=aR.getRGB(bM[1]);if(b.color.error){return null}b.color=b.color.hex;bM[2]&&(b.offset=bM[2]+"%");bN.push(b)}for(S=1,bP=bN.length-1;S<bP;S++){if(!bN[S].offset){var g=an(bN[S-1].offset||0),E=0;for(var R=S+1;R<bP;R++){if(bN[R].offset){E=bN[R].offset;break}}if(!E){E=100;R=bP}E=an(E);var bL=(E-g)/(R-S+1);for(;S<R;S++){g+=bL;bN[S].offset=g+"%"}}}return bN}),aK=aR._tear=function(b,d){b==d.top&&(d.top=b.prev);b==d.bottom&&(d.bottom=b.next);b.next&&(b.next.prev=b.prev);b.prev&&(b.prev.next=b.next)},ap=aR._tofront=function(b,d){if(d.top===b){return}aK(b,d);b.next=null;b.prev=d.top;d.top.next=b;d.top=b},p=aR._toback=function(b,d){if(d.bottom===b){return}aK(b,d);b.next=d.bottom;b.prev=null;d.bottom.prev=b;d.bottom=b},G=aR._insertafter=function(d,b,g){aK(d,g);b==g.top&&(g.top=d);b.next&&(b.next.prev=d);d.next=b.next;d.prev=b;b.next=d},aT=aR._insertbefore=function(d,b,g){aK(d,g);b==g.bottom&&(g.bottom=d);b.prev&&(b.prev.next=d);d.prev=b.prev;b.prev=d;d.next=b},bl=aR.toMatrix=function(g,b){var i=am(g),d={_:{transform:aX},getBBox:function(){return i}};aO(d,b);return d.matrix},T=aR.transformPath=function(d,b){return L(d,bl(d,b))},aO=aR._extractTransform=function(d,bZ){if(bZ==null){return d._.transform}bZ=bH(bZ).replace(/\.{3}|\u2026/g,d._.transform||aX);var bR=aR.parseTransformString(bZ),bP=0,bN=0,bM=0,bT=1,bS=1,b0=d._,bU=new aF;b0.transform=bR||[];if(bR){for(var bV=0,bO=bR.length;bV<bO;bV++){var bQ=bR[bV],b=bQ.length,R=bH(bQ[0]).toLowerCase(),bY=bQ[0]!=R,bL=bY?bU.invert():0,bX,E,bW,g,S;if(R=="t"&&b==3){if(bY){bX=bL.x(0,0);E=bL.y(0,0);bW=bL.x(bQ[1],bQ[2]);g=bL.y(bQ[1],bQ[2]);bU.translate(bW-bX,g-E)}else{bU.translate(bQ[1],bQ[2])}}else{if(R=="r"){if(b==2){S=S||d.getBBox(1);bU.rotate(bQ[1],S.x+S.width/2,S.y+S.height/2);bP+=bQ[1]}else{if(b==4){if(bY){bW=bL.x(bQ[2],bQ[3]);g=bL.y(bQ[2],bQ[3]);bU.rotate(bQ[1],bW,g)}else{bU.rotate(bQ[1],bQ[2],bQ[3])}bP+=bQ[1]}}}else{if(R=="s"){if(b==2||b==3){S=S||d.getBBox(1);bU.scale(bQ[1],bQ[b-1],S.x+S.width/2,S.y+S.height/2);bT*=bQ[1];bS*=bQ[b-1]}else{if(b==5){if(bY){bW=bL.x(bQ[3],bQ[4]);g=bL.y(bQ[3],bQ[4]);bU.scale(bQ[1],bQ[2],bW,g)}else{bU.scale(bQ[1],bQ[2],bQ[3],bQ[4])}bT*=bQ[1];bS*=bQ[2]}}}else{if(R=="m"&&b==7){bU.add(bQ[1],bQ[2],bQ[3],bQ[4],bQ[5],bQ[6])}}}}b0.dirtyT=1;d.matrix=bU}}d.matrix=bU;b0.sx=bT;b0.sy=bS;b0.deg=bP;b0.dx=bN=bU.e;b0.dy=bM=bU.f;if(bT==1&&bS==1&&!bP&&b0.bbox){b0.bbox.x+=+bN;b0.bbox.y+=+bM}else{b0.dirtyT=1}},l=function(d){var b=d[0];switch(b.toLowerCase()){case"t":return[b,0,0];case"m":return[b,1,0,0,1,0,0];case"r":if(d.length==4){return[b,0,d[2],d[3]]}else{return[b,0]}case"s":if(d.length==5){return[b,1,1,d[3],d[4]]}else{if(d.length==3){return[b,1,1]}else{return[b,1]}}}},aB=aR._equaliseTransform=function(R,E){E=bH(E).replace(/\.{3}|\u2026/g,R);R=aR.parseTransformString(R)||[];E=aR.parseTransformString(E)||[];var b=m(R.length,E.length),bN=[],bO=[],g=0,d,S,bM,bL;for(;g<b;g++){bM=R[g]||l(E[g]);bL=E[g]||l(bM);if((bM[0]!=bL[0])||(bM[0].toLowerCase()=="r"&&(bM[2]!=bL[2]||bM[3]!=bL[3]))||(bM[0].toLowerCase()=="s"&&(bM[3]!=bL[3]||bM[4]!=bL[4]))){return}bN[g]=[];bO[g]=[];for(d=0,S=m(bM.length,bL.length);d<S;d++){d in bM&&(bN[g][d]=bM[d]);d in bL&&(bO[g][d]=bL[d])}}return{from:bN,to:bO}};aR._getContainer=function(b,E,g,i){var d;d=i==null&&!aR.is(b,"object")?aA.doc.getElementById(b):b;if(d==null){return}if(d.tagName){if(E==null){return{container:d,width:d.style.pixelWidth||d.offsetWidth,height:d.style.pixelHeight||d.offsetHeight}}else{return{container:d,width:E,height:g}}}return{container:1,x:b,y:E,width:g,height:i}};aR.pathToRelative=aC;aR._engine={};aR.path2curve=W;aR.matrix=function(i,g,bL,S,R,E){return new aF(i,g,bL,S,R,E)};function aF(i,g,bL,S,R,E){if(i!=null){this.a=+i;this.b=+g;this.c=+bL;this.d=+S;this.e=+R;this.f=+E}else{this.a=1;this.b=0;this.c=0;this.d=1;this.e=0;this.f=0}}(function(g){g.add=function(bT,bQ,bO,bM,S,R){var E=[[],[],[]],i=[[this.a,this.c,this.e],[this.b,this.d,this.f],[0,0,1]],bS=[[bT,bO,S],[bQ,bM,R],[0,0,1]],bR,bP,bN,bL;if(bT&&bT instanceof aF){bS=[[bT.a,bT.c,bT.e],[bT.b,bT.d,bT.f],[0,0,1]]}for(bR=0;bR<3;bR++){for(bP=0;bP<3;bP++){bL=0;for(bN=0;bN<3;bN++){bL+=i[bR][bN]*bS[bN][bP]}E[bR][bP]=bL}}this.a=E[0][0];this.b=E[1][0];this.c=E[0][1];this.d=E[1][1];this.e=E[0][2];this.f=E[1][2]};g.invert=function(){var E=this,i=E.a*E.d-E.b*E.c;return new aF(E.d/i,-E.b/i,-E.c/i,E.a/i,(E.c*E.f-E.d*E.e)/i,(E.b*E.e-E.a*E.f)/i)};g.clone=function(){return new aF(this.a,this.b,this.c,this.d,this.e,this.f)};g.translate=function(i,E){this.add(1,0,0,1,i,E)};g.scale=function(E,S,i,R){S==null&&(S=E);(i||R)&&this.add(1,0,0,1,i,R);this.add(E,0,0,S,0,0);(i||R)&&this.add(1,0,0,1,-i,-R)};g.rotate=function(E,i,bL){E=aR.rad(E);i=i||0;bL=bL||0;var S=+au.cos(E).toFixed(9),R=+au.sin(E).toFixed(9);this.add(S,R,-R,S,i,bL);this.add(1,0,0,1,-i,-bL)};g.x=function(i,E){return i*this.a+E*this.c+this.e};g.y=function(i,E){return i*this.b+E*this.d+this.f};g.get=function(E){return +this[bH.fromCharCode(97+E)].toFixed(4)};g.toString=function(){return aR.svg?"matrix("+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)].join()+")":[this.get(0),this.get(2),this.get(1),this.get(3),0,0].join()};g.toFilter=function(){return"progid:DXImageTransform.Microsoft.Matrix(M11="+this.get(0)+", M12="+this.get(2)+", M21="+this.get(1)+", M22="+this.get(3)+", Dx="+this.get(4)+", Dy="+this.get(5)+", sizingmethod='auto expand')"};g.offset=function(){return[this.e.toFixed(4),this.f.toFixed(4)]};function d(i){return i[0]*i[0]+i[1]*i[1]}function b(i){var E=au.sqrt(d(i));i[0]&&(i[0]/=E);i[1]&&(i[1]/=E)}g.split=function(){var E={};E.dx=this.e;E.dy=this.f;var S=[[this.a,this.c],[this.b,this.d]];E.scalex=au.sqrt(d(S[0]));b(S[0]);E.shear=S[0][0]*S[1][0]+S[0][1]*S[1][1];S[1]=[S[1][0]-S[0][0]*E.shear,S[1][1]-S[0][1]*E.shear];E.scaley=au.sqrt(d(S[1]));b(S[1]);E.shear/=E.scaley;var i=-S[0][1],R=S[1][1];if(R<0){E.rotate=aR.deg(au.acos(R));if(i<0){E.rotate=360-E.rotate}}else{E.rotate=aR.deg(au.asin(i))}E.isSimple=!+E.shear.toFixed(9)&&(E.scalex.toFixed(9)==E.scaley.toFixed(9)||!E.rotate);E.isSuperSimple=!+E.shear.toFixed(9)&&E.scalex.toFixed(9)==E.scaley.toFixed(9)&&!E.rotate;E.noRotation=!+E.shear.toFixed(9)&&!E.rotate;return E};g.toTransformString=function(i){var E=i||this[F]();if(E.isSimple){E.scalex=+E.scalex.toFixed(4);E.scaley=+E.scaley.toFixed(4);E.rotate=+E.rotate.toFixed(4);return(E.dx||E.dy?"t"+[E.dx,E.dy]:aX)+(E.scalex!=1||E.scaley!=1?"s"+[E.scalex,E.scaley,0,0]:aX)+(E.rotate?"r"+[E.rotate,0,0]:aX)}else{return"m"+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)]}}})(aF.prototype);var V=navigator.userAgent.match(/Version\/(.*?)\s/)||navigator.userAgent.match(/Chrome\/(\d+)/);if((navigator.vendor=="Apple Computer, Inc.")&&(V&&V[1]<4||navigator.platform.slice(0,2)=="iP")||(navigator.vendor=="Google Inc."&&V&&V[1]<8)){a4.safari=function(){var b=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});setTimeout(function(){b.remove()})}}else{a4.safari=I}var P=function(){this.returnValue=false},bD=function(){return this.originalEvent.preventDefault()},a8=function(){this.cancelBubble=true},aJ=function(){return this.originalEvent.stopPropagation()},aD=(function(){if(aA.doc.addEventListener){return function(R,i,g,d){var b=Z&&bx[i]?bx[i]:i,E=function(bP){var bO=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bQ=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft,S=bP.clientX+bQ,bR=bP.clientY+bO;if(Z&&bx[ak](i)){for(var bM=0,bN=bP.targetTouches&&bP.targetTouches.length;bM<bN;bM++){if(bP.targetTouches[bM].target==R){var bL=bP;bP=bP.targetTouches[bM];bP.originalEvent=bL;bP.preventDefault=bD;bP.stopPropagation=aJ;break}}}return g.call(d,bP,S,bR)};R.addEventListener(b,E,false);return function(){R.removeEventListener(b,E,false);return true}}}else{if(aA.doc.attachEvent){return function(R,i,g,d){var E=function(bM){bM=bM||aA.win.event;var bL=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bN=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft,S=bM.clientX+bN,bO=bM.clientY+bL;bM.preventDefault=bM.preventDefault||P;bM.stopPropagation=bM.stopPropagation||a8;return g.call(d,bM,S,bO)};R.attachEvent("on"+i,E);var b=function(){R.detachEvent("on"+i,E);return true};return b}}}})(),be=[],by=function(bM){var bP=bM.clientX,bO=bM.clientY,bR=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bS=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft,g,E=be.length;while(E--){g=be[E];if(Z){var S=bM.touches.length,R;while(S--){R=bM.touches[S];if(R.identifier==g.el._drag.id){bP=R.clientX;bO=R.clientY;(bM.originalEvent?bM.originalEvent:bM).preventDefault();break}}}else{bM.preventDefault()}var d=g.el.node,b,bL=d.nextSibling,bQ=d.parentNode,bN=d.style.display;aA.win.opera&&bQ.removeChild(d);d.style.display="none";b=g.el.paper.getElementByPoint(bP,bO);d.style.display=bN;aA.win.opera&&(bL?bQ.insertBefore(d,bL):bQ.appendChild(d));b&&eve("raphael.drag.over."+g.el.id,g.el,b);bP+=bS;bO+=bR;eve("raphael.drag.move."+g.el.id,g.move_scope||g.el,bP-g.el._drag.x,bO-g.el._drag.y,bP,bO,bM)}},e=function(g){aR.unmousemove(by).unmouseup(e);var d=be.length,b;while(d--){b=be[d];b.el._drag={};eve("raphael.drag.end."+b.el.id,b.end_scope||b.start_scope||b.move_scope||b.el,g)}be=[]},bh=aR.el={};for(var ax=Q.length;ax--;){(function(b){aR[b]=bh[b]=function(g,d){if(aR.is(g,"function")){this.events=this.events||[];this.events.push({name:b,f:g,unbind:aD(this.shape||this.node||aA.doc,b,g,d||this)})}return this};aR["un"+b]=bh["un"+b]=function(i){var g=this.events||[],d=g.length;while(d--){if(g[d].name==b&&g[d].f==i){g[d].unbind();g.splice(d,1);!g.length&&delete this.events;return this}}return this}})(Q[ax])}bh.data=function(d,E){var g=aU[this.id]=aU[this.id]||{};if(arguments.length==1){if(aR.is(d,"object")){for(var b in d){if(d[ak](b)){this.data(b,d[b])}}return this}eve("raphael.data.get."+this.id,this,g[d],d);return g[d]}g[d]=E;eve("raphael.data.set."+this.id,this,E,d);return this};bh.removeData=function(b){if(b==null){aU[this.id]={}}else{aU[this.id]&&delete aU[this.id][b]}return this};bh.hover=function(i,b,g,d){return this.mouseover(i,g).mouseout(b,d||g)};bh.unhover=function(d,b){return this.unmouseover(d).unmouseout(b)};var bu=[];bh.drag=function(d,R,E,b,g,i){function S(bM){(bM.originalEvent||bM).preventDefault();var bL=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bN=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft;this._drag.x=bM.clientX+bN;this._drag.y=bM.clientY+bL;this._drag.id=bM.identifier;!be.length&&aR.mousemove(by).mouseup(e);be.push({el:this,move_scope:b,start_scope:g,end_scope:i});R&&eve.on("raphael.drag.start."+this.id,R);d&&eve.on("raphael.drag.move."+this.id,d);E&&eve.on("raphael.drag.end."+this.id,E);eve("raphael.drag.start."+this.id,g||b||this,bM.clientX+bN,bM.clientY+bL,bM)}this._drag={};bu.push({el:this,start:S});this.mousedown(S);return this};bh.onDragOver=function(b){b?eve.on("raphael.drag.over."+this.id,b):eve.unbind("raphael.drag.over."+this.id)};bh.undrag=function(){var b=bu.length;while(b--){if(bu[b].el==this){this.unmousedown(bu[b].start);bu.splice(b,1);eve.unbind("raphael.drag.*."+this.id)}}!bu.length&&aR.unmousemove(by).unmouseup(e)};a4.circle=function(b,i,g){var d=aR._engine.circle(this,b||0,i||0,g||0);this.__set__&&this.__set__.push(d);return d};a4.rect=function(b,R,d,i,E){var g=aR._engine.rect(this,b||0,R||0,d||0,i||0,E||0);this.__set__&&this.__set__.push(g);return g};a4.ellipse=function(b,E,i,g){var d=aR._engine.ellipse(this,b||0,E||0,i||0,g||0);this.__set__&&this.__set__.push(d);return d};a4.path=function(b){b&&!aR.is(b,aj)&&!aR.is(b[0],bd)&&(b+=aX);var d=aR._engine.path(aR.format[bG](aR,arguments),this);this.__set__&&this.__set__.push(d);return d};a4.image=function(E,b,R,d,i){var g=aR._engine.image(this,E||"about:blank",b||0,R||0,d||0,i||0);this.__set__&&this.__set__.push(g);return g};a4.text=function(b,i,g){var d=aR._engine.text(this,b||0,i||0,bH(g));this.__set__&&this.__set__.push(d);return d};a4.set=function(d){!aR.is(d,"array")&&(d=Array.prototype.splice.call(arguments,0,arguments.length));var b=new al(d);this.__set__&&this.__set__.push(b);return b};a4.setStart=function(b){this.__set__=b||this.set()};a4.setFinish=function(d){var b=this.__set__;delete this.__set__;return b};a4.setSize=function(d,b){return aR._engine.setSize.call(this,d,b)};a4.setViewBox=function(b,E,d,i,g){return aR._engine.setViewBox.call(this,b,E,d,i,g)};a4.top=a4.bottom=null;a4.raphael=aR;var bs=function(g){var E=g.getBoundingClientRect(),bM=g.ownerDocument,R=bM.body,b=bM.documentElement,i=b.clientTop||R.clientTop||0,S=b.clientLeft||R.clientLeft||0,bL=E.top+(aA.win.pageYOffset||b.scrollTop||R.scrollTop)-i,d=E.left+(aA.win.pageXOffset||b.scrollLeft||R.scrollLeft)-S;return{y:bL,x:d}};a4.getElementByPoint=function(d,bL){var S=this,g=S.canvas,R=aA.doc.elementFromPoint(d,bL);if(aA.win.opera&&R.tagName=="svg"){var E=bs(g),i=g.createSVGRect();i.x=d-E.x;i.y=bL-E.y;i.width=i.height=1;var b=g.getIntersectionList(i,null);if(b.length){R=b[b.length-1]}}if(!R){return null}while(R.parentNode&&R!=g.parentNode&&!R.raphael){R=R.parentNode}R==S.canvas.parentNode&&(R=g);R=R&&R.raphael?S.getById(R.raphaelid):null;return R};a4.getById=function(d){var b=this.bottom;while(b){if(b.id==d){return b}b=b.next}return null};a4.forEach=function(g,b){var d=this.bottom;while(d){if(g.call(b,d)===false){return this}d=d.next}return this};a4.getElementsByPoint=function(b,g){var d=this.set();this.forEach(function(i){if(i.isPointInside(b,g)){d.push(i)}});return d};function y(){return this.x+aQ+this.y}function at(){return this.x+aQ+this.y+aQ+this.width+" \xd7 "+this.height}bh.isPointInside=function(b,g){var d=this.realPath=this.realPath||N[this.type](this);return aR.isPointInsidePath(d,b,g)};bh.getBBox=function(d){if(this.removed){return{}}var b=this._;if(d){if(b.dirty||!b.bboxwt){this.realPath=N[this.type](this);b.bboxwt=am(this.realPath);b.bboxwt.toString=at;b.dirty=0}return b.bboxwt}if(b.dirty||b.dirtyT||!b.bbox){if(b.dirty||!this.realPath){b.bboxwt=0;this.realPath=N[this.type](this)}b.bbox=am(L(this.realPath,this.matrix));b.bbox.toString=at;b.dirty=b.dirtyT=0}return b.bbox};bh.clone=function(){if(this.removed){return null}var b=this.paper[this.type]().attr(this.attr());this.__set__&&this.__set__.push(b);return b};bh.glow=function(bL){if(this.type=="text"){return null}bL=bL||{};var g={width:(bL.width||10)+(+this.attr("stroke-width")||1),fill:bL.fill||false,opacity:bL.opacity||0.5,offsetx:bL.offsetx||0,offsety:bL.offsety||0,color:bL.color||"#000"},S=g.width/2,E=this.paper,b=E.set(),R=this.realPath||N[this.type](this);R=this.matrix?L(R,this.matrix):R;for(var d=1;d<S+1;d++){b.push(E.path(R).attr({stroke:g.color,fill:g.fill?g.color:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(g.width/S*d).toFixed(3),opacity:+(g.opacity/S).toFixed(3)}))}return b.insertBefore(this).translate(g.offsetx,g.offsety)};var a7={},k=function(d,b,E,i,bM,bL,S,R,g){if(g==null){return q(d,b,E,i,bM,bL,S,R)}else{return aR.findDotsAtSegment(d,b,E,i,bM,bL,S,R,C(d,b,E,i,bM,bL,S,R,g))}},a6=function(b,d){return function(bT,R,S){bT=W(bT);var bP,bO,g,bL,E="",bS={},bQ,bN=0;for(var bM=0,bR=bT.length;bM<bR;bM++){g=bT[bM];if(g[0]=="M"){bP=+g[1];bO=+g[2]}else{bL=k(bP,bO,g[1],g[2],g[3],g[4],g[5],g[6]);if(bN+bL>R){if(d&&!bS.start){bQ=k(bP,bO,g[1],g[2],g[3],g[4],g[5],g[6],R-bN);E+=["C"+bQ.start.x,bQ.start.y,bQ.m.x,bQ.m.y,bQ.x,bQ.y];if(S){return E}bS.start=E;E=["M"+bQ.x,bQ.y+"C"+bQ.n.x,bQ.n.y,bQ.end.x,bQ.end.y,g[5],g[6]].join();bN+=bL;bP=+g[5];bO=+g[6];continue}if(!b&&!d){bQ=k(bP,bO,g[1],g[2],g[3],g[4],g[5],g[6],R-bN);return{x:bQ.x,y:bQ.y,alpha:bQ.alpha}}}bN+=bL;bP=+g[5];bO=+g[6]}E+=g.shift()+g}bS.end=E;bQ=b?bN:d?bS:aR.findDotsAtSegment(bP,bO,g[0],g[1],g[2],g[3],g[4],g[5],1);bQ.alpha&&(bQ={x:bQ.x,y:bQ.y,alpha:bQ.alpha});return bQ}};var aS=a6(1),J=a6(),ad=a6(0,1);aR.getTotalLength=aS;aR.getPointAtLength=J;aR.getSubpath=function(d,i,g){if(this.getTotalLength(d)-g<0.000001){return ad(d,i).end}var b=ad(d,g,1);return i?ad(b,i).end:b};bh.getTotalLength=function(){if(this.type!="path"){return}if(this.node.getTotalLength){return this.node.getTotalLength()}return aS(this.attrs.path)};bh.getPointAtLength=function(b){if(this.type!="path"){return}return J(this.attrs.path,b)};bh.getSubpath=function(d,b){if(this.type!="path"){return}return aR.getSubpath(this.attrs.path,d,b)};var o=aR.easing_formulas={linear:function(b){return b},"<":function(b){return bp(b,1.7)},">":function(b){return bp(b,0.48)},"<>":function(bL){var i=0.48-bL/1.04,g=au.sqrt(0.1734+i*i),b=g-i,S=bp(aw(b),1/3)*(b<0?-1:1),R=-g-i,E=bp(aw(R),1/3)*(R<0?-1:1),d=S+E+0.5;return(1-d)*3*d*d+d*d*d},backIn:function(d){var b=1.70158;return d*d*((b+1)*d-b)},backOut:function(d){d=d-1;var b=1.70158;return d*d*((b+1)*d+b)+1},elastic:function(b){if(b==!!b){return b}return bp(2,-10*b)*au.sin((b-0.075)*(2*aV)/0.3)+1},bounce:function(i){var d=7.5625,g=2.75,b;if(i<(1/g)){b=d*i*i}else{if(i<(2/g)){i-=(1.5/g);b=d*i*i+0.75}else{if(i<(2.5/g)){i-=(2.25/g);b=d*i*i+0.9375}else{i-=(2.625/g);b=d*i*i+0.984375}}}return b}};o.easeIn=o["ease-in"]=o["<"];o.easeOut=o["ease-out"]=o[">"];o.easeInOut=o["ease-in-out"]=o["<>"];o["back-in"]=o.backIn;o["back-out"]=o.backOut;var ab=[],aN=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(b){setTimeout(b,16)},bC=function(){var bL=+new Date,bT=0;for(;bT<ab.length;bT++){var bZ=ab[bT];if(bZ.el.removed||bZ.paused){continue}var E=bL-bZ.start,bR=bZ.ms,bQ=bZ.easing,bU=bZ.from,bO=bZ.diff,d=bZ.to,bN=bZ.t,S=bZ.el,bP={},b,bX={},b1;if(bZ.initstatus){E=(bZ.initstatus*bZ.anim.top-bZ.prev)/(bZ.percent-bZ.prev)*bR;bZ.status=bZ.initstatus;delete bZ.initstatus;bZ.stop&&ab.splice(bT--,1)}else{bZ.status=(bZ.prev+(bZ.percent-bZ.prev)*(E/bR))/bZ.anim.top}if(E<0){continue}if(E<bR){var g=bQ(E/bR);for(var bS in bU){if(bU[ak](bS)){switch(ar[bS]){case aL:b=+bU[bS]+g*bR*bO[bS];break;case"colour":b="rgb("+[H(ah(bU[bS].r+g*bR*bO[bS].r)),H(ah(bU[bS].g+g*bR*bO[bS].g)),H(ah(bU[bS].b+g*bR*bO[bS].b))].join(",")+")";break;case"path":b=[];for(var bW=0,bM=bU[bS].length;bW<bM;bW++){b[bW]=[bU[bS][bW][0]];for(var bV=1,bY=bU[bS][bW].length;bV<bY;bV++){b[bW][bV]=+bU[bS][bW][bV]+g*bR*bO[bS][bW][bV]}b[bW]=b[bW].join(aQ)}b=b.join(aQ);break;case"transform":if(bO[bS].real){b=[];for(bW=0,bM=bU[bS].length;bW<bM;bW++){b[bW]=[bU[bS][bW][0]];for(bV=1,bY=bU[bS][bW].length;bV<bY;bV++){b[bW][bV]=bU[bS][bW][bV]+g*bR*bO[bS][bW][bV]}}}else{var b0=function(b2){return +bU[bS][b2]+g*bR*bO[bS][b2]};b=[["m",b0(0),b0(1),b0(2),b0(3),b0(4),b0(5)]]}break;case"csv":if(bS=="clip-rect"){b=[];bW=4;while(bW--){b[bW]=+bU[bS][bW]+g*bR*bO[bS][bW]}}break;default:var R=[][bE](bU[bS]);b=[];bW=S.paper.customAttributes[bS].length;while(bW--){b[bW]=+R[bW]+g*bR*bO[bS][bW]}break}bP[bS]=b}}S.attr(bP);(function(b3,i,b2){setTimeout(function(){eve("raphael.anim.frame."+b3,i,b2)})})(S.id,S,bZ.anim)}else{(function(b3,b2,i){setTimeout(function(){eve("raphael.anim.frame."+b2.id,b2,i);eve("raphael.anim.finish."+b2.id,b2,i);aR.is(b3,"function")&&b3.call(b2)})})(bZ.callback,S,bZ.anim);S.attr(d);ab.splice(bT--,1);if(bZ.repeat>1&&!bZ.next){for(b1 in d){if(d[ak](b1)){bX[b1]=bZ.totalOrigin[b1]}}bZ.el.attr(bX);aM(bZ.anim,bZ.el,bZ.anim.percents[0],null,bZ.totalOrigin,bZ.repeat-1)}if(bZ.next&&!bZ.stop){aM(bZ.anim,bZ.el,bZ.next,null,bZ.totalOrigin,bZ.repeat)}}}aR.svg&&S&&S.paper&&S.paper.safari();ab.length&&aN(bC)},H=function(b){return b>255?255:b<0?0:b};bh.animateWith=function(d,E,g,b,bL,bQ){var S=this;if(S.removed){bQ&&bQ.call(S);return S}var bO=g instanceof bA?g:aR.animation(g,b,bL,bQ),bN,bM;aM(bO,S,bO.percents[0],null,S.attr());for(var R=0,bP=ab.length;R<bP;R++){if(ab[R].anim==E&&ab[R].el==d){ab[bP-1].start=ab[R].start;break}}return S};function a3(bR,i,d,bQ,bP,bL){var bM=3*i,bO=3*(bQ-i)-bM,b=1-bM-bO,S=3*d,bN=3*(bP-d)-S,bS=1-S-bN;function R(bT){return((b*bT+bO)*bT+bM)*bT}function g(bT,bV){var bU=E(bT,bV);return((bS*bU+bN)*bU+S)*bU}function E(bT,b0){var bZ,bY,bW,bU,bX,bV;for(bW=bT,bV=0;bV<8;bV++){bU=R(bW)-bT;if(aw(bU)<b0){return bW}bX=(3*b*bW+2*bO)*bW+bM;if(aw(bX)<0.000001){break}bW=bW-bU/bX}bZ=0;bY=1;bW=bT;if(bW<bZ){return bZ}if(bW>bY){return bY}while(bZ<bY){bU=R(bW);if(aw(bU-bT)<b0){return bW}if(bT>bU){bZ=bW}else{bY=bW}bW=(bY-bZ)/2+bZ}return bW}return g(bR,1/(200*bL))}bh.onAnimation=function(b){b?eve.on("raphael.anim.frame."+this.id,b):eve.unbind("raphael.anim.frame."+this.id);return this};function bA(E,g){var d=[],i={};this.ms=g;this.times=1;if(E){for(var b in E){if(E[ak](b)){i[an(b)]=E[b];d.push(an(b))}}d.sort(u)}this.anim=i;this.top=d[d.length-1];this.percents=d}bA.prototype.delay=function(d){var b=new bA(this.anim,this.ms);b.times=this.times;b.del=+d||0;return b};bA.prototype.repeat=function(d){var b=new bA(this.anim,this.ms);b.del=this.del;b.times=au.floor(m(d,0))||1;return b};function aM(b3,g,b,b1,bL,bP){b=an(b);var ca,S,bO,cb=[],bV,bU,R,bX=b3.ms,b2={},E={},bR={};if(b1){for(b6=0,bQ=ab.length;b6<bQ;b6++){var b8=ab[b6];if(b8.el.id==g.id&&b8.anim==b3){if(b8.percent!=b){ab.splice(b6,1);bO=1}else{S=b8}g.attr(b8.totalOrigin);break}}}else{b1=+E}for(var b6=0,bQ=b3.percents.length;b6<bQ;b6++){if(b3.percents[b6]==b||b3.percents[b6]>b1*b3.top){b=b3.percents[b6];bU=b3.percents[b6-1]||0;bX=bX/b3.top*(b-bU);bV=b3.percents[b6+1];ca=b3.anim[b];break}else{if(b1){g.attr(b3.anim[b3.percents[b6]])}}}if(!ca){return}if(!S){for(var bZ in ca){if(ca[ak](bZ)){if(ar[ak](bZ)||g.paper.customAttributes[ak](bZ)){b2[bZ]=g.attr(bZ);(b2[bZ]==null)&&(b2[bZ]=r[bZ]);E[bZ]=ca[bZ];switch(ar[bZ]){case aL:bR[bZ]=(E[bZ]-b2[bZ])/bX;break;case"colour":b2[bZ]=aR.getRGB(b2[bZ]);var b0=aR.getRGB(E[bZ]);bR[bZ]={r:(b0.r-b2[bZ].r)/bX,g:(b0.g-b2[bZ].g)/bX,b:(b0.b-b2[bZ].b)/bX};break;case"path":var bM=W(b2[bZ],E[bZ]),bT=bM[1];b2[bZ]=bM[0];bR[bZ]=[];for(b6=0,bQ=b2[bZ].length;b6<bQ;b6++){bR[bZ][b6]=[0];for(var b5=1,b7=b2[bZ][b6].length;b5<b7;b5++){bR[bZ][b6][b5]=(bT[b6][b5]-b2[bZ][b6][b5])/bX}}break;case"transform":var cd=g._,cc=aB(cd[bZ],E[bZ]);if(cc){b2[bZ]=cc.from;E[bZ]=cc.to;bR[bZ]=[];bR[bZ].real=true;for(b6=0,bQ=b2[bZ].length;b6<bQ;b6++){bR[bZ][b6]=[b2[bZ][b6][0]];for(b5=1,b7=b2[bZ][b6].length;b5<b7;b5++){bR[bZ][b6][b5]=(E[bZ][b6][b5]-b2[bZ][b6][b5])/bX}}}else{var bY=(g.matrix||new aF),b9={_:{transform:cd.transform},getBBox:function(){return g.getBBox(1)}};b2[bZ]=[bY.a,bY.b,bY.c,bY.d,bY.e,bY.f];aO(b9,E[bZ]);E[bZ]=b9._.transform;bR[bZ]=[(b9.matrix.a-bY.a)/bX,(b9.matrix.b-bY.b)/bX,(b9.matrix.c-bY.c)/bX,(b9.matrix.d-bY.d)/bX,(b9.matrix.e-bY.e)/bX,(b9.matrix.f-bY.f)/bX]}break;case"csv":var d=bH(ca[bZ])[F](a),bN=bH(b2[bZ])[F](a);if(bZ=="clip-rect"){b2[bZ]=bN;bR[bZ]=[];b6=bN.length;while(b6--){bR[bZ][b6]=(d[b6]-b2[bZ][b6])/bX}}E[bZ]=d;break;default:d=[][bE](ca[bZ]);bN=[][bE](b2[bZ]);bR[bZ]=[];b6=g.paper.customAttributes[bZ].length;while(b6--){bR[bZ][b6]=((d[b6]||0)-(bN[b6]||0))/bX}break}}}}var bW=ca.easing,b4=aR.easing_formulas[bW];if(!b4){b4=bH(bW).match(c);if(b4&&b4.length==5){var bS=b4;b4=function(i){return a3(i,+bS[1],+bS[2],+bS[3],+bS[4],bX)}}else{b4=bB}}R=ca.start||b3.start||+new Date;b8={anim:b3,percent:b,timestamp:R,start:R+(b3.del||0),status:0,initstatus:b1||0,stop:false,ms:bX,easing:b4,from:b2,diff:bR,to:E,el:g,callback:ca.callback,prev:bU,next:bV,repeat:bP||b3.times,origin:g.attr(),totalOrigin:bL};ab.push(b8);if(b1&&!S&&!bO){b8.stop=true;b8.start=new Date-bX*b1;if(ab.length==1){return bC()}}if(bO){b8.start=new Date-b8.ms*b1}ab.length==1&&aN(bC)}else{S.initstatus=b1;S.start=new Date-S.ms*b1}eve("raphael.anim.start."+g.id,g,b3)}aR.animation=function(E,d,S,R){if(E instanceof bA){return E}if(aR.is(S,"function")||!S){R=R||S||null;S=null}E=Object(E);d=+d||0;var i={},g,b;for(b in E){if(E[ak](b)&&an(b)!=b&&an(b)+"%"!=b){g=true;i[b]=E[b]}}if(!g){return new bA(E,d)}else{S&&(i.easing=S);R&&(i.callback=R);return new bA({100:i},d)}};bh.animate=function(i,b,R,E){var d=this;if(d.removed){E&&E.call(d);return d}var g=i instanceof bA?i:aR.animation(i,b,R,E);aM(g,d,g.percents[0],null,d.attr());return d};bh.setTime=function(d,b){if(d&&b!=null){this.status(d,bm(b,d.ms)/d.ms)}return this};bh.status=function(R,E){var d=[],g=0,b,S;if(E!=null){aM(R,this,-1,bm(E,1));return this}else{b=ab.length;for(;g<b;g++){S=ab[g];if(S.el.id==this.id&&(!R||S.anim==R)){if(R){return S.status}d.push({anim:S.anim,status:S.status})}}if(R){return 0}return d}};bh.pause=function(d){for(var b=0;b<ab.length;b++){if(ab[b].el.id==this.id&&(!d||ab[b].anim==d)){if(eve("raphael.anim.pause."+this.id,this,ab[b].anim)!==false){ab[b].paused=true}}}return this};bh.resume=function(d){for(var b=0;b<ab.length;b++){if(ab[b].el.id==this.id&&(!d||ab[b].anim==d)){var g=ab[b];if(eve("raphael.anim.resume."+this.id,this,g.anim)!==false){delete g.paused;this.status(g.anim,g.status)}}}return this};bh.stop=function(d){for(var b=0;b<ab.length;b++){if(ab[b].el.id==this.id&&(!d||ab[b].anim==d)){if(eve("raphael.anim.stop."+this.id,this,ab[b].anim)!==false){ab.splice(b--,1)}}}return this};function aa(d){for(var b=0;b<ab.length;b++){if(ab[b].el.paper==d){ab.splice(b--,1)}}}eve.on("raphael.remove",aa);eve.on("raphael.clear",aa);bh.toString=function(){return"Rapha\xebl\u2019s object"};var al=function(b){this.items=[];this.length=0;this.type="set";if(b){for(var d=0,g=b.length;d<g;d++){if(b[d]&&(b[d].constructor==bh.constructor||b[d].constructor==al)){this[this.items.length]=this.items[this.items.length]=b[d];this.length++}}}},bc=al.prototype;bc.push=function(){var E,b;for(var d=0,g=arguments.length;d<g;d++){E=arguments[d];if(E&&(E.constructor==bh.constructor||E.constructor==al)){b=this.items.length;this[b]=this.items[b]=E;this.length++}}return this};bc.pop=function(){this.length&&delete this[this.length--];return this.items.pop()};bc.forEach=function(E,b){for(var d=0,g=this.items.length;d<g;d++){if(E.call(b,this.items[d],d)===false){return this}}return this};for(var B in bh){if(bh[ak](B)){bc[B]=(function(b){return function(){var d=arguments;return this.forEach(function(g){g[b][bG](g,d)})}})(B)}}bc.attr=function(d,S){if(d&&aR.is(d,bd)&&aR.is(d[0],"object")){for(var b=0,R=d.length;b<R;b++){this.items[b].attr(d[b])}}else{for(var g=0,E=this.items.length;g<E;g++){this.items[g].attr(d,S)}}return this};bc.clear=function(){while(this.length){this.pop()}};bc.splice=function(E,bL,bM){E=E<0?m(this.length+E,0):E;bL=m(0,bm(this.length-E,bL));var g=[],b=[],d=[],R;for(R=2;R<arguments.length;R++){d.push(arguments[R])}for(R=0;R<bL;R++){b.push(this[E+R])}for(;R<this.length-E;R++){g.push(this[E+R])}var S=d.length;for(R=0;R<S+g.length;R++){this.items[E+R]=this[E+R]=R<S?d[R]:g[R-S]}R=this.items.length=this.length-=bL-S;while(this[R]){delete this[R++]}return new al(b)};bc.exclude=function(g){for(var b=0,d=this.length;b<d;b++){if(this[b]==g){this.splice(b,1);return true}}};bc.animate=function(g,b,bL,bN){(aR.is(bL,"function")||!bL)&&(bN=bL||null);var S=this.items.length,E=S,bO,bM=this,R;if(!S){return this}bN&&(R=function(){!--S&&bN.call(bM)});bL=aR.is(bL,aj)?bL:R;var d=aR.animation(g,b,bL,R);bO=this.items[--E].animate(d);while(E--){this.items[E]&&!this.items[E].removed&&this.items[E].animateWith(bO,d,d)}return this};bc.insertAfter=function(d){var b=this.items.length;while(b--){this.items[b].insertAfter(d)}return this};bc.getBBox=function(){var b=[],S=[],d=[],E=[];for(var g=this.items.length;g--;){if(!this.items[g].removed){var R=this.items[g].getBBox();b.push(R.x);S.push(R.y);d.push(R.x+R.width);E.push(R.y+R.height)}}b=bm[bG](0,b);S=bm[bG](0,S);d=m[bG](0,d);E=m[bG](0,E);return{x:b,y:S,x2:d,y2:E,width:d-b,height:E-S}};bc.clone=function(g){g=new al;for(var b=0,d=this.items.length;b<d;b++){g.push(this.items[b].clone())}return g};bc.toString=function(){return"Rapha\xebl\u2018s set"};aR.registerFont=function(d){if(!d.face){return d}this.fonts=this.fonts||{};var i={w:d.w,face:{},glyphs:{}},g=d.face["font-family"];for(var S in d.face){if(d.face[ak](S)){i.face[S]=d.face[S]}}if(this.fonts[g]){this.fonts[g].push(i)}else{this.fonts[g]=[i]}if(!d.svg){i.face["units-per-em"]=U(d.face["units-per-em"],10);for(var E in d.glyphs){if(d.glyphs[ak](E)){var R=d.glyphs[E];i.glyphs[E]={w:R.w,k:{},d:R.d&&"M"+R.d.replace(/[mlcxtrv]/g,function(bL){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[bL]||"M"})+"z"};if(R.k){for(var b in R.k){if(R[ak](b)){i.glyphs[E].k[b]=R.k[b]}}}}}}return d};a4.getFont=function(bM,bN,d,E){E=E||"normal";d=d||"normal";bN=+bN||{normal:400,bold:700,lighter:300,bolder:800}[bN]||400;if(!aR.fonts){return}var R=aR.fonts[bM];if(!R){var g=new RegExp("(^|\\s)"+bM.replace(/[^\w\d\s+!~.:_-]/g,aX)+"(\\s|$)","i");for(var b in aR.fonts){if(aR.fonts[ak](b)){if(g.test(b)){R=aR.fonts[b];break}}}}var S;if(R){for(var bL=0,bO=R.length;bL<bO;bL++){S=R[bL];if(S.face["font-weight"]==bN&&(S.face["font-style"]==d||!S.face["font-style"])&&S.face["font-stretch"]==E){break}}}return S};a4.print=function(bL,S,b,bO,bP,bY,d){bY=bY||"middle";d=m(bm(d||0,1),-1);var bX=bH(b)[F](aX),bU=0,bW=0,bS=aX,bZ;aR.is(bO,b)&&(bO=this.getFont(bO));if(bO){bZ=(bP||16)/bO.face["units-per-em"];var E=bO.face.bbox[F](a),bN=+E[0],g=E[3]-E[1],R=0,bQ=+E[1]+(bY=="baseline"?g+(+bO.face.descent):g/2);for(var bT=0,bM=bX.length;bT<bM;bT++){if(bX[bT]=="\n"){bU=0;bV=0;bW=0;R+=g}else{var bR=bW&&bO.glyphs[bX[bT-1]]||{},bV=bO.glyphs[bX[bT]];bU+=bW?(bR.w||bO.w)+(bR.k&&bR.k[bX[bT]]||0)+(bO.w*d):0;bW=1}if(bV&&bV.d){bS+=aR.transformPath(bV.d,["t",bU*bZ,R*bZ,"s",bZ,bZ,bN,bQ,"t",(bL-bN)/bZ,(S-bQ)/bZ])}}}return this.path(bS).attr({fill:"#000",stroke:"none"})};a4.add=function(E){if(aR.is(E,"array")){var g=this.set(),d=0,R=E.length,b;for(;d<R;d++){b=E[d]||{};bw[ak](b.type)&&g.push(this[b.type]().attr(b))}}return g};aR.format=function(d,g){var b=aR.is(g,bd)?[0][bE](g):arguments;d&&aR.is(d,aj)&&b.length-1&&(d=d.replace(br,function(R,E){return b[++E]==null?aX:b[E]}));return d||aX};aR.fullfill=(function(){var g=/\{([^\}]+)\}/g,b=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,d=function(R,E,S){var i=S;E.replace(b,function(bN,bM,bL,bP,bO){bM=bM||bP;if(i){if(bM in i){i=i[bM]}typeof i=="function"&&bO&&(i=i())}});i=(i==null||i==S?R:i)+"";return i};return function(E,i){return String(E).replace(g,function(S,R){return d(S,R,i)})}})();aR.ninja=function(){s.was?(aA.win.Raphael=s.is):delete Raphael;return aR};aR.st=bc;(function(i,d,g){if(i.readyState==null&&i.addEventListener){i.addEventListener(d,g=function(){i.removeEventListener(d,g,false);i.readyState="complete"},false);i.readyState="loading"}function b(){(/in/).test(i.readyState)?setTimeout(b,9):aR.eve("raphael.DOMload")}b()})(document,"DOMContentLoaded");s.was?(aA.win.Raphael=aR):(Raphael=aR);eve.on("raphael.DOMload",function(){ao=true})})();window.Raphael&&window.Raphael.svg&&function(l){var d="hasOwnProperty",B=String,n=parseFloat,q=parseInt,f=Math,C=f.max,s=f.abs,h=f.pow,g=/[, ]+/,z=l.eve,r="",j=" ";var o="http://www.w3.org/1999/xlink",y={block:"M5,0 0,2.5 5,5z",classic:"M5,0 0,2.5 5,5 3.5,3 3.5,2z",diamond:"M2.5,0 5,2.5 2.5,5 0,2.5z",open:"M6,1 1,3.5 6,6",oval:"M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"},u={};l.toString=function(){return"Your browser supports SVG.\nYou are running Rapha\xebl "+this.version};var i=function(F,D){if(D){if(typeof F=="string"){F=i(F)}for(var E in D){if(D[d](E)){if(E.substring(0,6)=="xlink:"){F.setAttributeNS(o,E.substring(6),B(D[E]))}else{F.setAttribute(E,B(D[E]))}}}}else{F=l._g.doc.createElementNS("http://www.w3.org/2000/svg",F);F.style&&(F.style.webkitTapHighlightColor="rgba(0,0,0,0)")}return F},a=function(M,Q){var O="linear",E=M.id+Q,K=0.5,I=0.5,G=M.node,D=M.paper,S=G.style,F=l._g.doc.getElementById(E);if(!F){Q=B(Q).replace(l._radial_gradient,function(V,T,W){O="radial";if(T&&W){K=n(T);I=n(W);var U=((I>0.5)*2-1);h(K-0.5,2)+h(I-0.5,2)>0.25&&(I=f.sqrt(0.25-h(K-0.5,2))*U+0.5)&&I!=0.5&&(I=I.toFixed(5)-0.00001*U)}return r});Q=Q.split(/\s*\-\s*/);if(O=="linear"){var J=Q.shift();J=-n(J);if(isNaN(J)){return null}var H=[0,0,f.cos(l.rad(J)),f.sin(l.rad(J))],P=1/(C(s(H[2]),s(H[3]))||1);H[2]*=P;H[3]*=P;if(H[2]<0){H[0]=-H[2];H[2]=0}if(H[3]<0){H[1]=-H[3];H[3]=0}}var N=l._parseDots(Q);if(!N){return null}E=E.replace(/[\(\)\s,\xb0#]/g,"_");if(M.gradient&&E!=M.gradient.id){D.defs.removeChild(M.gradient);delete M.gradient}if(!M.gradient){F=i(O+"Gradient",{id:E});M.gradient=F;i(F,O=="radial"?{fx:K,fy:I}:{x1:H[0],y1:H[1],x2:H[2],y2:H[3],gradientTransform:M.matrix.invert()});D.defs.appendChild(F);for(var L=0,R=N.length;L<R;L++){F.appendChild(i("stop",{offset:N[L].offset?N[L].offset:L?"100%":"0%","stop-color":N[L].color||"#fff"}))}}}i(G,{fill:"url(#"+E+")",opacity:1,"fill-opacity":1});S.fill=r;S.opacity=1;S.fillOpacity=1;return 1},b=function(E){var D=E.getBBox(1);i(E.pattern,{patternTransform:E.matrix.invert()+" translate("+D.x+","+D.y+")"})},c=function(O,Q,J){if(O.type=="path"){var D=B(Q).toLowerCase().split("-"),N=O.paper,ab=J?"end":"start",S=O.node,P=O.attrs,I=P["stroke-width"],W=D.length,G="classic",V,F,L,T,R,K=3,X=3,M=5;while(W--){switch(D[W]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":G=D[W];break;case"wide":X=5;break;case"narrow":X=2;break;case"long":K=5;break;case"short":K=2;break}}if(G=="open"){K+=2;X+=2;M+=2;L=1;T=J?4:1;R={fill:"none",stroke:P.stroke}}else{T=L=K/2;R={fill:P.stroke,stroke:"none"}}if(O._.arrows){if(J){O._.arrows.endPath&&u[O._.arrows.endPath]--;O._.arrows.endMarker&&u[O._.arrows.endMarker]--}else{O._.arrows.startPath&&u[O._.arrows.startPath]--;O._.arrows.startMarker&&u[O._.arrows.startMarker]--}}else{O._.arrows={}}if(G!="none"){var E="raphael-marker-"+G,aa="raphael-marker-"+ab+G+K+X;if(!l._g.doc.getElementById(E)){N.defs.appendChild(i(i("path"),{"stroke-linecap":"round",d:y[G],id:E}));u[E]=1}else{u[E]++}var H=l._g.doc.getElementById(aa),U;if(!H){H=i(i("marker"),{id:aa,markerHeight:X,markerWidth:K,orient:"auto",refX:T,refY:X/2});U=i(i("use"),{"xlink:href":"#"+E,transform:(J?"rotate(180 "+K/2+" "+X/2+") ":r)+"scale("+K/M+","+X/M+")","stroke-width":(1/((K/M+X/M)/2)).toFixed(4)});H.appendChild(U);N.defs.appendChild(H);u[aa]=1}else{u[aa]++;U=H.getElementsByTagName("use")[0]}i(U,R);var Z=L*(G!="diamond"&&G!="oval");if(J){V=O._.arrows.startdx*I||0;F=l.getTotalLength(P.path)-Z*I}else{V=Z*I;F=l.getTotalLength(P.path)-(O._.arrows.enddx*I||0)}R={};R["marker-"+ab]="url(#"+aa+")";if(F||V){R.d=Raphael.getSubpath(P.path,V,F)}i(S,R);O._.arrows[ab+"Path"]=E;O._.arrows[ab+"Marker"]=aa;O._.arrows[ab+"dx"]=Z;O._.arrows[ab+"Type"]=G;O._.arrows[ab+"String"]=Q}else{if(J){V=O._.arrows.startdx*I||0;F=l.getTotalLength(P.path)-V}else{V=0;F=l.getTotalLength(P.path)-(O._.arrows.enddx*I||0)}O._.arrows[ab+"Path"]&&i(S,{d:Raphael.getSubpath(P.path,V,F)});delete O._.arrows[ab+"Path"];delete O._.arrows[ab+"Marker"];delete O._.arrows[ab+"dx"];delete O._.arrows[ab+"Type"];delete O._.arrows[ab+"String"]}for(R in u){if(u[d](R)&&!u[R]){var Y=l._g.doc.getElementById(R);Y&&Y.parentNode.removeChild(Y)}}}},v={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},k=function(J,H,I){H=v[B(H).toLowerCase()];if(H){var F=J.attrs["stroke-width"]||"1",D={round:F,square:F,butt:0}[J.attrs["stroke-linecap"]||I["stroke-linecap"]]||0,G=[],E=H.length;while(E--){G[E]=H[E]*F+((E%2)?1:-1)*D}i(J.node,{"stroke-dasharray":G.join(",")})}},w=function(O,W){var S=O.node,P=O.attrs,M=S.style.visibility;S.style.visibility="hidden";for(var R in W){if(W[d](R)){if(!l._availableAttrs[d](R)){continue}var Q=W[R];P[R]=Q;switch(R){case"blur":O.blur(Q);break;case"href":case"title":case"target":var U=S.parentNode;if(U.tagName.toLowerCase()!="a"){var H=i("a");U.insertBefore(H,S);H.appendChild(S);U=H}if(R=="target"){U.setAttributeNS(o,"show",Q=="blank"?"new":Q)}else{U.setAttributeNS(o,R,Q)}break;case"cursor":S.style.cursor=Q;break;case"transform":O.transform(Q);break;case"arrow-start":c(O,Q);break;case"arrow-end":c(O,Q,1);break;case"clip-rect":var E=B(Q).split(g);if(E.length==4){O.clip&&O.clip.parentNode.parentNode.removeChild(O.clip.parentNode);var F=i("clipPath"),T=i("rect");F.id=l.createUUID();i(T,{x:E[0],y:E[1],width:E[2],height:E[3]});F.appendChild(T);O.paper.defs.appendChild(F);i(S,{"clip-path":"url(#"+F.id+")"});O.clip=T}if(!Q){var N=S.getAttribute("clip-path");if(N){var V=l._g.doc.getElementById(N.replace(/(^url\(#|\)$)/g,r));V&&V.parentNode.removeChild(V);i(S,{"clip-path":r});delete O.clip}}break;case"path":if(O.type=="path"){i(S,{d:Q?P.path=l._pathToAbsolute(Q):"M0,0"});O._.dirty=1;if(O._.arrows){"startString" in O._.arrows&&c(O,O._.arrows.startString);"endString" in O._.arrows&&c(O,O._.arrows.endString,1)}}break;case"width":S.setAttribute(R,Q);O._.dirty=1;if(P.fx){R="x";Q=P.x}else{break}case"x":if(P.fx){Q=-P.x-(P.width||0)}case"rx":if(R=="rx"&&O.type=="rect"){break}case"cx":S.setAttribute(R,Q);O.pattern&&b(O);O._.dirty=1;break;case"height":S.setAttribute(R,Q);O._.dirty=1;if(P.fy){R="y";Q=P.y}else{break}case"y":if(P.fy){Q=-P.y-(P.height||0)}case"ry":if(R=="ry"&&O.type=="rect"){break}case"cy":S.setAttribute(R,Q);O.pattern&&b(O);O._.dirty=1;break;case"r":if(O.type=="rect"){i(S,{rx:Q,ry:Q})}else{S.setAttribute(R,Q)}O._.dirty=1;break;case"src":if(O.type=="image"){S.setAttributeNS(o,"href",Q)}break;case"stroke-width":if(O._.sx!=1||O._.sy!=1){Q/=C(s(O._.sx),s(O._.sy))||1}if(O.paper._vbSize){Q*=O.paper._vbSize}S.setAttribute(R,Q);if(P["stroke-dasharray"]){k(O,P["stroke-dasharray"],W)}if(O._.arrows){"startString" in O._.arrows&&c(O,O._.arrows.startString);"endString" in O._.arrows&&c(O,O._.arrows.endString,1)}break;case"stroke-dasharray":k(O,Q,W);break;case"fill":var I=B(Q).match(l._ISURL);if(I){F=i("pattern");var L=i("image");F.id=l.createUUID();i(F,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1});i(L,{x:0,y:0,"xlink:href":I[1]});F.appendChild(L);(function(X){l._preload(I[1],function(){var Y=this.offsetWidth,Z=this.offsetHeight;i(X,{width:Y,height:Z});i(L,{width:Y,height:Z});O.paper.safari()})})(F);O.paper.defs.appendChild(F);i(S,{fill:"url(#"+F.id+")"});O.pattern=F;O.pattern&&b(O);break}var G=l.getRGB(Q);if(!G.error){delete W.gradient;delete P.gradient;!l.is(P.opacity,"undefined")&&l.is(W.opacity,"undefined")&&i(S,{opacity:P.opacity});!l.is(P["fill-opacity"],"undefined")&&l.is(W["fill-opacity"],"undefined")&&i(S,{"fill-opacity":P["fill-opacity"]})}else{if((O.type=="circle"||O.type=="ellipse"||B(Q).charAt()!="r")&&a(O,Q)){if("opacity" in P||"fill-opacity" in P){var D=l._g.doc.getElementById(S.getAttribute("fill").replace(/^url\(#|\)$/g,r));if(D){var J=D.getElementsByTagName("stop");i(J[J.length-1],{"stop-opacity":("opacity" in P?P.opacity:1)*("fill-opacity" in P?P["fill-opacity"]:1)})}}P.gradient=Q;P.fill="none";break}}G[d]("opacity")&&i(S,{"fill-opacity":G.opacity>1?G.opacity/100:G.opacity});case"stroke":G=l.getRGB(Q);S.setAttribute(R,G.hex);R=="stroke"&&G[d]("opacity")&&i(S,{"stroke-opacity":G.opacity>1?G.opacity/100:G.opacity});if(R=="stroke"&&O._.arrows){"startString" in O._.arrows&&c(O,O._.arrows.startString);"endString" in O._.arrows&&c(O,O._.arrows.endString,1)}break;case"gradient":(O.type=="circle"||O.type=="ellipse"||B(Q).charAt()!="r")&&a(O,Q);break;case"opacity":if(P.gradient&&!P[d]("stroke-opacity")){i(S,{"stroke-opacity":Q>1?Q/100:Q})}case"fill-opacity":if(P.gradient){D=l._g.doc.getElementById(S.getAttribute("fill").replace(/^url\(#|\)$/g,r));if(D){J=D.getElementsByTagName("stop");i(J[J.length-1],{"stop-opacity":Q})}break}default:R=="font-size"&&(Q=q(Q,10)+"px");var K=R.replace(/(\-.)/g,function(X){return X.substring(1).toUpperCase()});S.style[K]=Q;O._.dirty=1;S.setAttribute(R,Q);break}}}p(O,W);S.style.visibility=M},A=1.2,p=function(D,H){if(D.type!="text"||!(H[d]("text")||H[d]("font")||H[d]("font-size")||H[d]("x")||H[d]("y"))){return}var M=D.attrs,F=D.node,O=F.firstChild?q(l._g.doc.defaultView.getComputedStyle(F.firstChild,r).getPropertyValue("font-size"),10):10;if(H[d]("text")){M.text=H.text;while(F.firstChild){F.removeChild(F.firstChild)}var G=B(H.text).split("\n"),E=[],K;for(var I=0,N=G.length;I<N;I++){K=i("tspan");I&&i(K,{dy:O*A,x:M.x});K.appendChild(l._g.doc.createTextNode(G[I]));F.appendChild(K);E[I]=K}}else{E=F.getElementsByTagName("tspan");for(I=0,N=E.length;I<N;I++){if(I){i(E[I],{dy:O*A,x:M.x})}else{i(E[0],{dy:0})}}}i(F,{x:M.x,y:M.y});D._.dirty=1;var J=D._getBBox(),L=M.y-(J.y+J.height/2);L&&l.is(L,"finite")&&i(E[0],{dy:L})},t=function(E,D){var G=0,F=0;this[0]=this.node=E;E.raphael=true;this.id=l._oid++;E.raphaelid=this.id;this.matrix=l.matrix();this.realPath=null;this.paper=D;this.attrs=this.attrs||{};this._={transform:[],sx:1,sy:1,deg:0,dx:0,dy:0,dirty:1};!D.bottom&&(D.bottom=this);this.prev=D.top;D.top&&(D.top.next=this);D.top=this;this.next=null},m=l.el;t.prototype=m;m.constructor=t;l._engine.path=function(D,G){var E=i("path");G.canvas&&G.canvas.appendChild(E);var F=new t(E,G);F.type="path";w(F,{fill:"none",stroke:"#000",path:D});return F};m.rotate=function(E,D,G){if(this.removed){return this}E=B(E).split(g);if(E.length-1){D=n(E[1]);G=n(E[2])}E=n(E[0]);(G==null)&&(D=G);if(D==null||G==null){var F=this.getBBox(1);D=F.x+F.width/2;G=F.y+F.height/2}this.transform(this._.transform.concat([["r",E,D,G]]));return this};m.scale=function(H,F,D,G){if(this.removed){return this}H=B(H).split(g);if(H.length-1){F=n(H[1]);D=n(H[2]);G=n(H[3])}H=n(H[0]);(F==null)&&(F=H);(G==null)&&(D=G);if(D==null||G==null){var E=this.getBBox(1)}D=D==null?E.x+E.width/2:D;G=G==null?E.y+E.height/2:G;this.transform(this._.transform.concat([["s",H,F,D,G]]));return this};m.translate=function(E,D){if(this.removed){return this}E=B(E).split(g);if(E.length-1){D=n(E[1])}E=n(E[0])||0;D=+D||0;this.transform(this._.transform.concat([["t",E,D]]));return this};m.transform=function(E){var F=this._;if(E==null){return F.transform}l._extractTransform(this,E);this.clip&&i(this.clip,{transform:this.matrix.invert()});this.pattern&&b(this);this.node&&i(this.node,{transform:this.matrix});if(F.sx!=1||F.sy!=1){var D=this.attrs[d]("stroke-width")?this.attrs["stroke-width"]:1;this.attr({"stroke-width":D})}return this};m.hide=function(){!this.removed&&this.paper.safari(this.node.style.display="none");return this};m.show=function(){!this.removed&&this.paper.safari(this.node.style.display="");return this};m.remove=function(){if(this.removed||!this.node.parentNode){return}var E=this.paper;E.__set__&&E.__set__.exclude(this);z.unbind("raphael.*.*."+this.id);if(this.gradient){E.defs.removeChild(this.gradient)}l._tear(this,E);if(this.node.parentNode.tagName.toLowerCase()=="a"){this.node.parentNode.parentNode.removeChild(this.node.parentNode)}else{this.node.parentNode.removeChild(this.node)}for(var D in this){this[D]=typeof this[D]=="function"?l._removedFactory(D):null}this.removed=true};m._getBBox=function(){if(this.node.style.display=="none"){this.show();var D=true}var F={};try{F=this.node.getBBox()}catch(E){}finally{F=F||{}}D&&this.hide();return F};m.attr=function(D,M){if(this.removed){return this}if(D==null){var J={};for(var L in this.attrs){if(this.attrs[d](L)){J[L]=this.attrs[L]}}J.gradient&&J.fill=="none"&&(J.fill=J.gradient)&&delete J.gradient;J.transform=this._.transform;return J}if(M==null&&l.is(D,"string")){if(D=="fill"&&this.attrs.fill=="none"&&this.attrs.gradient){return this.attrs.gradient}if(D=="transform"){return this._.transform}var K=D.split(g),G={};for(var H=0,O=K.length;H<O;H++){D=K[H];if(D in this.attrs){G[D]=this.attrs[D]}else{if(l.is(this.paper.customAttributes[D],"function")){G[D]=this.paper.customAttributes[D].def}else{G[D]=l._availableAttrs[D]}}}return O-1?G:G[K[0]]}if(M==null&&l.is(D,"array")){G={};for(H=0,O=D.length;H<O;H++){G[D[H]]=this.attr(D[H])}return G}if(M!=null){var E={};E[D]=M}else{if(D!=null&&l.is(D,"object")){E=D}}for(var N in E){z("raphael.attr."+N+"."+this.id,this,E[N])}for(N in this.paper.customAttributes){if(this.paper.customAttributes[d](N)&&E[d](N)&&l.is(this.paper.customAttributes[N],"function")){var I=this.paper.customAttributes[N].apply(this,[].concat(E[N]));this.attrs[N]=E[N];for(var F in I){if(I[d](F)){E[F]=I[F]}}}}w(this,E);return this};m.toFront=function(){if(this.removed){return this}if(this.node.parentNode.tagName.toLowerCase()=="a"){this.node.parentNode.parentNode.appendChild(this.node.parentNode)}else{this.node.parentNode.appendChild(this.node)}var D=this.paper;D.top!=this&&l._tofront(this,D);return this};m.toBack=function(){if(this.removed){return this}var E=this.node.parentNode;if(E.tagName.toLowerCase()=="a"){E.parentNode.insertBefore(this.node.parentNode,this.node.parentNode.parentNode.firstChild)}else{if(E.firstChild!=this.node){E.insertBefore(this.node,this.node.parentNode.firstChild)}}l._toback(this,this.paper);var D=this.paper;return this};m.insertAfter=function(D){if(this.removed){return this}var E=D.node||D[D.length-1].node;if(E.nextSibling){E.parentNode.insertBefore(this.node,E.nextSibling)}else{E.parentNode.appendChild(this.node)}l._insertafter(this,D,this.paper);return this};m.insertBefore=function(D){if(this.removed){return this}var E=D.node||D[0].node;E.parentNode.insertBefore(this.node,E);l._insertbefore(this,D,this.paper);return this};m.blur=function(E){var D=this;if(+E!==0){var F=i("filter"),G=i("feGaussianBlur");D.attrs.blur=E;F.id=l.createUUID();i(G,{stdDeviation:+E||1.5});F.appendChild(G);D.paper.defs.appendChild(F);D._blur=F;i(D.node,{filter:"url(#"+F.id+")"})}else{if(D._blur){D._blur.parentNode.removeChild(D._blur);delete D._blur;delete D.attrs.blur}D.node.removeAttribute("filter")}};l._engine.circle=function(E,D,I,H){var G=i("circle");E.canvas&&E.canvas.appendChild(G);var F=new t(G,E);F.attrs={cx:D,cy:I,r:H,fill:"none",stroke:"#000"};F.type="circle";i(G,F.attrs);return F};l._engine.rect=function(F,D,K,E,I,J){var H=i("rect");F.canvas&&F.canvas.appendChild(H);var G=new t(H,F);G.attrs={x:D,y:K,width:E,height:I,r:J||0,rx:J||0,ry:J||0,fill:"none",stroke:"#000"};G.type="rect";i(H,G.attrs);return G};l._engine.ellipse=function(E,D,J,I,H){var G=i("ellipse");E.canvas&&E.canvas.appendChild(G);var F=new t(G,E);F.attrs={cx:D,cy:J,rx:I,ry:H,fill:"none",stroke:"#000"};F.type="ellipse";i(G,F.attrs);return F};l._engine.image=function(F,J,D,K,E,I){var H=i("image");i(H,{x:D,y:K,width:E,height:I,preserveAspectRatio:"none"});H.setAttributeNS(o,"href",J);F.canvas&&F.canvas.appendChild(H);var G=new t(H,F);G.attrs={x:D,y:K,width:E,height:I,src:J};G.type="image";return G};l._engine.text=function(E,D,I,H){var G=i("text");E.canvas&&E.canvas.appendChild(G);var F=new t(G,E);F.attrs={x:D,y:I,"text-anchor":"middle",text:H,font:l._availableAttrs.font,stroke:"none",fill:"#000"};F.type="text";w(F,F.attrs);return F};l._engine.setSize=function(E,D){this.width=E||this.width;this.height=D||this.height;this.canvas.setAttribute("width",this.width);this.canvas.setAttribute("height",this.height);if(this._viewBox){this.setViewBox.apply(this,this._viewBox)}return this};l._engine.create=function(){var G=l._getContainer.apply(0,arguments),E=G&&G.container,K=G.x,J=G.y,F=G.width,L=G.height;if(!E){throw new Error("SVG container not found.")}var D=i("svg"),I="overflow:hidden;",H;K=K||0;J=J||0;F=F||512;L=L||342;i(D,{height:L,version:1.1,width:F,xmlns:"http://www.w3.org/2000/svg"});if(E==1){D.style.cssText=I+"position:absolute;left:"+K+"px;top:"+J+"px";l._g.doc.body.appendChild(D);H=1}else{D.style.cssText=I+"position:relative";if(E.firstChild){E.insertBefore(D,E.firstChild)}else{E.appendChild(D)}}E=new l._Paper;E.width=F;E.height=L;E.canvas=D;E.clear();E._left=E._top=0;H&&(E.renderfix=function(){});E.renderfix();return E};l._engine.setViewBox=function(I,G,K,D,E){z("raphael.setViewBox",this,this._viewBox,[I,G,K,D,E]);var M=C(K/this.width,D/this.height),H=this.top,L=E?"meet":"xMinYMin",F,J;if(I==null){if(this._vbSize){M=1}delete this._vbSize;F="0 0 "+this.width+j+this.height}else{this._vbSize=M;F=I+j+G+j+K+j+D}i(this.canvas,{viewBox:F,preserveAspectRatio:L});while(M&&H){J="stroke-width" in H.attrs?H.attrs["stroke-width"]:1;H.attr({"stroke-width":J});H._.dirty=1;H._.dirtyT=1;H=H.prev}this._viewBox=[I,G,K,D,!!E];return this};l.prototype.renderfix=function(){var I=this.canvas,D=I.style,H;try{H=I.getScreenCTM()||I.createSVGMatrix()}catch(G){H=I.createSVGMatrix()}var F=-H.e%1,E=-H.f%1;if(F||E){if(F){this._left=(this._left+F)%1;D.left=this._left+"px"}if(E){this._top=(this._top+E)%1;D.top=this._top+"px"}}};l.prototype.clear=function(){l.eve("raphael.clear",this);var D=this.canvas;while(D.firstChild){D.removeChild(D.firstChild)}this.bottom=this.top=null;(this.desc=i("desc")).appendChild(l._g.doc.createTextNode("Created with Rapha\xebl "+l.version));D.appendChild(this.desc);D.appendChild(this.defs=i("defs"))};l.prototype.remove=function(){z("raphael.remove",this);this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var D in this){this[D]=typeof this[D]=="function"?l._removedFactory(D):null}};var x=l.st;for(var e in m){if(m[d](e)&&!x[d](e)){x[e]=(function(D){return function(){var E=arguments;return this.forEach(function(F){F[D].apply(F,E)})}})(e)}}}(window.Raphael);window.Raphael&&window.Raphael.vml&&function(l){var e="hasOwnProperty",F=String,n=parseFloat,h=Math,B=h.round,I=h.max,C=h.min,s=h.abs,v="fill",i=/[, ]+/,A=l.eve,w=" progid:DXImageTransform.Microsoft",k=" ",q="",D={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},j=/([clmz]),?([^clmz]*)/gi,t=/ progid:\S+Blur\([^\)]+\)/g,H=/-?[^,\s-]+/g,d="position:absolute;left:0;top:0;width:1px;height:1px",b=21600,z={path:1,rect:1,image:1},r={circle:1,ellipse:1},f=function(S){var P=/[ahqstv]/ig,K=l._pathToAbsolute;F(S).match(P)&&(K=l._path2curve);P=/[clmz]/g;if(K==l._pathToAbsolute&&!F(S).match(P)){var O=F(S).replace(j,function(W,Y,U){var X=[],T=Y.toLowerCase()=="m",V=D[Y];U.replace(H,function(Z){if(T&&X.length==2){V+=X+D[Y=="m"?"l":"L"];X=[]}X.push(B(Z*b))});return V+X});return O}var Q=K(S),J,E;O=[];for(var M=0,R=Q.length;M<R;M++){J=Q[M];E=Q[M][0].toLowerCase();E=="z"&&(E="x");for(var L=1,N=J.length;L<N;L++){E+=B(J[L]*b)+(L!=N-1?",":q)}O.push(E)}return O.join(k)},o=function(L,K,J){var E=l.matrix();E.rotate(-L,0.5,0.5);return{dx:E.x(K,J),dy:E.y(K,J)}},p=function(R,Q,P,M,L,N){var Z=R._,T=R.matrix,E=Z.fillpos,S=R.node,O=S.style,K=1,J="",V,X=b/Q,W=b/P;O.visibility="hidden";if(!Q||!P){return}S.coordsize=s(X)+k+s(W);O.rotation=N*(Q*P<0?-1:1);if(N){var Y=o(N,M,L);M=Y.dx;L=Y.dy}Q<0&&(J+="x");P<0&&(J+=" y")&&(K=-1);O.flip=J;S.coordorigin=(M*-X)+k+(L*-W);if(E||Z.fillsize){var U=S.getElementsByTagName(v);U=U&&U[0];S.removeChild(U);if(E){Y=o(N,T.x(E[0],E[1]),T.y(E[0],E[1]));U.position=Y.dx*K+k+Y.dy*K}if(Z.fillsize){U.size=Z.fillsize[0]*s(Q)+k+Z.fillsize[1]*s(P)}S.appendChild(U)}O.visibility="visible"};l.toString=function(){return"Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl "+this.version};var c=function(E,O,J){var Q=F(O).toLowerCase().split("-"),M=J?"end":"start",K=Q.length,N="classic",P="medium",L="medium";while(K--){switch(Q[K]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":N=Q[K];break;case"wide":case"narrow":L=Q[K];break;case"long":case"short":P=Q[K];break}}var R=E.node.getElementsByTagName("stroke")[0];R[M+"arrow"]=N;R[M+"arrowlength"]=P;R[M+"arrowwidth"]=L},x=function(Z,aj){Z.attrs=Z.attrs||{};var ae=Z.node,an=Z.attrs,V=ae.style,R,ah=z[Z.type]&&(aj.x!=an.x||aj.y!=an.y||aj.width!=an.width||aj.height!=an.height||aj.cx!=an.cx||aj.cy!=an.cy||aj.rx!=an.rx||aj.ry!=an.ry||aj.r!=an.r),Y=r[Z.type]&&(an.cx!=aj.cx||an.cy!=aj.cy||an.r!=aj.r||an.rx!=aj.rx||an.ry!=aj.ry),aq=Z;for(var W in aj){if(aj[e](W)){an[W]=aj[W]}}if(ah){an.path=l._getPath[Z.type](Z);Z._.dirty=1}aj.href&&(ae.href=aj.href);aj.title&&(ae.title=aj.title);aj.target&&(ae.target=aj.target);aj.cursor&&(V.cursor=aj.cursor);"blur" in aj&&Z.blur(aj.blur);if(aj.path&&Z.type=="path"||ah){ae.path=f(~F(an.path).toLowerCase().indexOf("r")?l._pathToAbsolute(an.path):an.path);if(Z.type=="image"){Z._.fillpos=[an.x,an.y];Z._.fillsize=[an.width,an.height];p(Z,1,1,0,0,0)}}"transform" in aj&&Z.transform(aj.transform);if(Y){var M=+an.cx,K=+an.cy,Q=+an.rx||+an.r||0,P=+an.ry||+an.r||0;ae.path=l.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x",B((M-Q)*b),B((K-P)*b),B((M+Q)*b),B((K+P)*b),B(M*b))}if("clip-rect" in aj){var J=F(aj["clip-rect"]).split(i);if(J.length==4){J[2]=+J[2]+(+J[0]);J[3]=+J[3]+(+J[1]);var X=ae.clipRect||l._g.doc.createElement("div"),ap=X.style;ap.clip=l.format("rect({1}px {2}px {3}px {0}px)",J);if(!ae.clipRect){ap.position="absolute";ap.top=0;ap.left=0;ap.width=Z.paper.width+"px";ap.height=Z.paper.height+"px";ae.parentNode.insertBefore(X,ae);X.appendChild(ae);ae.clipRect=X}}if(!aj["clip-rect"]){ae.clipRect&&(ae.clipRect.style.clip="auto")}}if(Z.textpath){var al=Z.textpath.style;aj.font&&(al.font=aj.font);aj["font-family"]&&(al.fontFamily='"'+aj["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g,q)+'"');aj["font-size"]&&(al.fontSize=aj["font-size"]);aj["font-weight"]&&(al.fontWeight=aj["font-weight"]);aj["font-style"]&&(al.fontStyle=aj["font-style"])}if("arrow-start" in aj){c(aq,aj["arrow-start"])}if("arrow-end" in aj){c(aq,aj["arrow-end"],1)}if(aj.opacity!=null||aj["stroke-width"]!=null||aj.fill!=null||aj.src!=null||aj.stroke!=null||aj["stroke-width"]!=null||aj["stroke-opacity"]!=null||aj["fill-opacity"]!=null||aj["stroke-dasharray"]!=null||aj["stroke-miterlimit"]!=null||aj["stroke-linejoin"]!=null||aj["stroke-linecap"]!=null){var af=ae.getElementsByTagName(v),am=false;af=af&&af[0];!af&&(am=af=G(v));if(Z.type=="image"&&aj.src){af.src=aj.src}aj.fill&&(af.on=true);if(af.on==null||aj.fill=="none"||aj.fill===null){af.on=false}if(af.on&&aj.fill){var O=F(aj.fill).match(l._ISURL);if(O){af.parentNode==ae&&ae.removeChild(af);af.rotate=true;af.src=O[1];af.type="tile";var E=Z.getBBox(1);af.position=E.x+k+E.y;Z._.fillpos=[E.x,E.y];l._preload(O[1],function(){Z._.fillsize=[this.offsetWidth,this.offsetHeight]})}else{af.color=l.getRGB(aj.fill).hex;af.src=q;af.type="solid";if(l.getRGB(aj.fill).error&&(aq.type in {circle:1,ellipse:1}||F(aj.fill).charAt()!="r")&&a(aq,aj.fill,af)){an.fill="none";an.gradient=aj.fill;af.rotate=false}}}if("fill-opacity" in aj||"opacity" in aj){var N=((+an["fill-opacity"]+1||2)-1)*((+an.opacity+1||2)-1)*((+l.getRGB(aj.fill).o+1||2)-1);N=C(I(N,0),1);af.opacity=N;if(af.src){af.color="none"}}ae.appendChild(af);var S=(ae.getElementsByTagName("stroke")&&ae.getElementsByTagName("stroke")[0]),ao=false;!S&&(ao=S=G("stroke"));if((aj.stroke&&aj.stroke!="none")||aj["stroke-width"]||aj["stroke-opacity"]!=null||aj["stroke-dasharray"]||aj["stroke-miterlimit"]||aj["stroke-linejoin"]||aj["stroke-linecap"]){S.on=true}(aj.stroke=="none"||aj.stroke===null||S.on==null||aj.stroke==0||aj["stroke-width"]==0)&&(S.on=false);var ad=l.getRGB(aj.stroke);S.on&&aj.stroke&&(S.color=ad.hex);N=((+an["stroke-opacity"]+1||2)-1)*((+an.opacity+1||2)-1)*((+ad.o+1||2)-1);var aa=(n(aj["stroke-width"])||1)*0.75;N=C(I(N,0),1);aj["stroke-width"]==null&&(aa=an["stroke-width"]);aj["stroke-width"]&&(S.weight=aa);aa&&aa<1&&(N*=aa)&&(S.weight=1);S.opacity=N;aj["stroke-linejoin"]&&(S.joinstyle=aj["stroke-linejoin"]||"miter");S.miterlimit=aj["stroke-miterlimit"]||8;aj["stroke-linecap"]&&(S.endcap=aj["stroke-linecap"]=="butt"?"flat":aj["stroke-linecap"]=="square"?"square":"round");if(aj["stroke-dasharray"]){var ac={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};S.dashstyle=ac[e](aj["stroke-dasharray"])?ac[aj["stroke-dasharray"]]:q}ao&&ae.appendChild(S)}if(aq.type=="text"){aq.paper.canvas.style.display=q;var ag=aq.paper.span,ab=100,L=an.font&&an.font.match(/\d+(?:\.\d*)?(?=px)/);V=ag.style;an.font&&(V.font=an.font);an["font-family"]&&(V.fontFamily=an["font-family"]);an["font-weight"]&&(V.fontWeight=an["font-weight"]);an["font-style"]&&(V.fontStyle=an["font-style"]);L=n(an["font-size"]||L&&L[0])||10;V.fontSize=L*ab+"px";aq.textpath.string&&(ag.innerHTML=F(aq.textpath.string).replace(/</g,"&#60;").replace(/&/g,"&#38;").replace(/\n/g,"<br>"));var U=ag.getBoundingClientRect();aq.W=an.w=(U.right-U.left)/ab;aq.H=an.h=(U.bottom-U.top)/ab;aq.X=an.x;aq.Y=an.y+aq.H/2;("x" in aj||"y" in aj)&&(aq.path.v=l.format("m{0},{1}l{2},{1}",B(an.x*b),B(an.y*b),B(an.x*b)+1));var T=["x","y","text","font","font-family","font-weight","font-style","font-size"];for(var ai=0,ak=T.length;ai<ak;ai++){if(T[ai] in aj){aq._.dirty=1;break}}switch(an["text-anchor"]){case"start":aq.textpath.style["v-text-align"]="left";aq.bbx=aq.W/2;break;case"end":aq.textpath.style["v-text-align"]="right";aq.bbx=-aq.W/2;break;default:aq.textpath.style["v-text-align"]="center";aq.bbx=0;break}aq.textpath.style["v-text-kern"]=true}},a=function(E,R,U){E.attrs=E.attrs||{};var S=E.attrs,L=Math.pow,M,N,P="linear",Q=".5 .5";E.attrs.gradient=R;R=F(R).replace(l._radial_gradient,function(X,Y,W){P="radial";if(Y&&W){Y=n(Y);W=n(W);L(Y-0.5,2)+L(W-0.5,2)>0.25&&(W=h.sqrt(0.25-L(Y-0.5,2))*((W>0.5)*2-1)+0.5);Q=Y+k+W}return q});R=R.split(/\s*\-\s*/);if(P=="linear"){var J=R.shift();J=-n(J);if(isNaN(J)){return null}}var O=l._parseDots(R);if(!O){return null}E=E.shape||E.node;if(O.length){E.removeChild(U);U.on=true;U.method="none";U.color=O[0].color;U.color2=O[O.length-1].color;var V=[];for(var K=0,T=O.length;K<T;K++){O[K].offset&&V.push(O[K].offset+k+O[K].color)}U.colors=V.length?V.join():"0% "+U.color;if(P=="radial"){U.type="gradientTitle";U.focus="100%";U.focussize="0 0";U.focusposition=Q;U.angle=0}else{U.type="gradient";U.angle=(270-J)%360}E.appendChild(U)}return 1},u=function(J,E){this[0]=this.node=J;J.raphael=true;this.id=l._oid++;J.raphaelid=this.id;this.X=0;this.Y=0;this.attrs={};this.paper=E;this.matrix=l.matrix();this._={transform:[],sx:1,sy:1,dx:0,dy:0,deg:0,dirty:1,dirtyT:1};!E.bottom&&(E.bottom=this);this.prev=E.top;E.top&&(E.top.next=this);E.top=this;this.next=null};var m=l.el;u.prototype=m;m.constructor=u;m.transform=function(M){if(M==null){return this._.transform}var O=this.paper._viewBoxShift,N=O?"s"+[O.scale,O.scale]+"-1-1t"+[O.dx,O.dy]:q,R;if(O){R=M=F(M).replace(/\.{3}|\u2026/g,this._.transform||q)}l._extractTransform(this,N+M);var S=this.matrix.clone(),U=this.skew,K=this.node,Q,L=~F(this.attrs.fill).indexOf("-"),E=!F(this.attrs.fill).indexOf("url(");S.translate(-0.5,-0.5);if(E||L||this.type=="image"){U.matrix="1 0 0 1";U.offset="0 0";Q=S.split();if((L&&Q.noRotation)||!Q.isSimple){K.style.filter=S.toFilter();var P=this.getBBox(),J=this.getBBox(1),V=P.x-J.x,T=P.y-J.y;K.coordorigin=(V*-b)+k+(T*-b);p(this,1,1,V,T,0)}else{K.style.filter=q;p(this,Q.scalex,Q.scaley,Q.dx,Q.dy,Q.rotate)}}else{K.style.filter=q;U.matrix=F(S);U.offset=S.offset()}R&&(this._.transform=R);return this};m.rotate=function(J,E,L){if(this.removed){return this}if(J==null){return}J=F(J).split(i);if(J.length-1){E=n(J[1]);L=n(J[2])}J=n(J[0]);(L==null)&&(E=L);if(E==null||L==null){var K=this.getBBox(1);E=K.x+K.width/2;L=K.y+K.height/2}this._.dirtyT=1;this.transform(this._.transform.concat([["r",J,E,L]]));return this};m.translate=function(J,E){if(this.removed){return this}J=F(J).split(i);if(J.length-1){E=n(J[1])}J=n(J[0])||0;E=+E||0;if(this._.bbox){this._.bbox.x+=J;this._.bbox.y+=E}this.transform(this._.transform.concat([["t",J,E]]));return this};m.scale=function(M,K,E,L){if(this.removed){return this}M=F(M).split(i);if(M.length-1){K=n(M[1]);E=n(M[2]);L=n(M[3]);isNaN(E)&&(E=null);isNaN(L)&&(L=null)}M=n(M[0]);(K==null)&&(K=M);(L==null)&&(E=L);if(E==null||L==null){var J=this.getBBox(1)}E=E==null?J.x+J.width/2:E;L=L==null?J.y+J.height/2:L;this.transform(this._.transform.concat([["s",M,K,E,L]]));this._.dirtyT=1;return this};m.hide=function(){!this.removed&&(this.node.style.display="none");return this};m.show=function(){!this.removed&&(this.node.style.display=q);return this};m._getBBox=function(){if(this.removed){return{}}return{x:this.X+(this.bbx||0)-this.W/2,y:this.Y-this.H,width:this.W,height:this.H}};m.remove=function(){if(this.removed||!this.node.parentNode){return}this.paper.__set__&&this.paper.__set__.exclude(this);l.eve.unbind("raphael.*.*."+this.id);l._tear(this,this.paper);this.node.parentNode.removeChild(this.node);this.shape&&this.shape.parentNode.removeChild(this.shape);for(var E in this){this[E]=typeof this[E]=="function"?l._removedFactory(E):null}this.removed=true};m.attr=function(E,R){if(this.removed){return this}if(E==null){var O={};for(var Q in this.attrs){if(this.attrs[e](Q)){O[Q]=this.attrs[Q]}}O.gradient&&O.fill=="none"&&(O.fill=O.gradient)&&delete O.gradient;O.transform=this._.transform;return O}if(R==null&&l.is(E,"string")){if(E==v&&this.attrs.fill=="none"&&this.attrs.gradient){return this.attrs.gradient}var P=E.split(i),L={};for(var M=0,T=P.length;M<T;M++){E=P[M];if(E in this.attrs){L[E]=this.attrs[E]}else{if(l.is(this.paper.customAttributes[E],"function")){L[E]=this.paper.customAttributes[E].def}else{L[E]=l._availableAttrs[E]}}}return T-1?L:L[P[0]]}if(this.attrs&&R==null&&l.is(E,"array")){L={};for(M=0,T=E.length;M<T;M++){L[E[M]]=this.attr(E[M])}return L}var J;if(R!=null){J={};J[E]=R}R==null&&l.is(E,"object")&&(J=E);for(var S in J){A("raphael.attr."+S+"."+this.id,this,J[S])}if(J){for(S in this.paper.customAttributes){if(this.paper.customAttributes[e](S)&&J[e](S)&&l.is(this.paper.customAttributes[S],"function")){var N=this.paper.customAttributes[S].apply(this,[].concat(J[S]));this.attrs[S]=J[S];for(var K in N){if(N[e](K)){J[K]=N[K]}}}}if(J.text&&this.type=="text"){this.textpath.string=J.text}x(this,J)}return this};m.toFront=function(){!this.removed&&this.node.parentNode.appendChild(this.node);this.paper&&this.paper.top!=this&&l._tofront(this,this.paper);return this};m.toBack=function(){if(this.removed){return this}if(this.node.parentNode.firstChild!=this.node){this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild);l._toback(this,this.paper)}return this};m.insertAfter=function(E){if(this.removed){return this}if(E.constructor==l.st.constructor){E=E[E.length-1]}if(E.node.nextSibling){E.node.parentNode.insertBefore(this.node,E.node.nextSibling)}else{E.node.parentNode.appendChild(this.node)}l._insertafter(this,E,this.paper);return this};m.insertBefore=function(E){if(this.removed){return this}if(E.constructor==l.st.constructor){E=E[0]}E.node.parentNode.insertBefore(this.node,E.node);l._insertbefore(this,E,this.paper);return this};m.blur=function(E){var J=this.node.runtimeStyle,K=J.filter;K=K.replace(t,q);if(+E!==0){this.attrs.blur=E;J.filter=K+k+w+".Blur(pixelradius="+(+E||1.5)+")";J.margin=l.format("-{0}px 0 0 -{0}px",B(+E||1.5))}else{J.filter=K;J.margin=0;delete this.attrs.blur}};l._engine.path=function(L,J){var M=G("shape");M.style.cssText=d;M.coordsize=b+k+b;M.coordorigin=J.coordorigin;var N=new u(M,J),E={fill:"none",stroke:"#000"};L&&(E.path=L);N.type="path";N.path=[];N.Path=q;x(N,E);J.canvas.appendChild(M);var K=G("skew");K.on=true;M.appendChild(K);N.skew=K;N.transform(q);return N};l._engine.rect=function(J,O,M,P,K,E){var Q=l._rectPath(O,M,P,K,E),L=J.path(Q),N=L.attrs;L.X=N.x=O;L.Y=N.y=M;L.W=N.width=P;L.H=N.height=K;N.r=E;N.path=Q;L.type="rect";return L};l._engine.ellipse=function(J,E,O,N,M){var L=J.path(),K=L.attrs;L.X=E-N;L.Y=O-M;L.W=N*2;L.H=M*2;L.type="ellipse";x(L,{cx:E,cy:O,rx:N,ry:M});return L};l._engine.circle=function(J,E,N,M){var L=J.path(),K=L.attrs;L.X=E-M;L.Y=N-M;L.W=L.H=M*2;L.type="circle";x(L,{cx:E,cy:N,r:M});return L};l._engine.image=function(J,E,P,N,Q,L){var S=l._rectPath(P,N,Q,L),M=J.path(S).attr({stroke:"none"}),O=M.attrs,K=M.node,R=K.getElementsByTagName(v)[0];O.src=E;M.X=O.x=P;M.Y=O.y=N;M.W=O.width=Q;M.H=O.height=L;O.path=S;M.type="image";R.parentNode==K&&K.removeChild(R);R.rotate=true;R.src=E;R.type="tile";M._.fillpos=[P,N];M._.fillsize=[Q,L];K.appendChild(R);p(M,1,1,0,0,0);return M};l._engine.text=function(E,O,N,P){var L=G("shape"),R=G("path"),K=G("textpath");O=O||0;N=N||0;P=P||"";R.v=l.format("m{0},{1}l{2},{1}",B(O*b),B(N*b),B(O*b)+1);R.textpathok=true;K.string=F(P);K.on=true;L.style.cssText=d;L.coordsize=b+k+b;L.coordorigin="0 0";var J=new u(L,E),M={fill:"#000",stroke:"none",font:l._availableAttrs.font,text:P};J.shape=L;J.path=R;J.textpath=K;J.type="text";J.attrs.text=F(P);J.attrs.x=O;J.attrs.y=N;J.attrs.w=1;J.attrs.h=1;x(J,M);L.appendChild(K);L.appendChild(R);E.canvas.appendChild(L);var Q=G("skew");Q.on=true;L.appendChild(Q);J.skew=Q;J.transform(q);return J};l._engine.setSize=function(K,E){var J=this.canvas.style;this.width=K;this.height=E;K==+K&&(K+="px");E==+E&&(E+="px");J.width=K;J.height=E;J.clip="rect(0 "+K+" "+E+" 0)";if(this._viewBox){l._engine.setViewBox.apply(this,this._viewBox)}return this};l._engine.setViewBox=function(N,M,O,K,L){l.eve("raphael.setViewBox",this,this._viewBox,[N,M,O,K,L]);var E=this.width,Q=this.height,R=1/I(O/E,K/Q),P,J;if(L){P=Q/K;J=E/O;if(O*P<E){N-=(E-O*P)/2/P}if(K*J<Q){M-=(Q-K*J)/2/J}}this._viewBox=[N,M,O,K,!!L];this._viewBoxShift={dx:-N,dy:-M,scale:R};this.forEach(function(S){S.transform("...")});return this};var G;l._engine.initWin=function(K){var J=K.document;J.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!J.namespaces.rvml&&J.namespaces.add("rvml","urn:schemas-microsoft-com:vml");G=function(L){return J.createElement("<rvml:"+L+' class="rvml">')}}catch(E){G=function(L){return J.createElement("<"+L+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}};l._engine.initWin(l._g.win);l._engine.create=function(){var K=l._getContainer.apply(0,arguments),E=K.container,Q=K.height,R,J=K.width,P=K.x,O=K.y;if(!E){throw new Error("VML container not found.")}var M=new l._Paper,N=M.canvas=l._g.doc.createElement("div"),L=N.style;P=P||0;O=O||0;J=J||512;Q=Q||342;M.width=J;M.height=Q;J==+J&&(J+="px");Q==+Q&&(Q+="px");M.coordsize=b*1000+k+b*1000;M.coordorigin="0 0";M.span=l._g.doc.createElement("span");M.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";N.appendChild(M.span);L.cssText=l.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",J,Q);if(E==1){l._g.doc.body.appendChild(N);L.left=P+"px";L.top=O+"px";L.position="absolute"}else{if(E.firstChild){E.insertBefore(N,E.firstChild)}else{E.appendChild(N)}}M.renderfix=function(){};return M};l.prototype.clear=function(){l.eve("raphael.clear",this);this.canvas.innerHTML=q;this.span=l._g.doc.createElement("span");this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";this.canvas.appendChild(this.span);this.bottom=this.top=null};l.prototype.remove=function(){l.eve("raphael.remove",this);this.canvas.parentNode.removeChild(this.canvas);for(var E in this){this[E]=typeof this[E]=="function"?l._removedFactory(E):null}return true};var y=l.st;for(var g in m){if(m[e](g)&&!y[e](g)){y[g]=(function(E){return function(){var J=arguments;return this.forEach(function(K){K[E].apply(K,J)})}})(g)}}}(window.Raphael); /* jQuery UI - v1.8.24 - 2012-09-28 * https://github.com/jquery/jquery-ui * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.effects.core.js, jquery.effects.blind.js, jquery.effects.bounce.js, jquery.effects.clip.js, jquery.effects.drop.js, jquery.effects.explode.js, jquery.effects.fade.js, jquery.effects.fold.js, jquery.effects.highlight.js, jquery.effects.pulsate.js, jquery.effects.scale.js, jquery.effects.shake.js, jquery.effects.slide.js, jquery.effects.transfer.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.tabs.js * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ (function(a,d){a.ui=a.ui||{};if(a.ui.version){return}a.extend(a.ui,{version:"1.8.24",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(e,f){return typeof e==="number"?this.each(function(){var g=this;setTimeout(function(){a(g).focus();if(f){f.call(g)}},e)}):this._focus.apply(this,arguments)},scrollParent:function(){var e;if((a.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){e=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(a.curCSS(this,"position",1))&&(/(auto|scroll)/).test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0)}else{e=this.parents().filter(function(){return(/(auto|scroll)/).test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!e.length?a(document):e},zIndex:function(h){if(h!==d){return this.css("zIndex",h)}if(this.length){var f=a(this[0]),e,g;while(f.length&&f[0]!==document){e=f.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){g=parseInt(f.css("zIndex"),10);if(!isNaN(g)&&g!==0){return g}}f=f.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});if(!a("<a>").outerWidth(1).jquery){a.each(["Width","Height"],function(g,e){var f=e==="Width"?["Left","Right"]:["Top","Bottom"],h=e.toLowerCase(),k={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};function j(m,l,i,n){a.each(f,function(){l-=parseFloat(a.curCSS(m,"padding"+this,true))||0;if(i){l-=parseFloat(a.curCSS(m,"border"+this+"Width",true))||0}if(n){l-=parseFloat(a.curCSS(m,"margin"+this,true))||0}});return l}a.fn["inner"+e]=function(i){if(i===d){return k["inner"+e].call(this)}return this.each(function(){a(this).css(h,j(this,i)+"px")})};a.fn["outer"+e]=function(i,l){if(typeof i!=="number"){return k["outer"+e].call(this,i)}return this.each(function(){a(this).css(h,j(this,i,true,l)+"px")})}})}function c(g,e){var j=g.nodeName.toLowerCase();if("area"===j){var i=g.parentNode,h=i.name,f;if(!g.href||!h||i.nodeName.toLowerCase()!=="map"){return false}f=a("img[usemap=#"+h+"]")[0];return !!f&&b(f)}return(/input|select|textarea|button|object/.test(j)?!g.disabled:"a"==j?g.href||e:e)&&b(g)}function b(e){return !a(e).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.extend(a.expr[":"],{data:a.expr.createPseudo?a.expr.createPseudo(function(e){return function(f){return !!a.data(f,e)}}):function(g,f,e){return !!a.data(g,e[3])},focusable:function(e){return c(e,!isNaN(a.attr(e,"tabindex")))},tabbable:function(g){var e=a.attr(g,"tabindex"),f=isNaN(e);return(f||e>=0)&&c(g,!f)}});a(function(){var e=document.body,f=e.appendChild(f=document.createElement("div"));f.offsetHeight;a.extend(f.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});a.support.minHeight=f.offsetHeight===100;a.support.selectstart="onselectstart" in f;e.removeChild(f).style.display="none"});if(!a.curCSS){a.curCSS=a.css}a.extend(a.ui,{plugin:{add:function(f,g,j){var h=a.ui[f].prototype;for(var e in j){h.plugins[e]=h.plugins[e]||[];h.plugins[e].push([g,j[e]])}},call:function(e,g,f){var j=e.plugins[g];if(!j||!e.element[0].parentNode){return}for(var h=0;h<j.length;h++){if(e.options[j[h][0]]){j[h][1].apply(e.element,f)}}}},contains:function(f,e){return document.compareDocumentPosition?f.compareDocumentPosition(e)&16:f!==e&&f.contains(e)},hasScroll:function(h,f){if(a(h).css("overflow")==="hidden"){return false}var e=(f&&f==="left")?"scrollLeft":"scrollTop",g=false;if(h[e]>0){return true}h[e]=1;g=(h[e]>0);h[e]=0;return g},isOverAxis:function(f,e,g){return(f>e)&&(f<(e+g))},isOver:function(j,f,i,h,e,g){return a.ui.isOverAxis(j,i,e)&&a.ui.isOverAxis(f,h,g)}})})(jQuery);(function(b,d){if(b.cleanData){var c=b.cleanData;b.cleanData=function(f){for(var g=0,h;(h=f[g])!=null;g++){try{b(h).triggerHandler("remove")}catch(j){}}c(f)}}else{var a=b.fn.remove;b.fn.remove=function(e,f){return this.each(function(){if(!f){if(!e||b.filter(e,[this]).length){b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove")}catch(g){}})}}return a.call(b(this),e,f)})}}b.widget=function(f,h,e){var g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return !!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var i=new h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])};b.widget.bridge=function(f,e){b.fn[f]=function(i){var g=typeof i==="string",h=Array.prototype.slice.call(arguments,1),j=this;i=!g&&h.length?b.extend.apply(null,[true,i].concat(h)):i;if(g&&i.charAt(0)==="_"){return j}if(g){this.each(function(){var k=b.data(this,f),l=k&&b.isFunction(k[i])?k[i].apply(k,h):k;if(l!==k&&l!==d){j=l;return false}})}else{this.each(function(){var k=b.data(this,f);if(k){k.option(i||{})._init()}else{b.data(this,f,new e(i,this))}})}return j}};b.Widget=function(e,f){if(arguments.length){this._createWidget(e,f)}};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(f,g){b.data(g,this.widgetName,this);this.element=b(g);this.options=b.extend(true,{},this.options,this._getCreateOptions(),f);var e=this;this.element.bind("remove."+this.widgetName,function(){e.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(f,g){var e=f;if(arguments.length===0){return b.extend({},this.options)}if(typeof f==="string"){if(g===d){return this.options[f]}e={};e[f]=g}this._setOptions(e);return this},_setOptions:function(f){var e=this;b.each(f,function(g,h){e._setOption(g,h)});return this},_setOption:function(e,f){this.options[e]=f;if(e==="disabled"){this.widget()[f?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",f)}return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(e,f,g){var j,i,h=this.options[e];g=g||{};f=b.Event(f);f.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();f.target=this.element[0];i=f.originalEvent;if(i){for(j in i){if(!(j in f)){f[j]=i[j]}}}this.element.trigger(f,g);return !(b.isFunction(h)&&h.call(this.element[0],f,g)===false||f.isDefaultPrevented())}}})(jQuery);(function(b,c){var a=false;b(document).mouseup(function(d){a=false});b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var d=this;this.element.bind("mousedown."+this.widgetName,function(e){return d._mouseDown(e)}).bind("click."+this.widgetName,function(e){if(true===b.data(e.target,d.widgetName+".preventClickEvent")){b.removeData(e.target,d.widgetName+".preventClickEvent");e.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);if(this._mouseMoveDelegate){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)}},_mouseDown:function(f){if(a){return}(this._mouseStarted&&this._mouseUp(f));this._mouseDownEvent=f;var e=this,g=(f.which==1),d=(typeof this.options.cancel=="string"&&f.target.nodeName?b(f.target).closest(this.options.cancel).length:false);if(!g||d||!this._mouseCapture(f)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(f)&&this._mouseDelayMet(f)){this._mouseStarted=(this._mouseStart(f)!==false);if(!this._mouseStarted){f.preventDefault();return true}}if(true===b.data(f.target,this.widgetName+".preventClickEvent")){b.removeData(f.target,this.widgetName+".preventClickEvent")}this._mouseMoveDelegate=function(h){return e._mouseMove(h)};this._mouseUpDelegate=function(h){return e._mouseUp(h)};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);f.preventDefault();a=true;return true},_mouseMove:function(d){if(b.browser.msie&&!(document.documentMode>=9)&&!d.button){return this._mouseUp(d)}if(this._mouseStarted){this._mouseDrag(d);return d.preventDefault()}if(this._mouseDistanceMet(d)&&this._mouseDelayMet(d)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,d)!==false);(this._mouseStarted?this._mouseDrag(d):this._mouseUp(d))}return !this._mouseStarted},_mouseUp:function(d){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(d.target==this._mouseDownEvent.target){b.data(d.target,this.widgetName+".preventClickEvent",true)}this._mouseStop(d)}return false},_mouseDistanceMet:function(d){return(Math.max(Math.abs(this._mouseDownEvent.pageX-d.pageX),Math.abs(this._mouseDownEvent.pageY-d.pageY))>=this.options.distance)},_mouseDelayMet:function(d){return this.mouseDelayMet},_mouseStart:function(d){},_mouseDrag:function(d){},_mouseStop:function(d){},_mouseCapture:function(d){return true}})})(jQuery);(function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this},_mouseCapture:function(c){var d=this.options;if(this.helper||d.disabled||a(c.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(c);if(!this.handle){return false}if(d.iframeFix){a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})}return true},_mouseStart:function(c){var d=this.options;this.helper=this._createHelper(c);this.helper.addClass("ui-draggable-dragging");this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:c.pageX-this.offset.left,top:c.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(c);this.originalPageX=c.pageX;this.originalPageY=c.pageY;(d.cursorAt&&this._adjustOffsetFromHelper(d.cursorAt));if(d.containment){this._setContainment()}if(this._trigger("start",c)===false){this._clear();return false}this._cacheHelperProportions();if(a.ui.ddmanager&&!d.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,c)}this._mouseDrag(c,true);if(a.ui.ddmanager){a.ui.ddmanager.dragStart(this,c)}return true},_mouseDrag:function(c,e){this.position=this._generatePosition(c);this.positionAbs=this._convertPositionTo("absolute");if(!e){var d=this._uiHash();if(this._trigger("drag",c,d)===false){this._mouseUp({});return false}this.position=d.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,c)}return false},_mouseStop:function(e){var g=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){g=a.ui.ddmanager.drop(this,e)}if(this.dropped){g=this.dropped;this.dropped=false}var d=this.element[0],f=false;while(d&&(d=d.parentNode)){if(d==document){f=true}}if(!f&&this.options.helper==="original"){return false}if((this.options.revert=="invalid"&&!g)||(this.options.revert=="valid"&&g)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,g))){var c=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(c._trigger("stop",e)!==false){c._clear()}})}else{if(this._trigger("stop",e)!==false){this._clear()}}return false},_mouseUp:function(c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});if(a.ui.ddmanager){a.ui.ddmanager.dragStop(this,c)}return a.ui.mouse.prototype._mouseUp.call(this,c)},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp({})}else{this._clear()}return this},_getHandle:function(c){var d=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==c.target){d=true}});return d},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d])):(e.helper=="clone"?this.element.clone().removeAttr("id"):this.element);if(!c.parents("body").length){c.appendTo((e.appendTo=="parent"?this.element[0].parentNode:e.appendTo))}if(c[0]!=this.element[0]&&!(/(fixed|absolute)/).test(c.css("position"))){c.css("position","absolute")}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.element.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0),right:(parseInt(this.element.css("marginRight"),10)||0),bottom:(parseInt(this.element.css("marginBottom"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var g=this.options;if(g.containment=="parent"){g.containment=this.helper[0].parentNode}if(g.containment=="document"||g.containment=="window"){this.containment=[g.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,g.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(g.containment=="document"?0:a(window).scrollLeft())+a(g.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(g.containment=="document"?0:a(window).scrollTop())+(a(g.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(g.containment)&&g.containment.constructor!=Array){var h=a(g.containment);var e=h[0];if(!e){return}var f=h.offset();var d=(a(e).css("overflow")!="hidden");this.containment=[(parseInt(a(e).css("borderLeftWidth"),10)||0)+(parseInt(a(e).css("paddingLeft"),10)||0),(parseInt(a(e).css("borderTopWidth"),10)||0)+(parseInt(a(e).css("paddingTop"),10)||0),(d?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(a(e).css("borderLeftWidth"),10)||0)-(parseInt(a(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(d?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(a(e).css("borderTopWidth"),10)||0)-(parseInt(a(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=h}else{if(g.containment.constructor==Array){this.containment=g.containment}}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(d){var e=this.options,l=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(l[0].tagName);var h=d.pageX;var g=d.pageY;if(this.originalPosition){var c;if(this.containment){if(this.relative_container){var k=this.relative_container.offset();c=[this.containment[0]+k.left,this.containment[1]+k.top,this.containment[2]+k.left,this.containment[3]+k.top]}else{c=this.containment}if(d.pageX-this.offset.click.left<c[0]){h=c[0]+this.offset.click.left}if(d.pageY-this.offset.click.top<c[1]){g=c[1]+this.offset.click.top}if(d.pageX-this.offset.click.left>c[2]){h=c[2]+this.offset.click.left}if(d.pageY-this.offset.click.top>c[3]){g=c[3]+this.offset.click.top}}if(e.grid){var j=e.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/e.grid[1])*e.grid[1]:this.originalPageY;g=c?(!(j-this.offset.click.top<c[1]||j-this.offset.click.top>c[3])?j:(!(j-this.offset.click.top<c[1])?j-e.grid[1]:j+e.grid[1])):j;var f=e.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/e.grid[0])*e.grid[0]:this.originalPageX;h=c?(!(f-this.offset.click.left<c[0]||f-this.offset.click.left>c[2])?f:(!(f-this.offset.click.left<c[0])?f-e.grid[0]:f+e.grid[0])):f}}return{top:(g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:l.scrollTop())))),left:(h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:l.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(c,d,e){e=e||this._uiHash();a.ui.plugin.call(this,c,[d,e]);if(c=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.Widget.prototype._trigger.call(this,c,d,e)},plugins:{},_uiHash:function(c){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});a.extend(a.ui.draggable,{version:"1.8.24"});a.ui.plugin.add("draggable","connectToSortable",{start:function(d,f){var e=a(this).data("draggable"),g=e.options,c=a.extend({},f,{item:e.element});e.sortables=[];a(g.connectToSortable).each(function(){var h=a.data(this,"sortable");if(h&&!h.options.disabled){e.sortables.push({instance:h,shouldRevert:h.options.revert});h.refreshPositions();h._trigger("activate",d,c)}})},stop:function(d,f){var e=a(this).data("draggable"),c=a.extend({},f,{item:e.element});a.each(e.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;e.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(d);this.instance.options.helper=this.instance.options._helper;if(e.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",d,c)}})},drag:function(d,g){var f=a(this).data("draggable"),c=this;var e=function(j){var p=this.offset.click.top,n=this.offset.click.left;var h=this.positionAbs.top,l=this.positionAbs.left;var k=j.height,m=j.width;var q=j.top,i=j.left;return a.ui.isOver(h+p,l+n,q,i,k,m)};a.each(f.sortables,function(h){this.instance.positionAbs=f.positionAbs;this.instance.helperProportions=f.helperProportions;this.instance.offset.click=f.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(c).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return g.helper[0]};d.target=this.instance.currentItem[0];this.instance._mouseCapture(d,true);this.instance._mouseStart(d,true,true);this.instance.offset.click.top=f.offset.click.top;this.instance.offset.click.left=f.offset.click.left;this.instance.offset.parent.left-=f.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=f.offset.parent.top-this.instance.offset.parent.top;f._trigger("toSortable",d);f.dropped=this.instance.element;f.currentItem=f.element;this.instance.fromOutside=f}if(this.instance.currentItem){this.instance._mouseDrag(d)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",d,this.instance._uiHash(this.instance));this.instance._mouseStop(d,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}f._trigger("fromSortable",d);f.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(d,e){var c=a("body"),f=a(this).data("draggable").options;if(c.css("cursor")){f._cursor=c.css("cursor")}c.css("cursor",f.cursor)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._cursor){a("body").css("cursor",e._cursor)}}});a.ui.plugin.add("draggable","opacity",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("opacity")){f._opacity=c.css("opacity")}c.css("opacity",f.opacity)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._opacity){a(d.helper).css("opacity",e._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(d,e){var c=a(this).data("draggable");if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){c.overflowOffset=c.scrollParent.offset()}},drag:function(e,f){var d=a(this).data("draggable"),g=d.options,c=false;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!g.axis||g.axis!="x"){if((d.overflowOffset.top+d.scrollParent[0].offsetHeight)-e.pageY<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop+g.scrollSpeed}else{if(e.pageY-d.overflowOffset.top<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop-g.scrollSpeed}}}if(!g.axis||g.axis!="y"){if((d.overflowOffset.left+d.scrollParent[0].offsetWidth)-e.pageX<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(e.pageX-d.overflowOffset.left<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft-g.scrollSpeed}}}}else{if(!g.axis||g.axis!="x"){if(e.pageY-a(document).scrollTop()<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(e.pageY-a(document).scrollTop())<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}}if(!g.axis||g.axis!="y"){if(e.pageX-a(document).scrollLeft()<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(e.pageX-a(document).scrollLeft())<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}}if(c!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(d,e)}}});a.ui.plugin.add("draggable","snap",{start:function(d,e){var c=a(this).data("draggable"),f=c.options;c.snapElements=[];a(f.snap.constructor!=String?(f.snap.items||":data(draggable)"):f.snap).each(function(){var h=a(this);var g=h.offset();if(this!=c.element[0]){c.snapElements.push({item:this,width:h.outerWidth(),height:h.outerHeight(),top:g.top,left:g.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(d,e){var g=a(this).data("draggable").options;var f=a.makeArray(a(g.stack)).sort(function(i,h){return(parseInt(a(i).css("zIndex"),10)||0)-(parseInt(a(h).css("zIndex"),10)||0)});if(!f.length){return}var c=parseInt(f[0].style.zIndex)||0;a(f).each(function(h){this.style.zIndex=c+h});this[0].style.zIndex=c+f.length}});a.ui.plugin.add("draggable","zIndex",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("zIndex")){f._zIndex=c.css("zIndex")}c.css("zIndex",f.zIndex)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._zIndex){a(d.helper).css("zIndex",e._zIndex)}}})})(jQuery);(function(a,b){a.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var d=this.options,c=d.accept;this.isover=0;this.isout=1;this.accept=a.isFunction(c)?c:function(e){return e.is(c)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};a.ui.ddmanager.droppables[d.scope]=a.ui.ddmanager.droppables[d.scope]||[];a.ui.ddmanager.droppables[d.scope].push(this);(d.addClasses&&this.element.addClass("ui-droppable"))},destroy:function(){var c=a.ui.ddmanager.droppables[this.options.scope];for(var d=0;d<c.length;d++){if(c[d]==this){c.splice(d,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(c,d){if(c=="accept"){this.accept=a.isFunction(d)?d:function(e){return e.is(d)}}a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(d){var c=a.ui.ddmanager.current;if(this.options.activeClass){this.element.addClass(this.options.activeClass)}(c&&this._trigger("activate",d,this.ui(c)))},_deactivate:function(d){var c=a.ui.ddmanager.current;if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}(c&&this._trigger("deactivate",d,this.ui(c)))},_over:function(d){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0]){return}if(this.accept.call(this.element[0],(c.currentItem||c.element))){if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}this._trigger("over",d,this.ui(c))}},_out:function(d){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0]){return}if(this.accept.call(this.element[0],(c.currentItem||c.element))){if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("out",d,this.ui(c))}},_drop:function(d,e){var c=e||a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0]){return false}var f=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g=a.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],(c.currentItem||c.element))&&a.ui.intersect(c,a.extend(g,{offset:g.element.offset()}),g.options.tolerance)){f=true;return false}});if(f){return false}if(this.accept.call(this.element[0],(c.currentItem||c.element))){if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("drop",d,this.ui(c));return this.element}return false},ui:function(d){return{draggable:(d.currentItem||d.element),helper:d.helper,position:d.position,offset:d.positionAbs}}});a.extend(a.ui.droppable,{version:"1.8.24"});a.ui.intersect=function(q,j,o){if(!j.offset){return false}var e=(q.positionAbs||q.position.absolute).left,d=e+q.helperProportions.width,n=(q.positionAbs||q.position.absolute).top,m=n+q.helperProportions.height;var g=j.offset.left,c=g+j.proportions.width,p=j.offset.top,k=p+j.proportions.height;switch(o){case"fit":return(g<=e&&d<=c&&p<=n&&m<=k);break;case"intersect":return(g<e+(q.helperProportions.width/2)&&d-(q.helperProportions.width/2)<c&&p<n+(q.helperProportions.height/2)&&m-(q.helperProportions.height/2)<k);break;case"pointer":var h=((q.positionAbs||q.position.absolute).left+(q.clickOffset||q.offset.click).left),i=((q.positionAbs||q.position.absolute).top+(q.clickOffset||q.offset.click).top),f=a.ui.isOver(i,h,p,g,j.proportions.height,j.proportions.width);return f;break;case"touch":return((n>=p&&n<=k)||(m>=p&&m<=k)||(n<p&&m>k))&&((e>=g&&e<=c)||(d>=g&&d<=c)||(e<g&&d>c));break;default:return false;break}};a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(f,h){var c=a.ui.ddmanager.droppables[f.options.scope]||[];var g=h?h.type:null;var k=(f.currentItem||f.element).find(":data(droppable)").andSelf();droppablesLoop:for(var e=0;e<c.length;e++){if(c[e].options.disabled||(f&&!c[e].accept.call(c[e].element[0],(f.currentItem||f.element)))){continue}for(var d=0;d<k.length;d++){if(k[d]==c[e].element[0]){c[e].proportions.height=0;continue droppablesLoop}}c[e].visible=c[e].element.css("display")!="none";if(!c[e].visible){continue}if(g=="mousedown"){c[e]._activate.call(c[e],h)}c[e].offset=c[e].element.offset();c[e].proportions={width:c[e].element[0].offsetWidth,height:c[e].element[0].offsetHeight}}},drop:function(c,d){var e=false;a.each(a.ui.ddmanager.droppables[c.options.scope]||[],function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&a.ui.intersect(c,this,this.options.tolerance)){e=this._drop.call(this,d)||e}if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],(c.currentItem||c.element))){this.isout=1;this.isover=0;this._deactivate.call(this,d)}});return e},dragStart:function(c,d){c.element.parents(":not(body,html)").bind("scroll.droppable",function(){if(!c.options.refreshPositions){a.ui.ddmanager.prepareOffsets(c,d)}})},drag:function(c,d){if(c.options.refreshPositions){a.ui.ddmanager.prepareOffsets(c,d)}a.each(a.ui.ddmanager.droppables[c.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var g=a.ui.intersect(c,this,this.options.tolerance);var i=!g&&this.isover==1?"isout":(g&&this.isover==0?"isover":null);if(!i){return}var h;if(this.options.greedy){var f=this.options.scope;var e=this.element.parents(":data(droppable)").filter(function(){return a.data(this,"droppable").options.scope===f});if(e.length){h=a.data(e[0],"droppable");h.greedyChild=(i=="isover"?1:0)}}if(h&&i=="isover"){h.isover=0;h.isout=1;h._out.call(h,d)}this[i]=1;this[i=="isout"?"isover":"isout"]=0;this[i=="isover"?"_over":"_out"].call(this,d);if(h&&i=="isout"){h.isout=0;h.isover=1;h._over.call(h,d)}})},dragStop:function(c,d){c.element.parents(":not(body,html)").unbind("scroll.droppable");if(!c.options.refreshPositions){a.ui.ddmanager.prepareOffsets(c,d)}}}})(jQuery);(function(c,d){c.widget("ui.resizable",c.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1000},_create:function(){var f=this,k=this.options;this.element.addClass("ui-resizable");c.extend(this,{_aspectRatio:!!(k.aspectRatio),aspectRatio:k.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:k.helper||k.ghost||k.animate?k.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){this.element.wrap(c('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=k.handles||(!c(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all"){this.handles="n,e,s,w,se,sw,ne,nw"}var l=this.handles.split(",");this.handles={};for(var g=0;g<l.length;g++){var j=c.trim(l[g]),e="ui-resizable-"+j;var h=c('<div class="ui-resizable-handle '+e+'"></div>');h.css({zIndex:k.zIndex});if("se"==j){h.addClass("ui-icon ui-icon-gripsmall-diagonal-se")}this.handles[j]=".ui-resizable-"+j;this.element.append(h)}}this._renderAxis=function(q){q=q||this.element;for(var n in this.handles){if(this.handles[n].constructor==String){this.handles[n]=c(this.handles[n],this.element).show()}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var o=c(this.handles[n],this.element),p=0;p=/sw|ne|nw|se|n|s/.test(n)?o.outerHeight():o.outerWidth();var m=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");q.css(m,p);this._proportionallyResize()}if(!c(this.handles[n]).length){continue}}};this._renderAxis(this.element);this._handles=c(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!f.resizing){if(this.className){var i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}f.axis=i&&i[1]?i[1]:"se"}});if(k.autoHide){this._handles.hide();c(this.element).addClass("ui-resizable-autohide").hover(function(){if(k.disabled){return}c(this).removeClass("ui-resizable-autohide");f._handles.show()},function(){if(k.disabled){return}if(!f.resizing){c(this).addClass("ui-resizable-autohide");f._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var e=function(g){c(g).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){e(this.element);var f=this.element;f.after(this.originalElement.css({position:f.css("position"),width:f.outerWidth(),height:f.outerHeight(),top:f.css("top"),left:f.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);e(this.originalElement);return this},_mouseCapture:function(f){var g=false;for(var e in this.handles){if(c(this.handles[e])[0]==f.target){g=true}}return !this.options.disabled&&g},_mouseStart:function(g){var j=this.options,f=this.element.position(),e=this.element;this.resizing=true;this.documentScroll={top:c(document).scrollTop(),left:c(document).scrollLeft()};if(e.is(".ui-draggable")||(/absolute/).test(e.css("position"))){e.css({position:"absolute",top:f.top,left:f.left})}this._renderProxy();var k=b(this.helper.css("left")),h=b(this.helper.css("top"));if(j.containment){k+=c(j.containment).scrollLeft()||0;h+=c(j.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:k,top:h};this.size=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalSize=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalPosition={left:k,top:h};this.sizeDiff={width:e.outerWidth()-e.width(),height:e.outerHeight()-e.height()};this.originalMousePosition={left:g.pageX,top:g.pageY};this.aspectRatio=(typeof j.aspectRatio=="number")?j.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);var i=c(".ui-resizable-"+this.axis).css("cursor");c("body").css("cursor",i=="auto"?this.axis+"-resize":i);e.addClass("ui-resizable-resizing");this._propagate("start",g);return true},_mouseDrag:function(e){var h=this.helper,g=this.options,m={},q=this,j=this.originalMousePosition,n=this.axis;var r=(e.pageX-j.left)||0,p=(e.pageY-j.top)||0;var i=this._change[n];if(!i){return false}var l=i.apply(this,[e,r,p]),k=c.browser.msie&&c.browser.version<7,f=this.sizeDiff;this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey){l=this._updateRatio(l,e)}l=this._respectSize(l,e);this._propagate("resize",e);h.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}this._updateCache(l);this._trigger("resize",e,this.ui());return false},_mouseStop:function(h){this.resizing=false;var i=this.options,m=this;if(this._helper){var g=this._proportionallyResizeElements,e=g.length&&(/textarea/i).test(g[0].nodeName),f=e&&c.ui.hasScroll(g[0],"left")?0:m.sizeDiff.height,k=e?0:m.sizeDiff.width;var n={width:(m.helper.width()-k),height:(m.helper.height()-f)},j=(parseInt(m.element.css("left"),10)+(m.position.left-m.originalPosition.left))||null,l=(parseInt(m.element.css("top"),10)+(m.position.top-m.originalPosition.top))||null;if(!i.animate){this.element.css(c.extend(n,{top:l,left:j}))}m.helper.height(m.size.height);m.helper.width(m.size.width);if(this._helper&&!i.animate){this._proportionallyResize()}}c("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",h);if(this._helper){this.helper.remove()}return false},_updateVirtualBoundaries:function(g){var j=this.options,i,h,f,k,e;e={minWidth:a(j.minWidth)?j.minWidth:0,maxWidth:a(j.maxWidth)?j.maxWidth:Infinity,minHeight:a(j.minHeight)?j.minHeight:0,maxHeight:a(j.maxHeight)?j.maxHeight:Infinity};if(this._aspectRatio||g){i=e.minHeight*this.aspectRatio;f=e.minWidth/this.aspectRatio;h=e.maxHeight*this.aspectRatio;k=e.maxWidth/this.aspectRatio;if(i>e.minWidth){e.minWidth=i}if(f>e.minHeight){e.minHeight=f}if(h<e.maxWidth){e.maxWidth=h}if(k<e.maxHeight){e.maxHeight=k}}this._vBoundaries=e},_updateCache:function(e){var f=this.options;this.offset=this.helper.offset();if(a(e.left)){this.position.left=e.left}if(a(e.top)){this.position.top=e.top}if(a(e.height)){this.size.height=e.height}if(a(e.width)){this.size.width=e.width}},_updateRatio:function(h,g){var i=this.options,j=this.position,f=this.size,e=this.axis;if(a(h.height)){h.width=(h.height*this.aspectRatio)}else{if(a(h.width)){h.height=(h.width/this.aspectRatio)}}if(e=="sw"){h.left=j.left+(f.width-h.width);h.top=null}if(e=="nw"){h.top=j.top+(f.height-h.height);h.left=j.left+(f.width-h.width)}return h},_respectSize:function(l,g){var j=this.helper,i=this._vBoundaries,r=this._aspectRatio||g.shiftKey,q=this.axis,t=a(l.width)&&i.maxWidth&&(i.maxWidth<l.width),m=a(l.height)&&i.maxHeight&&(i.maxHeight<l.height),h=a(l.width)&&i.minWidth&&(i.minWidth>l.width),s=a(l.height)&&i.minHeight&&(i.minHeight>l.height);if(h){l.width=i.minWidth}if(s){l.height=i.minHeight}if(t){l.width=i.maxWidth}if(m){l.height=i.maxHeight}var f=this.originalPosition.left+this.originalSize.width,p=this.position.top+this.size.height;var k=/sw|nw|w/.test(q),e=/nw|ne|n/.test(q);if(h&&k){l.left=f-i.minWidth}if(t&&k){l.left=f-i.maxWidth}if(s&&e){l.top=p-i.minHeight}if(m&&e){l.top=p-i.maxHeight}var n=!l.width&&!l.height;if(n&&!l.left&&l.top){l.top=null}else{if(n&&!l.top&&l.left){l.left=null}}return l},_proportionallyResize:function(){var k=this.options;if(!this._proportionallyResizeElements.length){return}var g=this.helper||this.element;for(var f=0;f<this._proportionallyResizeElements.length;f++){var h=this._proportionallyResizeElements[f];if(!this.borderDif){var e=[h.css("borderTopWidth"),h.css("borderRightWidth"),h.css("borderBottomWidth"),h.css("borderLeftWidth")],j=[h.css("paddingTop"),h.css("paddingRight"),h.css("paddingBottom"),h.css("paddingLeft")];this.borderDif=c.map(e,function(l,n){var m=parseInt(l,10)||0,o=parseInt(j[n],10)||0;return m+o})}if(c.browser.msie&&!(!(c(g).is(":hidden")||c(g).parents(":hidden").length))){continue}h.css({height:(g.height()-this.borderDif[0]-this.borderDif[2])||0,width:(g.width()-this.borderDif[1]-this.borderDif[3])||0})}},_renderProxy:function(){var f=this.element,i=this.options;this.elementOffset=f.offset();if(this._helper){this.helper=this.helper||c('<div style="overflow:hidden;"></div>');var e=c.browser.msie&&c.browser.version<7,g=(e?1:0),h=(e?2:-1);this.helper.addClass(this._helper).css({width:this.element.outerWidth()+h,height:this.element.outerHeight()+h,position:"absolute",left:this.elementOffset.left-g+"px",top:this.elementOffset.top-g+"px",zIndex:++i.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(g,f,e){return{width:this.originalSize.width+f}},w:function(h,f,e){var j=this.options,g=this.originalSize,i=this.originalPosition;return{left:i.left+f,width:g.width-f}},n:function(h,f,e){var j=this.options,g=this.originalSize,i=this.originalPosition;return{top:i.top+e,height:g.height-e}},s:function(g,f,e){return{height:this.originalSize.height+e}},se:function(g,f,e){return c.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[g,f,e]))},sw:function(g,f,e){return c.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[g,f,e]))},ne:function(g,f,e){return c.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[g,f,e]))},nw:function(g,f,e){return c.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[g,f,e]))}},_propagate:function(f,e){c.ui.plugin.call(this,f,[e,this.ui()]);(f!="resize"&&this._trigger(f,e,this.ui()))},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});c.extend(c.ui.resizable,{version:"1.8.24"});c.ui.plugin.add("resizable","alsoResize",{start:function(f,g){var e=c(this).data("resizable"),i=e.options;var h=function(j){c(j).each(function(){var k=c(this);k.data("resizable-alsoresize",{width:parseInt(k.width(),10),height:parseInt(k.height(),10),left:parseInt(k.css("left"),10),top:parseInt(k.css("top"),10)})})};if(typeof(i.alsoResize)=="object"&&!i.alsoResize.parentNode){if(i.alsoResize.length){i.alsoResize=i.alsoResize[0];h(i.alsoResize)}else{c.each(i.alsoResize,function(j){h(j)})}}else{h(i.alsoResize)}},resize:function(g,i){var f=c(this).data("resizable"),j=f.options,h=f.originalSize,l=f.originalPosition;var k={height:(f.size.height-h.height)||0,width:(f.size.width-h.width)||0,top:(f.position.top-l.top)||0,left:(f.position.left-l.left)||0},e=function(m,n){c(m).each(function(){var q=c(this),r=c(this).data("resizable-alsoresize"),p={},o=n&&n.length?n:q.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];c.each(o,function(s,u){var t=(r[u]||0)+(k[u]||0);if(t&&t>=0){p[u]=t||null}});q.css(p)})};if(typeof(j.alsoResize)=="object"&&!j.alsoResize.nodeType){c.each(j.alsoResize,function(m,n){e(m,n)})}else{e(j.alsoResize)}},stop:function(e,f){c(this).removeData("resizable-alsoresize")}});c.ui.plugin.add("resizable","animate",{stop:function(i,n){var p=c(this).data("resizable"),j=p.options;var h=p._proportionallyResizeElements,e=h.length&&(/textarea/i).test(h[0].nodeName),f=e&&c.ui.hasScroll(h[0],"left")?0:p.sizeDiff.height,l=e?0:p.sizeDiff.width;var g={width:(p.size.width-l),height:(p.size.height-f)},k=(parseInt(p.element.css("left"),10)+(p.position.left-p.originalPosition.left))||null,m=(parseInt(p.element.css("top"),10)+(p.position.top-p.originalPosition.top))||null;p.element.animate(c.extend(g,m&&k?{top:m,left:k}:{}),{duration:j.animateDuration,easing:j.animateEasing,step:function(){var o={width:parseInt(p.element.css("width"),10),height:parseInt(p.element.css("height"),10),top:parseInt(p.element.css("top"),10),left:parseInt(p.element.css("left"),10)};if(h&&h.length){c(h[0]).css({width:o.width,height:o.height})}p._updateCache(o);p._propagate("resize",i)}})}});c.ui.plugin.add("resizable","containment",{start:function(f,r){var t=c(this).data("resizable"),j=t.options,l=t.element;var g=j.containment,k=(g instanceof c)?g.get(0):(/parent/.test(g))?l.parent().get(0):g;if(!k){return}t.containerElement=c(k);if(/document/.test(g)||g==document){t.containerOffset={left:0,top:0};t.containerPosition={left:0,top:0};t.parentData={element:c(document),left:0,top:0,width:c(document).width(),height:c(document).height()||document.body.parentNode.scrollHeight}}else{var n=c(k),i=[];c(["Top","Right","Left","Bottom"]).each(function(p,o){i[p]=b(n.css("padding"+o))});t.containerOffset=n.offset();t.containerPosition=n.position();t.containerSize={height:(n.innerHeight()-i[3]),width:(n.innerWidth()-i[1])};var q=t.containerOffset,e=t.containerSize.height,m=t.containerSize.width,h=(c.ui.hasScroll(k,"left")?k.scrollWidth:m),s=(c.ui.hasScroll(k)?k.scrollHeight:e);t.parentData={element:k,left:q.left,top:q.top,width:h,height:s}}},resize:function(g,q){var t=c(this).data("resizable"),i=t.options,f=t.containerSize,p=t.containerOffset,m=t.size,n=t.position,r=t._aspectRatio||g.shiftKey,e={top:0,left:0},h=t.containerElement;if(h[0]!=document&&(/static/).test(h.css("position"))){e=p}if(n.left<(t._helper?p.left:0)){t.size.width=t.size.width+(t._helper?(t.position.left-p.left):(t.position.left-e.left));if(r){t.size.height=t.size.width/t.aspectRatio}t.position.left=i.helper?p.left:0}if(n.top<(t._helper?p.top:0)){t.size.height=t.size.height+(t._helper?(t.position.top-p.top):t.position.top);if(r){t.size.width=t.size.height*t.aspectRatio}t.position.top=t._helper?p.top:0}t.offset.left=t.parentData.left+t.position.left;t.offset.top=t.parentData.top+t.position.top;var l=Math.abs((t._helper?t.offset.left-e.left:(t.offset.left-e.left))+t.sizeDiff.width),s=Math.abs((t._helper?t.offset.top-e.top:(t.offset.top-p.top))+t.sizeDiff.height);var k=t.containerElement.get(0)==t.element.parent().get(0),j=/relative|absolute/.test(t.containerElement.css("position"));if(k&&j){l-=t.parentData.left}if(l+t.size.width>=t.parentData.width){t.size.width=t.parentData.width-l;if(r){t.size.height=t.size.width/t.aspectRatio}}if(s+t.size.height>=t.parentData.height){t.size.height=t.parentData.height-s;if(r){t.size.width=t.size.height*t.aspectRatio}}},stop:function(f,n){var q=c(this).data("resizable"),g=q.options,l=q.position,m=q.containerOffset,e=q.containerPosition,i=q.containerElement;var j=c(q.helper),r=j.offset(),p=j.outerWidth()-q.sizeDiff.width,k=j.outerHeight()-q.sizeDiff.height;if(q._helper&&!g.animate&&(/relative/).test(i.css("position"))){c(this).css({left:r.left-e.left-m.left,width:p,height:k})}if(q._helper&&!g.animate&&(/static/).test(i.css("position"))){c(this).css({left:r.left-e.left-m.left,width:p,height:k})}}});c.ui.plugin.add("resizable","ghost",{start:function(g,h){var e=c(this).data("resizable"),i=e.options,f=e.size;e.ghost=e.originalElement.clone();e.ghost.css({opacity:0.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:"");e.ghost.appendTo(e.helper)},resize:function(f,g){var e=c(this).data("resizable"),h=e.options;if(e.ghost){e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})}},stop:function(f,g){var e=c(this).data("resizable"),h=e.options;if(e.ghost&&e.helper){e.helper.get(0).removeChild(e.ghost.get(0))}}});c.ui.plugin.add("resizable","grid",{resize:function(e,m){var p=c(this).data("resizable"),h=p.options,k=p.size,i=p.originalSize,j=p.originalPosition,n=p.axis,l=h._aspectRatio||e.shiftKey;h.grid=typeof h.grid=="number"?[h.grid,h.grid]:h.grid;var g=Math.round((k.width-i.width)/(h.grid[0]||1))*(h.grid[0]||1),f=Math.round((k.height-i.height)/(h.grid[1]||1))*(h.grid[1]||1);if(/^(se|s|e)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f}else{if(/^(ne)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f;p.position.top=j.top-f}else{if(/^(sw)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f;p.position.left=j.left-g}else{p.size.width=i.width+g;p.size.height=i.height+f;p.position.top=j.top-f;p.position.left=j.left-g}}}}});var b=function(e){return parseInt(e,10)||0};var a=function(e){return !isNaN(parseInt(e,10))}})(jQuery);(function(a,b){a.widget("ui.selectable",a.ui.mouse,{options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch"},_create:function(){var c=this;this.element.addClass("ui-selectable");this.dragged=false;var d;this.refresh=function(){d=a(c.options.filter,c.element[0]);d.addClass("ui-selectee");d.each(function(){var e=a(this);var f=e.offset();a.data(this,"selectable-item",{element:this,$element:e,left:f.left,top:f.top,right:f.left+e.outerWidth(),bottom:f.top+e.outerHeight(),startselected:false,selected:e.hasClass("ui-selected"),selecting:e.hasClass("ui-selecting"),unselecting:e.hasClass("ui-unselecting")})})};this.refresh();this.selectees=d.addClass("ui-selectee");this._mouseInit();this.helper=a("<div class='ui-selectable-helper'></div>")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this},_mouseStart:function(e){var c=this;this.opos=[e.pageX,e.pageY];if(this.options.disabled){return}var d=this.options;this.selectees=a(d.filter,this.element[0]);this._trigger("start",e);a(d.appendTo).append(this.helper);this.helper.css({left:e.clientX,top:e.clientY,width:0,height:0});if(d.autoRefresh){this.refresh()}this.selectees.filter(".ui-selected").each(function(){var f=a.data(this,"selectable-item");f.startselected=true;if(!e.metaKey&&!e.ctrlKey){f.$element.removeClass("ui-selected");f.selected=false;f.$element.addClass("ui-unselecting");f.unselecting=true;c._trigger("unselecting",e,{unselecting:f.element})}});a(e.target).parents().andSelf().each(function(){var g=a.data(this,"selectable-item");if(g){var f=(!e.metaKey&&!e.ctrlKey)||!g.$element.hasClass("ui-selected");g.$element.removeClass(f?"ui-unselecting":"ui-selected").addClass(f?"ui-selecting":"ui-unselecting");g.unselecting=!f;g.selecting=f;g.selected=f;if(f){c._trigger("selecting",e,{selecting:g.element})}else{c._trigger("unselecting",e,{unselecting:g.element})}return false}})},_mouseDrag:function(j){var d=this;this.dragged=true;if(this.options.disabled){return}var f=this.options;var e=this.opos[0],i=this.opos[1],c=j.pageX,h=j.pageY;if(e>c){var g=c;c=e;e=g}if(i>h){var g=h;h=i;i=g}this.helper.css({left:e,top:i,width:c-e,height:h-i});this.selectees.each(function(){var k=a.data(this,"selectable-item");if(!k||k.element==d.element[0]){return}var l=false;if(f.tolerance=="touch"){l=(!(k.left>c||k.right<e||k.top>h||k.bottom<i))}else{if(f.tolerance=="fit"){l=(k.left>e&&k.right<c&&k.top>i&&k.bottom<h)}}if(l){if(k.selected){k.$element.removeClass("ui-selected");k.selected=false}if(k.unselecting){k.$element.removeClass("ui-unselecting");k.unselecting=false}if(!k.selecting){k.$element.addClass("ui-selecting");k.selecting=true;d._trigger("selecting",j,{selecting:k.element})}}else{if(k.selecting){if((j.metaKey||j.ctrlKey)&&k.startselected){k.$element.removeClass("ui-selecting");k.selecting=false;k.$element.addClass("ui-selected");k.selected=true}else{k.$element.removeClass("ui-selecting");k.selecting=false;if(k.startselected){k.$element.addClass("ui-unselecting");k.unselecting=true}d._trigger("unselecting",j,{unselecting:k.element})}}if(k.selected){if(!j.metaKey&&!j.ctrlKey&&!k.startselected){k.$element.removeClass("ui-selected");k.selected=false;k.$element.addClass("ui-unselecting");k.unselecting=true;d._trigger("unselecting",j,{unselecting:k.element})}}}});return false},_mouseStop:function(e){var c=this;this.dragged=false;var d=this.options;a(".ui-unselecting",this.element[0]).each(function(){var f=a.data(this,"selectable-item");f.$element.removeClass("ui-unselecting");f.unselecting=false;f.startselected=false;c._trigger("unselected",e,{unselected:f.element})});a(".ui-selecting",this.element[0]).each(function(){var f=a.data(this,"selectable-item");f.$element.removeClass("ui-selecting").addClass("ui-selected");f.selecting=false;f.selected=true;f.startselected=true;c._trigger("selected",e,{selected:f.element})});this._trigger("stop",e);this.helper.remove();return false}});a.extend(a.ui.selectable,{version:"1.8.24"})})(jQuery);(function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000},_create:function(){var c=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?c.axis==="x"||(/left|right/).test(this.items[0].item.css("float"))||(/inline|table-cell/).test(this.items[0].item.css("display")):false;this.offset=this.element.offset();this._mouseInit();this.ready=true},destroy:function(){a.Widget.prototype.destroy.call(this);this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var c=this.items.length-1;c>=0;c--){this.items[c].item.removeData(this.widgetName+"-item")}return this},_setOption:function(c,d){if(c==="disabled"){this.options[c]=d;this.widget()[d?"addClass":"removeClass"]("ui-sortable-disabled")}else{a.Widget.prototype._setOption.apply(this,arguments)}},_mouseCapture:function(g,h){var f=this;if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(g);var e=null,d=this,c=a(g.target).parents().each(function(){if(a.data(this,f.widgetName+"-item")==d){e=a(this);return false}});if(a.data(g.target,f.widgetName+"-item")==d){e=a(g.target)}if(!e){return false}if(this.options.handle&&!h){var i=false;a(this.options.handle,e).find("*").andSelf().each(function(){if(this==g.target){i=true}});if(!i){return false}}this.currentItem=e;this._removeCurrentsFromItems();return true},_mouseStart:function(f,g,c){var h=this.options,d=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(f);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:f.pageX-this.offset.left,top:f.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(f);this.originalPageX=f.pageX;this.originalPageY=f.pageY;(h.cursorAt&&this._adjustOffsetFromHelper(h.cursorAt));this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(h.containment){this._setContainment()}if(h.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",h.cursor)}if(h.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",h.opacity)}if(h.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",h.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",f,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!c){for(var e=this.containers.length-1;e>=0;e--){this.containers[e]._trigger("activate",f,d._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(f);return true},_mouseDrag:function(g){this.position=this._generatePosition(g);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var h=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-g.pageY<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+h.scrollSpeed}else{if(g.pageY-this.overflowOffset.top<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-h.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-g.pageX<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+h.scrollSpeed}else{if(g.pageX-this.overflowOffset.left<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-h.scrollSpeed}}}else{if(g.pageY-a(document).scrollTop()<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-h.scrollSpeed)}else{if(a(window).height()-(g.pageY-a(document).scrollTop())<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+h.scrollSpeed)}}if(g.pageX-a(document).scrollLeft()<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-h.scrollSpeed)}else{if(a(window).width()-(g.pageX-a(document).scrollLeft())<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+h.scrollSpeed)}}}if(c!==false&&a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,g)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],d=f.item[0],j=this._intersectsWithPointer(f);if(!j){continue}if(f.instance!==this.currentContainer){continue}if(d!=this.currentItem[0]&&this.placeholder[j==1?"next":"prev"]()[0]!=d&&!a.ui.contains(this.placeholder[0],d)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],d):true)){this.direction=j==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f)){this._rearrange(g,f)}else{break}this._trigger("change",g,this._uiHash());break}}this._contactContainers(g);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,g)}this._trigger("sort",g,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(d,e){if(!d){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,d)}if(this.options.revert){var c=this;var f=c.placeholder.offset();c.reverting=true;a(this.helper).animate({left:f.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:f.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(d)})}else{this._clear(d,e)}return false},cancel:function(){var c=this;if(this.dragging){this._mouseUp({target:null});if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("deactivate",null,c._uiHash(this));if(this.containers[d].containerCache.over){this.containers[d]._trigger("out",null,c._uiHash(this));this.containers[d].containerCache.over=0}}}if(this.placeholder){if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}}return this},serialize:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};a(c).each(function(){var f=(a(e.item||this).attr(e.attribute||"id")||"").match(e.expression||(/(.+)[-=_](.+)/));if(f){d.push((e.key||f[1]+"[]")+"="+(e.key&&e.expression?f[1]:f[2]))}});if(!d.length&&e.key){d.push(e.key+"=")}return d.join("&")},toArray:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};c.each(function(){d.push(a(e.item||this).attr(e.attribute||"id")||"")});return d},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(e){var f=(this.options.axis==="x")||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),d=(this.options.axis==="y")||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),h=f&&d,c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(!h){return false}return this.floating?(((g&&g=="right")||c=="down")?2:1):(c&&(c=="down"?2:1))},_intersectsWithSides:function(f){var d=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,f.top+(f.height/2),f.height),e=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,f.left+(f.width/2),f.width),c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(this.floating&&g){return((g=="right"&&e)||(g=="left"&&!e))}else{return c&&((c=="down"&&d)||(c=="up"&&!d))}},_getDragVerticalDirection:function(){var c=this.positionAbs.top-this.lastPositionAbs.top;return c!=0&&(c>0?"down":"up")},_getDragHorizontalDirection:function(){var c=this.positionAbs.left-this.lastPositionAbs.left;return c!=0&&(c>0?"right":"left")},refresh:function(c){this._refreshItems(c);this.refreshPositions();return this},_connectWith:function(){var c=this.options;return c.connectWith.constructor==String?[c.connectWith]:c.connectWith},_getItemsAsjQuery:function(c){var m=this;var h=[];var f=[];var k=this._connectWith();if(k&&c){for(var e=k.length-1;e>=0;e--){var l=a(k[e]);for(var d=l.length-1;d>=0;d--){var g=a.data(l[d],this.widgetName);if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element):a(g.options.items,g.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),g])}}}}f.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var e=f.length-1;e>=0;e--){f[e][0].each(function(){h.push(this)})}return a(h)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");for(var d=0;d<this.items.length;d++){for(var c=0;c<e.length;c++){if(e[c]==this.items[d].item[0]){this.items.splice(d,1)}}}},_refreshItems:function(c){this.items=[];this.containers=[this];var k=this.items;var q=this;var g=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],c,{item:this.currentItem}):a(this.options.items,this.element),this]];var m=this._connectWith();if(m&&this.ready){for(var f=m.length-1;f>=0;f--){var n=a(m[f]);for(var e=n.length-1;e>=0;e--){var h=a.data(n[e],this.widgetName);if(h&&h!=this&&!h.options.disabled){g.push([a.isFunction(h.options.items)?h.options.items.call(h.element[0],c,{item:this.currentItem}):a(h.options.items,h.element),h]);this.containers.push(h)}}}}for(var f=g.length-1;f>=0;f--){var l=g[f][1];var d=g[f][0];for(var e=0,o=d.length;e<o;e++){var p=a(d[e]);p.data(this.widgetName+"-item",l);k.push({item:p,instance:l,width:0,height:0,left:0,top:0})}}},refreshPositions:function(c){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e];if(f.instance!=this.currentContainer&&this.currentContainer&&f.item[0]!=this.currentItem[0]){continue}var d=this.options.toleranceElement?a(this.options.toleranceElement,f.item):f.item;if(!c){f.width=d.outerWidth();f.height=d.outerHeight()}var g=d.offset();f.left=g.left;f.top=g.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var e=this.containers.length-1;e>=0;e--){var g=this.containers[e].element.offset();this.containers[e].containerCache.left=g.left;this.containers[e].containerCache.top=g.top;this.containers[e].containerCache.width=this.containers[e].element.outerWidth();this.containers[e].containerCache.height=this.containers[e].element.outerHeight()}}return this},_createPlaceholder:function(e){var c=e||this,f=c.options;if(!f.placeholder||f.placeholder.constructor==String){var d=f.placeholder;f.placeholder={element:function(){var g=a(document.createElement(c.currentItem[0].nodeName)).addClass(d||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!d){g.style.visibility="hidden"}return g},update:function(g,h){if(d&&!f.forcePlaceholderSize){return}if(!h.height()){h.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10))}if(!h.width()){h.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}}c.placeholder=a(f.placeholder.element.call(c.element,c.currentItem));c.currentItem.after(c.placeholder);f.placeholder.update(c,c.placeholder)},_contactContainers:function(c){var e=null,l=null;for(var g=this.containers.length-1;g>=0;g--){if(a.ui.contains(this.currentItem[0],this.containers[g].element[0])){continue}if(this._intersectsWith(this.containers[g].containerCache)){if(e&&a.ui.contains(this.containers[g].element[0],e.element[0])){continue}e=this.containers[g];l=g}else{if(this.containers[g].containerCache.over){this.containers[g]._trigger("out",c,this._uiHash(this));this.containers[g].containerCache.over=0}}}if(!e){return}if(this.containers.length===1){this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}else{if(this.currentContainer!=this.containers[l]){var k=10000;var h=null;var d=this.positionAbs[this.containers[l].floating?"left":"top"];for(var f=this.items.length-1;f>=0;f--){if(!a.ui.contains(this.containers[l].element[0],this.items[f].item[0])){continue}var m=this.containers[l].floating?this.items[f].item.offset().left:this.items[f].item.offset().top;if(Math.abs(m-d)<k){k=Math.abs(m-d);h=this.items[f];this.direction=(m-d>0)?"down":"up"}}if(!h&&!this.options.dropOnEmpty){return}this.currentContainer=this.containers[l];h?this._rearrange(c,h,null,true):this._rearrange(c,null,this.containers[l].element,true);this._trigger("change",c,this._uiHash());this.containers[l]._trigger("change",c,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}}},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d,this.currentItem])):(e.helper=="clone"?this.currentItem.clone():this.currentItem);if(!c.parents("body").length){a(e.appendTo!="parent"?e.appendTo:this.currentItem[0].parentNode)[0].appendChild(c[0])}if(c[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(c[0].style.width==""||e.forceHelperSize){c.width(this.currentItem.width())}if(c[0].style.height==""||e.forceHelperSize){c.height(this.currentItem.height())}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.currentItem.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var f=this.options;if(f.containment=="parent"){f.containment=this.helper[0].parentNode}if(f.containment=="document"||f.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(f.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(f.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(f.containment)){var d=a(f.containment)[0];var e=a(f.containment).offset();var c=(a(d).css("overflow")!="hidden");this.containment=[e.left+(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0)-this.margins.left,e.top+(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0)-this.margins.top,e.left+(c?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,e.top+(c?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(f){var i=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,j=(/(html|body)/i).test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var e=f.pageX;var d=f.pageY;if(this.originalPosition){if(this.containment){if(f.pageX-this.offset.click.left<this.containment[0]){e=this.containment[0]+this.offset.click.left}if(f.pageY-this.offset.click.top<this.containment[1]){d=this.containment[1]+this.offset.click.top}if(f.pageX-this.offset.click.left>this.containment[2]){e=this.containment[2]+this.offset.click.left}if(f.pageY-this.offset.click.top>this.containment[3]){d=this.containment[3]+this.offset.click.top}}if(i.grid){var h=this.originalPageY+Math.round((d-this.originalPageY)/i.grid[1])*i.grid[1];d=this.containment?(!(h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3])?h:(!(h-this.offset.click.top<this.containment[1])?h-i.grid[1]:h+i.grid[1])):h;var g=this.originalPageX+Math.round((e-this.originalPageX)/i.grid[0])*i.grid[0];e=this.containment?(!(g-this.offset.click.left<this.containment[0]||g-this.offset.click.left>this.containment[2])?g:(!(g-this.offset.click.left<this.containment[0])?g-i.grid[0]:g+i.grid[0])):g}}return{top:(d-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(j?0:c.scrollTop())))),left:(e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():j?0:c.scrollLeft())))}},_rearrange:function(h,g,d,f){d?d[0].appendChild(this.placeholder[0]):g.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?g.item[0]:g.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var e=this,c=this.counter;window.setTimeout(function(){if(c==e.counter){e.refreshPositions(!f)}},0)},_clear:function(e,f){this.reverting=false;var g=[],c=this;if(!this._noFinalSort&&this.currentItem.parent().length){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var d in this._storedCSS){if(this._storedCSS[d]=="auto"||this._storedCSS[d]=="static"){this._storedCSS[d]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!f){g.push(function(h){this._trigger("receive",h,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!f){g.push(function(h){this._trigger("update",h,this._uiHash())})}if(this!==this.currentContainer){if(!f){g.push(function(h){this._trigger("remove",h,this._uiHash())});g.push((function(h){return function(i){h._trigger("receive",i,this._uiHash(this))}}).call(this,this.currentContainer));g.push((function(h){return function(i){h._trigger("update",i,this._uiHash(this))}}).call(this,this.currentContainer))}}for(var d=this.containers.length-1;d>=0;d--){if(!f){g.push((function(h){return function(i){h._trigger("deactivate",i,this._uiHash(this))}}).call(this,this.containers[d]))}if(this.containers[d].containerCache.over){g.push((function(h){return function(i){h._trigger("out",i,this._uiHash(this))}}).call(this,this.containers[d]));this.containers[d].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!f){this._trigger("beforeStop",e,this._uiHash());for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return false}if(!f){this._trigger("beforeStop",e,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!f){for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(d){var c=d||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:d?d.element:null}}});a.extend(a.ui.sortable,{version:"1.8.24"})})(jQuery);jQuery.effects||(function(h,e){h.effects={};h.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(o,n){h.fx.step[n]=function(p){if(!p.colorInit){p.start=m(p.elem,n);p.end=k(p.end);p.colorInit=true}p.elem.style[n]="rgb("+Math.max(Math.min(parseInt((p.pos*(p.end[0]-p.start[0]))+p.start[0],10),255),0)+","+Math.max(Math.min(parseInt((p.pos*(p.end[1]-p.start[1]))+p.start[1],10),255),0)+","+Math.max(Math.min(parseInt((p.pos*(p.end[2]-p.start[2]))+p.start[2],10),255),0)+")"}});function k(o){var n;if(o&&o.constructor==Array&&o.length==3){return o}if(n=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(o)){return[parseInt(n[1],10),parseInt(n[2],10),parseInt(n[3],10)]}if(n=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(o)){return[parseFloat(n[1])*2.55,parseFloat(n[2])*2.55,parseFloat(n[3])*2.55]}if(n=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(o)){return[parseInt(n[1],16),parseInt(n[2],16),parseInt(n[3],16)]}if(n=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(o)){return[parseInt(n[1]+n[1],16),parseInt(n[2]+n[2],16),parseInt(n[3]+n[3],16)]}if(n=/rgba\(0, 0, 0, 0\)/.exec(o)){return a.transparent}return a[h.trim(o).toLowerCase()]}function m(p,n){var o;do{o=(h.curCSS||h.css)(p,n);if(o!=""&&o!="transparent"||h.nodeName(p,"body")){break}n="backgroundColor"}while(p=p.parentNode);return k(o)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};var f=["add","remove","toggle"],c={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};function g(){var q=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,r={},o,p;if(q&&q.length&&q[0]&&q[q[0]]){var n=q.length;while(n--){o=q[n];if(typeof q[o]=="string"){p=o.replace(/\-(\w)/g,function(s,t){return t.toUpperCase()});r[p]=q[o]}}}else{for(o in q){if(typeof q[o]==="string"){r[o]=q[o]}}}return r}function b(o){var n,p;for(n in o){p=o[n];if(p==null||h.isFunction(p)||n in c||(/scrollbar/).test(n)||(!(/color/i).test(n)&&isNaN(parseFloat(p)))){delete o[n]}}return o}function i(n,p){var q={_:0},o;for(o in p){if(n[o]!=p[o]){q[o]=p[o]}}return q}h.effects.animateClass=function(n,o,q,p){if(h.isFunction(q)){p=q;q=null}return this.queue(function(){var u=h(this),r=u.attr("style")||" ",v=b(g.call(this)),t,s=u.attr("class")||"";h.each(f,function(w,x){if(n[x]){u[x+"Class"](n[x])}});t=b(g.call(this));u.attr("class",s);u.animate(i(v,t),{queue:false,duration:o,easing:q,complete:function(){h.each(f,function(w,x){if(n[x]){u[x+"Class"](n[x])}});if(typeof u.attr("style")=="object"){u.attr("style").cssText="";u.attr("style").cssText=r}else{u.attr("style",r)}if(p){p.apply(this,arguments)}h.dequeue(this)}})})};h.fn.extend({_addClass:h.fn.addClass,addClass:function(o,n,q,p){return n?h.effects.animateClass.apply(this,[{add:o},n,q,p]):this._addClass(o)},_removeClass:h.fn.removeClass,removeClass:function(o,n,q,p){return n?h.effects.animateClass.apply(this,[{remove:o},n,q,p]):this._removeClass(o)},_toggleClass:h.fn.toggleClass,toggleClass:function(p,o,n,r,q){if(typeof o=="boolean"||o===e){if(!n){return this._toggleClass(p,o)}else{return h.effects.animateClass.apply(this,[(o?{add:p}:{remove:p}),n,r,q])}}else{return h.effects.animateClass.apply(this,[{toggle:p},o,n,r])}},switchClass:function(n,p,o,r,q){return h.effects.animateClass.apply(this,[{add:p,remove:n},o,r,q])}});h.extend(h.effects,{version:"1.8.24",save:function(o,p){for(var n=0;n<p.length;n++){if(p[n]!==null){o.data("ec.storage."+p[n],o[0].style[p[n]])}}},restore:function(o,p){for(var n=0;n<p.length;n++){if(p[n]!==null){o.css(p[n],o.data("ec.storage."+p[n]))}}},setMode:function(n,o){if(o=="toggle"){o=n.is(":hidden")?"show":"hide"}return o},getBaseline:function(o,p){var q,n;switch(o[0]){case"top":q=0;break;case"middle":q=0.5;break;case"bottom":q=1;break;default:q=o[0]/p.height}switch(o[1]){case"left":n=0;break;case"center":n=0.5;break;case"right":n=1;break;default:n=o[1]/p.width}return{x:n,y:q}},createWrapper:function(n){if(n.parent().is(".ui-effects-wrapper")){return n.parent()}var o={width:n.outerWidth(true),height:n.outerHeight(true),"float":n.css("float")},r=h("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),q=document.activeElement;try{q.id}catch(p){q=document.body}n.wrap(r);if(n[0]===q||h.contains(n[0],q)){h(q).focus()}r=n.parent();if(n.css("position")=="static"){r.css({position:"relative"});n.css({position:"relative"})}else{h.extend(o,{position:n.css("position"),zIndex:n.css("z-index")});h.each(["top","left","bottom","right"],function(s,t){o[t]=n.css(t);if(isNaN(parseInt(o[t],10))){o[t]="auto"}});n.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})}return r.css(o).show()},removeWrapper:function(n){var o,p=document.activeElement;if(n.parent().is(".ui-effects-wrapper")){o=n.parent().replaceWith(n);if(n[0]===p||h.contains(n[0],p)){h(p).focus()}return o}return n},setTransition:function(o,q,n,p){p=p||{};h.each(q,function(s,r){var t=o.cssUnit(r);if(t[0]>0){p[r]=t[0]*n+t[1]}});return p}});function d(o,n,p,q){if(typeof o=="object"){q=n;p=null;n=o;o=n.effect}if(h.isFunction(n)){q=n;p=null;n={}}if(typeof n=="number"||h.fx.speeds[n]){q=p;p=n;n={}}if(h.isFunction(p)){q=p;p=null}n=n||{};p=p||n.duration;p=h.fx.off?0:typeof p=="number"?p:p in h.fx.speeds?h.fx.speeds[p]:h.fx.speeds._default;q=q||n.complete;return[o,n,p,q]}function l(n){if(!n||typeof n==="number"||h.fx.speeds[n]){return true}if(typeof n==="string"&&!h.effects[n]){return true}return false}h.fn.extend({effect:function(q,p,s,u){var o=d.apply(this,arguments),r={options:o[1],duration:o[2],callback:o[3]},t=r.options.mode,n=h.effects[q];if(h.fx.off||!n){if(t){return this[t](r.duration,r.callback)}else{return this.each(function(){if(r.callback){r.callback.call(this)}})}}return n.call(this,r)},_show:h.fn.show,show:function(o){if(l(o)){return this._show.apply(this,arguments)}else{var n=d.apply(this,arguments);n[1].mode="show";return this.effect.apply(this,n)}},_hide:h.fn.hide,hide:function(o){if(l(o)){return this._hide.apply(this,arguments)}else{var n=d.apply(this,arguments);n[1].mode="hide";return this.effect.apply(this,n)}},__toggle:h.fn.toggle,toggle:function(o){if(l(o)||typeof o==="boolean"||h.isFunction(o)){return this.__toggle.apply(this,arguments)}else{var n=d.apply(this,arguments);n[1].mode="toggle";return this.effect.apply(this,n)}},cssUnit:function(n){var o=this.css(n),p=[];h.each(["em","px","%","pt"],function(q,r){if(o.indexOf(r)>0){p=[parseFloat(o),r]}});return p}});var j={};h.each(["Quad","Cubic","Quart","Quint","Expo"],function(o,n){j[n]=function(q){return Math.pow(q,o+2)}});h.extend(j,{Sine:function(n){return 1-Math.cos(n*Math.PI/2)},Circ:function(n){return 1-Math.sqrt(1-n*n)},Elastic:function(n){return n===0||n===1?n:-Math.pow(2,8*(n-1))*Math.sin(((n-1)*80-7.5)*Math.PI/15)},Back:function(n){return n*n*(3*n-2)},Bounce:function(q){var n,o=4;while(q<((n=Math.pow(2,--o))-1)/11){}return 1/Math.pow(4,3-o)-7.5625*Math.pow((n*3-2)/22-q,2)}});h.each(j,function(o,n){h.easing["easeIn"+o]=n;h.easing["easeOut"+o]=function(q){return 1-n(1-q)};h.easing["easeInOut"+o]=function(q){return q<0.5?n(q*2)/2:n(q*-2+2)/-2+1}})})(jQuery);(function(a,b){a.effects.blind=function(c){return this.queue(function(){var e=a(this),d=["position","top","bottom","left","right"];var i=a.effects.setMode(e,c.options.mode||"hide");var h=c.options.direction||"vertical";a.effects.save(e,d);e.show();var k=a.effects.createWrapper(e).css({overflow:"hidden"});var f=(h=="vertical")?"height":"width";var j=(h=="vertical")?k.height():k.width();if(i=="show"){k.css(f,0)}var g={};g[f]=i=="show"?j:0;k.animate(g,c.duration,c.options.easing,function(){if(i=="hide"){e.hide()}a.effects.restore(e,d);a.effects.removeWrapper(e);if(c.callback){c.callback.apply(e[0],arguments)}e.dequeue()})})}})(jQuery);(function(a,b){a.effects.bounce=function(c){return this.queue(function(){var f=a(this),m=["position","top","bottom","left","right"];var l=a.effects.setMode(f,c.options.mode||"effect");var o=c.options.direction||"up";var d=c.options.distance||20;var e=c.options.times||5;var h=c.duration||250;if(/show|hide/.test(l)){m.push("opacity")}a.effects.save(f,m);f.show();a.effects.createWrapper(f);var g=(o=="up"||o=="down")?"top":"left";var q=(o=="up"||o=="left")?"pos":"neg";var d=c.options.distance||(g=="top"?f.outerHeight(true)/3:f.outerWidth(true)/3);if(l=="show"){f.css("opacity",0).css(g,q=="pos"?-d:d)}if(l=="hide"){d=d/(e*2)}if(l!="hide"){e--}if(l=="show"){var j={opacity:1};j[g]=(q=="pos"?"+=":"-=")+d;f.animate(j,h/2,c.options.easing);d=d/2;e--}for(var k=0;k<e;k++){var p={},n={};p[g]=(q=="pos"?"-=":"+=")+d;n[g]=(q=="pos"?"+=":"-=")+d;f.animate(p,h/2,c.options.easing).animate(n,h/2,c.options.easing);d=(l=="hide")?d*2:d/2}if(l=="hide"){var j={opacity:0};j[g]=(q=="pos"?"-=":"+=")+d;f.animate(j,h/2,c.options.easing,function(){f.hide();a.effects.restore(f,m);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}})}else{var p={},n={};p[g]=(q=="pos"?"-=":"+=")+d;n[g]=(q=="pos"?"+=":"-=")+d;f.animate(p,h/2,c.options.easing).animate(n,h/2,c.options.easing,function(){a.effects.restore(f,m);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}})}f.queue("fx",function(){f.dequeue()});f.dequeue()})}})(jQuery);(function(a,b){a.effects.clip=function(c){return this.queue(function(){var g=a(this),k=["position","top","bottom","left","right","height","width"];var j=a.effects.setMode(g,c.options.mode||"hide");var l=c.options.direction||"vertical";a.effects.save(g,k);g.show();var d=a.effects.createWrapper(g).css({overflow:"hidden"});var f=g[0].tagName=="IMG"?d:g;var h={size:(l=="vertical")?"height":"width",position:(l=="vertical")?"top":"left"};var e=(l=="vertical")?f.height():f.width();if(j=="show"){f.css(h.size,0);f.css(h.position,e/2)}var i={};i[h.size]=j=="show"?e:0;i[h.position]=j=="show"?0:e/2;f.animate(i,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(j=="hide"){g.hide()}a.effects.restore(g,k);a.effects.removeWrapper(g);if(c.callback){c.callback.apply(g[0],arguments)}g.dequeue()}})})}})(jQuery);(function(a,b){a.effects.drop=function(c){return this.queue(function(){var f=a(this),e=["position","top","bottom","left","right","opacity"];var j=a.effects.setMode(f,c.options.mode||"hide");var i=c.options.direction||"left";a.effects.save(f,e);f.show();a.effects.createWrapper(f);var g=(i=="up"||i=="down")?"top":"left";var d=(i=="up"||i=="left")?"pos":"neg";var k=c.options.distance||(g=="top"?f.outerHeight(true)/2:f.outerWidth(true)/2);if(j=="show"){f.css("opacity",0).css(g,d=="pos"?-k:k)}var h={opacity:j=="show"?1:0};h[g]=(j=="show"?(d=="pos"?"+=":"-="):(d=="pos"?"-=":"+="))+k;f.animate(h,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(j=="hide"){f.hide()}a.effects.restore(f,e);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}f.dequeue()}})})}})(jQuery);(function(a,b){a.effects.explode=function(c){return this.queue(function(){var l=c.options.pieces?Math.round(Math.sqrt(c.options.pieces)):3;var f=c.options.pieces?Math.round(Math.sqrt(c.options.pieces)):3;c.options.mode=c.options.mode=="toggle"?(a(this).is(":visible")?"hide":"show"):c.options.mode;var k=a(this).show().css("visibility","hidden");var m=k.offset();m.top-=parseInt(k.css("marginTop"),10)||0;m.left-=parseInt(k.css("marginLeft"),10)||0;var h=k.outerWidth(true);var d=k.outerHeight(true);for(var g=0;g<l;g++){for(var e=0;e<f;e++){k.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-e*(h/f),top:-g*(d/l)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/f,height:d/l,left:m.left+e*(h/f)+(c.options.mode=="show"?(e-Math.floor(f/2))*(h/f):0),top:m.top+g*(d/l)+(c.options.mode=="show"?(g-Math.floor(l/2))*(d/l):0),opacity:c.options.mode=="show"?0:1}).animate({left:m.left+e*(h/f)+(c.options.mode=="show"?0:(e-Math.floor(f/2))*(h/f)),top:m.top+g*(d/l)+(c.options.mode=="show"?0:(g-Math.floor(l/2))*(d/l)),opacity:c.options.mode=="show"?1:0},c.duration||500)}}setTimeout(function(){c.options.mode=="show"?k.css({visibility:"visible"}):k.css({visibility:"visible"}).hide();if(c.callback){c.callback.apply(k[0])}k.dequeue();a("div.ui-effects-explode").remove()},c.duration||500)})}})(jQuery);(function(a,b){a.effects.fade=function(c){return this.queue(function(){var d=a(this),e=a.effects.setMode(d,c.options.mode||"hide");d.animate({opacity:e},{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){(c.callback&&c.callback.apply(this,arguments));d.dequeue()}})})}})(jQuery);(function(a,b){a.effects.fold=function(c){return this.queue(function(){var f=a(this),l=["position","top","bottom","left","right"];var i=a.effects.setMode(f,c.options.mode||"hide");var p=c.options.size||15;var o=!(!c.options.horizFirst);var h=c.duration?c.duration/2:a.fx.speeds._default/2;a.effects.save(f,l);f.show();var e=a.effects.createWrapper(f).css({overflow:"hidden"});var j=((i=="show")!=o);var g=j?["width","height"]:["height","width"];var d=j?[e.width(),e.height()]:[e.height(),e.width()];var k=/([0-9]+)%/.exec(p);if(k){p=parseInt(k[1],10)/100*d[i=="hide"?0:1]}if(i=="show"){e.css(o?{height:0,width:p}:{height:p,width:0})}var n={},m={};n[g[0]]=i=="show"?d[0]:p;m[g[1]]=i=="show"?d[1]:0;e.animate(n,h,c.options.easing).animate(m,h,c.options.easing,function(){if(i=="hide"){f.hide()}a.effects.restore(f,l);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(f[0],arguments)}f.dequeue()})})}})(jQuery);(function(a,b){a.effects.highlight=function(c){return this.queue(function(){var e=a(this),d=["backgroundImage","backgroundColor","opacity"],g=a.effects.setMode(e,c.options.mode||"show"),f={backgroundColor:e.css("backgroundColor")};if(g=="hide"){f.opacity=0}a.effects.save(e,d);e.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){(g=="hide"&&e.hide());a.effects.restore(e,d);(g=="show"&&!a.support.opacity&&this.style.removeAttribute("filter"));(c.callback&&c.callback.apply(this,arguments));e.dequeue()}})})}})(jQuery);(function(a,b){a.effects.pulsate=function(c){return this.queue(function(){var g=a(this),k=a.effects.setMode(g,c.options.mode||"show"),j=((c.options.times||5)*2)-1,h=c.duration?c.duration/2:a.fx.speeds._default/2,d=g.is(":visible"),e=0;if(!d){g.css("opacity",0).show();e=1}if((k=="hide"&&d)||(k=="show"&&!d)){j--}for(var f=0;f<j;f++){g.animate({opacity:e},h,c.options.easing);e=(e+1)%2}g.animate({opacity:e},h,c.options.easing,function(){if(e==0){g.hide()}(c.callback&&c.callback.apply(this,arguments))});g.queue("fx",function(){g.dequeue()}).dequeue()})}})(jQuery);(function(a,b){a.effects.puff=function(c){return this.queue(function(){var g=a(this),h=a.effects.setMode(g,c.options.mode||"hide"),f=parseInt(c.options.percent,10)||150,e=f/100,d={height:g.height(),width:g.width()};a.extend(c.options,{fade:true,mode:h,percent:h=="hide"?f:100,from:h=="hide"?d:{height:d.height*e,width:d.width*e}});g.effect("scale",c.options,c.duration,c.callback);g.dequeue()})};a.effects.scale=function(c){return this.queue(function(){var h=a(this);var e=a.extend(true,{},c.options);var k=a.effects.setMode(h,c.options.mode||"effect");var i=parseInt(c.options.percent,10)||(parseInt(c.options.percent,10)==0?0:(k=="hide"?0:100));var j=c.options.direction||"both";var d=c.options.origin;if(k!="effect"){e.origin=d||["middle","center"];e.restore=true}var g={height:h.height(),width:h.width()};h.from=c.options.from||(k=="show"?{height:0,width:0}:g);var f={y:j!="horizontal"?(i/100):1,x:j!="vertical"?(i/100):1};h.to={height:g.height*f.y,width:g.width*f.x};if(c.options.fade){if(k=="show"){h.from.opacity=0;h.to.opacity=1}if(k=="hide"){h.from.opacity=1;h.to.opacity=0}}e.from=h.from;e.to=h.to;e.mode=k;h.effect("size",e,c.duration,c.callback);h.dequeue()})};a.effects.size=function(c){return this.queue(function(){var d=a(this),o=["position","top","bottom","left","right","width","height","overflow","opacity"];var n=["position","top","bottom","left","right","overflow","opacity"];var k=["width","height","overflow"];var q=["fontSize"];var l=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"];var g=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"];var h=a.effects.setMode(d,c.options.mode||"effect");var j=c.options.restore||false;var f=c.options.scale||"both";var p=c.options.origin;var e={height:d.height(),width:d.width()};d.from=c.options.from||e;d.to=c.options.to||e;if(p){var i=a.effects.getBaseline(p,e);d.from.top=(e.height-d.from.height)*i.y;d.from.left=(e.width-d.from.width)*i.x;d.to.top=(e.height-d.to.height)*i.y;d.to.left=(e.width-d.to.width)*i.x}var m={from:{y:d.from.height/e.height,x:d.from.width/e.width},to:{y:d.to.height/e.height,x:d.to.width/e.width}};if(f=="box"||f=="both"){if(m.from.y!=m.to.y){o=o.concat(l);d.from=a.effects.setTransition(d,l,m.from.y,d.from);d.to=a.effects.setTransition(d,l,m.to.y,d.to)}if(m.from.x!=m.to.x){o=o.concat(g);d.from=a.effects.setTransition(d,g,m.from.x,d.from);d.to=a.effects.setTransition(d,g,m.to.x,d.to)}}if(f=="content"||f=="both"){if(m.from.y!=m.to.y){o=o.concat(q);d.from=a.effects.setTransition(d,q,m.from.y,d.from);d.to=a.effects.setTransition(d,q,m.to.y,d.to)}}a.effects.save(d,j?o:n);d.show();a.effects.createWrapper(d);d.css("overflow","hidden").css(d.from);if(f=="content"||f=="both"){l=l.concat(["marginTop","marginBottom"]).concat(q);g=g.concat(["marginLeft","marginRight"]);k=o.concat(l).concat(g);d.find("*[width]").each(function(){var s=a(this);if(j){a.effects.save(s,k)}var r={height:s.height(),width:s.width()};s.from={height:r.height*m.from.y,width:r.width*m.from.x};s.to={height:r.height*m.to.y,width:r.width*m.to.x};if(m.from.y!=m.to.y){s.from=a.effects.setTransition(s,l,m.from.y,s.from);s.to=a.effects.setTransition(s,l,m.to.y,s.to)}if(m.from.x!=m.to.x){s.from=a.effects.setTransition(s,g,m.from.x,s.from);s.to=a.effects.setTransition(s,g,m.to.x,s.to)}s.css(s.from);s.animate(s.to,c.duration,c.options.easing,function(){if(j){a.effects.restore(s,k)}})})}d.animate(d.to,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(d.to.opacity===0){d.css("opacity",d.from.opacity)}if(h=="hide"){d.hide()}a.effects.restore(d,j?o:n);a.effects.removeWrapper(d);if(c.callback){c.callback.apply(this,arguments)}d.dequeue()}})})}})(jQuery);(function(a,b){a.effects.shake=function(c){return this.queue(function(){var f=a(this),m=["position","top","bottom","left","right"];var l=a.effects.setMode(f,c.options.mode||"effect");var o=c.options.direction||"left";var d=c.options.distance||20;var e=c.options.times||3;var h=c.duration||c.options.duration||140;a.effects.save(f,m);f.show();a.effects.createWrapper(f);var g=(o=="up"||o=="down")?"top":"left";var q=(o=="up"||o=="left")?"pos":"neg";var j={},p={},n={};j[g]=(q=="pos"?"-=":"+=")+d;p[g]=(q=="pos"?"+=":"-=")+d*2;n[g]=(q=="pos"?"-=":"+=")+d*2;f.animate(j,h,c.options.easing);for(var k=1;k<e;k++){f.animate(p,h,c.options.easing).animate(n,h,c.options.easing)}f.animate(p,h,c.options.easing).animate(j,h/2,c.options.easing,function(){a.effects.restore(f,m);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}});f.queue("fx",function(){f.dequeue()});f.dequeue()})}})(jQuery);(function(a,b){a.effects.slide=function(c){return this.queue(function(){var f=a(this),e=["position","top","bottom","left","right"];var j=a.effects.setMode(f,c.options.mode||"show");var i=c.options.direction||"left";a.effects.save(f,e);f.show();a.effects.createWrapper(f).css({overflow:"hidden"});var g=(i=="up"||i=="down")?"top":"left";var d=(i=="up"||i=="left")?"pos":"neg";var k=c.options.distance||(g=="top"?f.outerHeight(true):f.outerWidth(true));if(j=="show"){f.css(g,d=="pos"?(isNaN(k)?"-"+k:-k):k)}var h={};h[g]=(j=="show"?(d=="pos"?"+=":"-="):(d=="pos"?"-=":"+="))+k;f.animate(h,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(j=="hide"){f.hide()}a.effects.restore(f,e);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}f.dequeue()}})})}})(jQuery);(function(a,b){a.effects.transfer=function(c){return this.queue(function(){var g=a(this),i=a(c.options.to),f=i.offset(),h={top:f.top,left:f.left,height:i.innerHeight(),width:i.innerWidth()},e=g.offset(),d=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(c.options.className).css({top:e.top,left:e.left,height:g.innerHeight(),width:g.innerWidth(),position:"absolute"}).animate(h,c.duration,c.options.easing,function(){d.remove();(c.callback&&c.callback.apply(g[0],arguments));g.dequeue()})})}})(jQuery);(function(a,b){a.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var c=this,d=c.options;c.running=0;c.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix");c.headers=c.element.find(d.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){if(d.disabled){return}a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){if(d.disabled){return}a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){if(d.disabled){return}a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){if(d.disabled){return}a(this).removeClass("ui-state-focus")});c.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(d.navigation){var e=c.element.find("a").filter(d.navigationFilter).eq(0);if(e.length){var f=e.closest(".ui-accordion-header");if(f.length){c.active=f}else{c.active=e.closest(".ui-accordion-content").prev()}}}c.active=c._findActive(c.active||d.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");c.active.next().addClass("ui-accordion-content-active");c._createIcons();c.resize();c.element.attr("role","tablist");c.headers.attr("role","tab").bind("keydown.accordion",function(g){return c._keydown(g)}).next().attr("role","tabpanel");c.headers.not(c.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide();if(!c.active.length){c.headers.eq(0).attr("tabIndex",0)}else{c.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0})}if(!a.browser.safari){c.headers.find("a").attr("tabIndex",-1)}if(d.event){c.headers.bind(d.event.split(" ").join(".accordion ")+".accordion",function(g){c._clickHandler.call(c,g,this);g.preventDefault()})}},_createIcons:function(){var c=this.options;if(c.icons){a("<span></span>").addClass("ui-icon "+c.icons.header).prependTo(this.headers);this.active.children(".ui-icon").toggleClass(c.icons.header).toggleClass(c.icons.headerSelected);this.element.addClass("ui-accordion-icons")}},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var c=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex");this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var d=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");if(c.autoHeight||c.fillHeight){d.css("height","")}return a.Widget.prototype.destroy.call(this)},_setOption:function(c,d){a.Widget.prototype._setOption.apply(this,arguments);if(c=="active"){this.activate(d)}if(c=="icons"){this._destroyIcons();if(d){this._createIcons()}}if(c=="disabled"){this.headers.add(this.headers.next())[d?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")}},_keydown:function(f){if(this.options.disabled||f.altKey||f.ctrlKey){return}var g=a.ui.keyCode,e=this.headers.length,c=this.headers.index(f.target),d=false;switch(f.keyCode){case g.RIGHT:case g.DOWN:d=this.headers[(c+1)%e];break;case g.LEFT:case g.UP:d=this.headers[(c-1+e)%e];break;case g.SPACE:case g.ENTER:this._clickHandler({target:f.target},f.target);f.preventDefault()}if(d){a(f.target).attr("tabIndex",-1);a(d).attr("tabIndex",0);d.focus();return false}return true},resize:function(){var c=this.options,e;if(c.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}e=this.element.parent().height();if(a.browser.msie){this.element.parent().css("overflow",d)}this.headers.each(function(){e-=a(this).outerHeight(true)});this.headers.next().each(function(){a(this).height(Math.max(0,e-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else{if(c.autoHeight){e=0;this.headers.next().each(function(){e=Math.max(e,a(this).height("").height())}).height(e)}}return this},activate:function(c){this.options.active=c;var d=this._findActive(c)[0];this._clickHandler({target:d},d);return this},_findActive:function(c){return c?typeof c==="number"?this.headers.filter(":eq("+c+")"):this.headers.not(this.headers.not(c)):c===false?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(c,g){var l=this.options;if(l.disabled){return}if(!c.target){if(!l.collapsible){return}this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(l.icons.headerSelected).addClass(l.icons.header);this.active.next().addClass("ui-accordion-content-active");var i=this.active.next(),f={options:l,newHeader:a([]),oldHeader:l.active,newContent:a([]),oldContent:i},d=(this.active=a([]));this._toggle(d,i,f);return}var h=a(c.currentTarget||g),j=h[0]===this.active[0];l.active=l.collapsible&&j?false:this.headers.index(h);if(this.running||(!l.collapsible&&j)){return}var e=this.active,d=h.next(),i=this.active.next(),f={options:l,newHeader:j&&l.collapsible?a([]):h,oldHeader:this.active,newContent:j&&l.collapsible?a([]):d,oldContent:i},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=j?a([]):h;this._toggle(d,i,f,j,k);e.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(l.icons.headerSelected).addClass(l.icons.header);if(!j){h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(l.icons.header).addClass(l.icons.headerSelected);h.next().addClass("ui-accordion-content-active")}return},_toggle:function(c,i,g,j,k){var m=this,n=m.options;m.toShow=c;m.toHide=i;m.data=g;var d=function(){if(!m){return}return m._completed.apply(m,arguments)};m._trigger("changestart",null,m.data);m.running=i.size()===0?c.size():i.size();if(n.animated){var f={};if(n.collapsible&&j){f={toShow:a([]),toHide:i,complete:d,down:k,autoHeight:n.autoHeight||n.fillSpace}}else{f={toShow:c,toHide:i,complete:d,down:k,autoHeight:n.autoHeight||n.fillSpace}}if(!n.proxied){n.proxied=n.animated}if(!n.proxiedDuration){n.proxiedDuration=n.duration}n.animated=a.isFunction(n.proxied)?n.proxied(f):n.proxied;n.duration=a.isFunction(n.proxiedDuration)?n.proxiedDuration(f):n.proxiedDuration;var l=a.ui.accordion.animations,e=n.duration,h=n.animated;if(h&&!l[h]&&!a.easing[h]){h="slide"}if(!l[h]){l[h]=function(o){this.slide(o,{easing:h,duration:e||700})}}l[h](f)}else{if(n.collapsible&&j){c.toggle()}else{i.hide();c.show()}d(true)}i.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur();c.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(c){this.running=c?0:--this.running;if(this.running){return}if(this.options.clearStyle){this.toShow.add(this.toHide).css({height:"",overflow:""})}this.toHide.removeClass("ui-accordion-content-active");if(this.toHide.length){this.toHide.parent()[0].className=this.toHide.parent()[0].className}this._trigger("change",null,this.data)}});a.extend(a.ui.accordion,{version:"1.8.24",animations:{slide:function(k,i){k=a.extend({easing:"swing",duration:300},k,i);if(!k.toHide.size()){k.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},k);return}if(!k.toShow.size()){k.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},k);return}var d=k.toShow.css("overflow"),h=0,e={},g={},f=["height","paddingTop","paddingBottom"],c;var j=k.toShow;c=j[0].style.width;j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0));a.each(f,function(l,n){g[n]="hide";var m=(""+a.css(k.toShow[0],n)).match(/^([\d+-.]+)(.*)$/);e[n]={value:m[1],unit:m[2]||"px"}});k.toShow.css({height:0,overflow:"hidden"}).show();k.toHide.filter(":hidden").each(k.complete).end().filter(":visible").animate(g,{step:function(l,m){if(m.prop=="height"){h=(m.end-m.start===0)?0:(m.now-m.start)/(m.end-m.start)}k.toShow[0].style[m.prop]=(h*e[m.prop].value)+e[m.prop].unit},duration:k.duration,easing:k.easing,complete:function(){if(!k.autoHeight){k.toShow.css("height","")}k.toShow.css({width:c,overflow:d});k.complete()}})},bounceslide:function(c){this.slide(c,{easing:c.down?"easeOutBounce":"swing",duration:c.down?1000:200})}}})})(jQuery);(function(a,b){var c=0;a.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:false,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var d=this,f=this.element[0].ownerDocument,e;this.isMultiLine=this.element.is("textarea");this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(g){if(d.options.disabled||d.element.propAttr("readOnly")){return}e=false;var h=a.ui.keyCode;switch(g.keyCode){case h.PAGE_UP:d._move("previousPage",g);break;case h.PAGE_DOWN:d._move("nextPage",g);break;case h.UP:d._keyEvent("previous",g);break;case h.DOWN:d._keyEvent("next",g);break;case h.ENTER:case h.NUMPAD_ENTER:if(d.menu.active){e=true;g.preventDefault()}case h.TAB:if(!d.menu.active){return}d.menu.select(g);break;case h.ESCAPE:d.element.val(d.term);d.close(g);break;default:clearTimeout(d.searching);d.searching=setTimeout(function(){if(d.term!=d.element.val()){d.selectedItem=null;d.search(null,g)}},d.options.delay);break}}).bind("keypress.autocomplete",function(g){if(e){e=false;g.preventDefault()}}).bind("focus.autocomplete",function(){if(d.options.disabled){return}d.selectedItem=null;d.previous=d.element.val()}).bind("blur.autocomplete",function(g){if(d.options.disabled){return}clearTimeout(d.searching);d.closing=setTimeout(function(){d.close(g);d._change(g)},150)});this._initSource();this.menu=a("<ul></ul>").addClass("ui-autocomplete").appendTo(a(this.options.appendTo||"body",f)[0]).mousedown(function(g){var h=d.menu.element[0];if(!a(g.target).closest(".ui-menu-item").length){setTimeout(function(){a(document).one("mousedown",function(i){if(i.target!==d.element[0]&&i.target!==h&&!a.ui.contains(h,i.target)){d.close()}})},1)}setTimeout(function(){clearTimeout(d.closing)},13)}).menu({focus:function(h,i){var g=i.item.data("item.autocomplete");if(false!==d._trigger("focus",h,{item:g})){if(/^key/.test(h.originalEvent.type)){d.element.val(g.value)}}},selected:function(i,j){var h=j.item.data("item.autocomplete"),g=d.previous;if(d.element[0]!==f.activeElement){d.element.focus();d.previous=g;setTimeout(function(){d.previous=g;d.selectedItem=h},1)}if(false!==d._trigger("select",i,{item:h})){d.element.val(h.value)}d.term=d.element.val();d.close(i);d.selectedItem=h},blur:function(g,h){if(d.menu.element.is(":visible")&&(d.element.val()!==d.term)){d.element.val(d.term)}}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");if(a.fn.bgiframe){this.menu.element.bgiframe()}d.beforeunloadHandler=function(){d.element.removeAttr("autocomplete")};a(window).bind("beforeunload",d.beforeunloadHandler)},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");this.menu.element.remove();a(window).unbind("beforeunload",this.beforeunloadHandler);a.Widget.prototype.destroy.call(this)},_setOption:function(d,e){a.Widget.prototype._setOption.apply(this,arguments);if(d==="source"){this._initSource()}if(d==="appendTo"){this.menu.element.appendTo(a(e||"body",this.element[0].ownerDocument)[0])}if(d==="disabled"&&e&&this.xhr){this.xhr.abort()}},_initSource:function(){var d=this,f,e;if(a.isArray(this.options.source)){f=this.options.source;this.source=function(h,g){g(a.ui.autocomplete.filter(f,h.term))}}else{if(typeof this.options.source==="string"){e=this.options.source;this.source=function(h,g){if(d.xhr){d.xhr.abort()}d.xhr=a.ajax({url:e,data:h,dataType:"json",success:function(j,i){g(j)},error:function(){g([])}})}}else{this.source=this.options.source}}},search:function(e,d){e=e!=null?e:this.element.val();this.term=this.element.val();if(e.length<this.options.minLength){return this.close(d)}clearTimeout(this.closing);if(this._trigger("search",d)===false){return}return this._search(e)},_search:function(d){this.pending++;this.element.addClass("ui-autocomplete-loading");this.source({term:d},this._response())},_response:function(){var e=this,d=++c;return function(f){if(d===c){e.__response(f)}e.pending--;if(!e.pending){e.element.removeClass("ui-autocomplete-loading")}}},__response:function(d){if(!this.options.disabled&&d&&d.length){d=this._normalize(d);this._suggest(d);this._trigger("open")}else{this.close()}},close:function(d){clearTimeout(this.closing);if(this.menu.element.is(":visible")){this.menu.element.hide();this.menu.deactivate();this._trigger("close",d)}},_change:function(d){if(this.previous!==this.element.val()){this._trigger("change",d,{item:this.selectedItem})}},_normalize:function(d){if(d.length&&d[0].label&&d[0].value){return d}return a.map(d,function(e){if(typeof e==="string"){return{label:e,value:e}}return a.extend({label:e.label||e.value,value:e.value||e.label},e)})},_suggest:function(d){var e=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(e,d);this.menu.deactivate();this.menu.refresh();e.show();this._resizeMenu();e.position(a.extend({of:this.element},this.options.position));if(this.options.autoFocus){this.menu.next(new a.Event("mouseover"))}},_resizeMenu:function(){var d=this.menu.element;d.outerWidth(Math.max(d.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(f,e){var d=this;a.each(e,function(g,h){d._renderItem(f,h)})},_renderItem:function(d,e){return a("<li></li>").data("item.autocomplete",e).append(a("<a></a>").text(e.label)).appendTo(d)},_move:function(e,d){if(!this.menu.element.is(":visible")){this.search(null,d);return}if(this.menu.first()&&/^previous/.test(e)||this.menu.last()&&/^next/.test(e)){this.element.val(this.term);this.menu.deactivate();return}this.menu[e](d)},widget:function(){return this.menu.element},_keyEvent:function(e,d){if(!this.isMultiLine||this.menu.element.is(":visible")){this._move(e,d);d.preventDefault()}}});a.extend(a.ui.autocomplete,{escapeRegex:function(d){return d.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(f,d){var e=new RegExp(a.ui.autocomplete.escapeRegex(d),"i");return a.grep(f,function(g){return e.test(g.label||g.value||g)})}})}(jQuery));(function(a){a.widget("ui.menu",{_create:function(){var b=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(c){if(!a(c.target).closest(".ui-menu-item a").length){return}c.preventDefault();b.select(c)});this.refresh()},refresh:function(){var c=this;var b=this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem");b.children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(d){c.activate(d,a(this).parent())}).mouseleave(function(){c.deactivate()})},activate:function(e,d){this.deactivate();if(this.hasScroll()){var f=d.offset().top-this.element.offset().top,b=this.element.scrollTop(),c=this.element.height();if(f<0){this.element.scrollTop(b+f)}else{if(f>=c){this.element.scrollTop(b+f-c+d.height())}}}this.active=d.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",e,{item:d})},deactivate:function(){if(!this.active){return}this.active.children("a").removeClass("ui-state-hover").removeAttr("id");this._trigger("blur");this.active=null},next:function(b){this.move("next",".ui-menu-item:first",b)},previous:function(b){this.move("prev",".ui-menu-item:last",b)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(e,d,c){if(!this.active){this.activate(c,this.element.children(d));return}var b=this.active[e+"All"](".ui-menu-item").eq(0);if(b.length){this.activate(c,b)}else{this.activate(c,this.element.children(d))}},nextPage:function(d){if(this.hasScroll()){if(!this.active||this.last()){this.activate(d,this.element.children(".ui-menu-item:first"));return}var e=this.active.offset().top,c=this.element.height(),b=this.element.children(".ui-menu-item").filter(function(){var f=a(this).offset().top-e-c+a(this).height();return f<10&&f>-10});if(!b.length){b=this.element.children(".ui-menu-item:last")}this.activate(d,b)}else{this.activate(d,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))}},previousPage:function(d){if(this.hasScroll()){if(!this.active||this.first()){this.activate(d,this.element.children(".ui-menu-item:last"));return}var e=this.active.offset().top,c=this.element.height(),b=this.element.children(".ui-menu-item").filter(function(){var f=a(this).offset().top-e+c-a(this).height();return f<10&&f>-10});if(!b.length){b=this.element.children(".ui-menu-item:first")}this.activate(d,b)}else{this.activate(d,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))}},hasScroll:function(){return this.element.height()<this.element[a.fn.prop?"prop":"attr"]("scrollHeight")},select:function(b){this._trigger("selected",b,{item:this.active})}})}(jQuery));(function(f,b){var k,e,a,h,i="ui-button ui-widget ui-state-default ui-corner-all",c="ui-state-hover ui-state-active ",g="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",j=function(){var l=f(this).find(":ui-button");setTimeout(function(){l.button("refresh")},1)},d=function(m){var l=m.name,n=m.form,o=f([]);if(l){if(n){o=f(n).find("[name='"+l+"']")}else{o=f("[name='"+l+"']",m.ownerDocument).filter(function(){return !this.form})}}return o};f.widget("ui.button",{options:{disabled:null,text:true,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",j);if(typeof this.options.disabled!=="boolean"){this.options.disabled=!!this.element.propAttr("disabled")}else{this.element.propAttr("disabled",this.options.disabled)}this._determineButtonType();this.hasTitle=!!this.buttonElement.attr("title");var l=this,n=this.options,o=this.type==="checkbox"||this.type==="radio",p="ui-state-hover"+(!o?" ui-state-active":""),m="ui-state-focus";if(n.label===null){n.label=this.buttonElement.html()}this.buttonElement.addClass(i).attr("role","button").bind("mouseenter.button",function(){if(n.disabled){return}f(this).addClass("ui-state-hover");if(this===k){f(this).addClass("ui-state-active")}}).bind("mouseleave.button",function(){if(n.disabled){return}f(this).removeClass(p)}).bind("click.button",function(q){if(n.disabled){q.preventDefault();q.stopImmediatePropagation()}});this.element.bind("focus.button",function(){l.buttonElement.addClass(m)}).bind("blur.button",function(){l.buttonElement.removeClass(m)});if(o){this.element.bind("change.button",function(){if(h){return}l.refresh()});this.buttonElement.bind("mousedown.button",function(q){if(n.disabled){return}h=false;e=q.pageX;a=q.pageY}).bind("mouseup.button",function(q){if(n.disabled){return}if(e!==q.pageX||a!==q.pageY){h=true}})}if(this.type==="checkbox"){this.buttonElement.bind("click.button",function(){if(n.disabled||h){return false}f(this).toggleClass("ui-state-active");l.buttonElement.attr("aria-pressed",l.element[0].checked)})}else{if(this.type==="radio"){this.buttonElement.bind("click.button",function(){if(n.disabled||h){return false}f(this).addClass("ui-state-active");l.buttonElement.attr("aria-pressed","true");var q=l.element[0];d(q).not(q).map(function(){return f(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")})}else{this.buttonElement.bind("mousedown.button",function(){if(n.disabled){return false}f(this).addClass("ui-state-active");k=this;f(document).one("mouseup",function(){k=null})}).bind("mouseup.button",function(){if(n.disabled){return false}f(this).removeClass("ui-state-active")}).bind("keydown.button",function(q){if(n.disabled){return false}if(q.keyCode==f.ui.keyCode.SPACE||q.keyCode==f.ui.keyCode.ENTER){f(this).addClass("ui-state-active")}}).bind("keyup.button",function(){f(this).removeClass("ui-state-active")});if(this.buttonElement.is("a")){this.buttonElement.keyup(function(q){if(q.keyCode===f.ui.keyCode.SPACE){f(this).click()}})}}}this._setOption("disabled",n.disabled);this._resetButton()},_determineButtonType:function(){if(this.element.is(":checkbox")){this.type="checkbox"}else{if(this.element.is(":radio")){this.type="radio"}else{if(this.element.is("input")){this.type="input"}else{this.type="button"}}}if(this.type==="checkbox"||this.type==="radio"){var l=this.element.parents().filter(":last"),n="label[for='"+this.element.attr("id")+"']";this.buttonElement=l.find(n);if(!this.buttonElement.length){l=l.length?l.siblings():this.element.siblings();this.buttonElement=l.filter(n);if(!this.buttonElement.length){this.buttonElement=l.find(n)}}this.element.addClass("ui-helper-hidden-accessible");var m=this.element.is(":checked");if(m){this.buttonElement.addClass("ui-state-active")}this.buttonElement.attr("aria-pressed",m)}else{this.buttonElement=this.element}},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass(i+" "+c+" "+g).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html());if(!this.hasTitle){this.buttonElement.removeAttr("title")}f.Widget.prototype.destroy.call(this)},_setOption:function(l,m){f.Widget.prototype._setOption.apply(this,arguments);if(l==="disabled"){if(m){this.element.propAttr("disabled",true)}else{this.element.propAttr("disabled",false)}return}this._resetButton()},refresh:function(){var l=this.element.is(":disabled");if(l!==this.options.disabled){this._setOption("disabled",l)}if(this.type==="radio"){d(this.element[0]).each(function(){if(f(this).is(":checked")){f(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true")}else{f(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}})}else{if(this.type==="checkbox"){if(this.element.is(":checked")){this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true")}else{this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false")}}}},_resetButton:function(){if(this.type==="input"){if(this.options.label){this.element.val(this.options.label)}return}var p=this.buttonElement.removeClass(g),n=f("<span></span>",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(p.empty()).text(),m=this.options.icons,l=m.primary&&m.secondary,o=[];if(m.primary||m.secondary){if(this.options.text){o.push("ui-button-text-icon"+(l?"s":(m.primary?"-primary":"-secondary")))}if(m.primary){p.prepend("<span class='ui-button-icon-primary ui-icon "+m.primary+"'></span>")}if(m.secondary){p.append("<span class='ui-button-icon-secondary ui-icon "+m.secondary+"'></span>")}if(!this.options.text){o.push(l?"ui-button-icons-only":"ui-button-icon-only");if(!this.hasTitle){p.attr("title",n)}}}else{o.push("ui-button-text-only")}p.addClass(o.join(" "))}});f.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(l,m){if(l==="disabled"){this.buttons.button("option",l,m)}f.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var l=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return f(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(l?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(l?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return f(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");f.Widget.prototype.destroy.call(this)}})}(jQuery));(function($,undefined){$.extend($.ui,{datepicker:{version:"1.8.24"}});var PROP_NAME="datepicker";var dpuuid=new Date().getTime();var instActive;function Datepicker(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false,disabled:false};$.extend(this._defaults,this.regional[""]);this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){if(this.debug){console.log.apply("",arguments)}},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase();var inline=(nodeName=="div"||nodeName=="span");if(!target.id){this.uuid+=1;target.id="dp"+this.uuid}var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{});if(nodeName=="input"){this._connectDatepicker(target,inst)}else{if(inline){this._inlineDatepicker(target,inst)}}},_newInst:function(target,inline){var id=target[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:id,input:target,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:inline,dpDiv:(!inline?this.dpDiv:bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}},_connectDatepicker:function(target,inst){var input=$(target);inst.append=$([]);inst.trigger=$([]);if(input.hasClass(this.markerClassName)){return}this._attachments(input,inst);input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});this._autoSize(inst);$.data(target,PROP_NAME,inst);if(inst.settings.disabled){this._disableDatepicker(target)}},_attachments:function(input,inst){var appendText=this._get(inst,"appendText");var isRTL=this._get(inst,"isRTL");if(inst.append){inst.append.remove()}if(appendText){inst.append=$('<span class="'+this._appendClass+'">'+appendText+"</span>");input[isRTL?"before":"after"](inst.append)}input.unbind("focus",this._showDatepicker);if(inst.trigger){inst.trigger.remove()}var showOn=this._get(inst,"showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){var buttonText=this._get(inst,"buttonText");var buttonImage=this._get(inst,"buttonImage");inst.trigger=$(this._get(inst,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText}):$('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage==""?buttonText:$("<img/>").attr({src:buttonImage,alt:buttonText,title:buttonText})));input[isRTL?"before":"after"](inst.trigger);inst.trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==input[0]){$.datepicker._hideDatepicker()}else{if($.datepicker._datepickerShowing&&$.datepicker._lastInput!=input[0]){$.datepicker._hideDatepicker();$.datepicker._showDatepicker(input[0])}else{$.datepicker._showDatepicker(input[0])}}return false})}},_autoSize:function(inst){if(this._get(inst,"autoSize")&&!inst.inline){var date=new Date(2009,12-1,20);var dateFormat=this._get(inst,"dateFormat");if(dateFormat.match(/[DM]/)){var findMax=function(names){var max=0;var maxI=0;for(var i=0;i<names.length;i++){if(names[i].length>max){max=names[i].length;maxI=i}}return maxI};date.setMonth(findMax(this._get(inst,(dateFormat.match(/MM/)?"monthNames":"monthNamesShort"))));date.setDate(findMax(this._get(inst,(dateFormat.match(/DD/)?"dayNames":"dayNamesShort")))+20-date.getDay())}inst.input.attr("size",this._formatDate(inst,date).length)}},_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return}divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst);this._setDate(inst,this._getDefaultDate(inst),true);this._updateDatepicker(inst);this._updateAlternate(inst);if(inst.settings.disabled){this._disableDatepicker(target)}inst.dpDiv.css("display","block")},_dialogDatepicker:function(input,date,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){this.uuid+=1;var id="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+id+'" style="position: absolute; top: -100px; width: 0px;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],PROP_NAME,inst)}extendRemove(inst.settings,settings||{});date=(date&&date.constructor==Date?this._formatDate(inst,date):date);this._dialogInput.val(date);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=document.documentElement.clientWidth;var browserHeight=document.documentElement.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",(this._pos[0]+20)+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv)}$.data(this._dialogInput[0],PROP_NAME,inst);return this},_destroyDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();$.removeData(target,PROP_NAME);if(nodeName=="input"){inst.append.remove();inst.trigger.remove();$target.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}},_enableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=false;inst.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled");inline.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=true;inst.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled");inline.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[this._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_getInst:function(target){try{return $.data(target,PROP_NAME)}catch(err){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(target,name,value){var inst=this._getInst(target);if(arguments.length==2&&typeof name=="string"){return(name=="defaults"?$.extend({},$.datepicker._defaults):(inst?(name=="all"?$.extend({},inst.settings):this._get(inst,name)):null))}var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}if(inst){if(this._curInst==inst){this._hideDatepicker()}var date=this._getDateDatepicker(target,true);var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");extendRemove(inst.settings,settings);if(minDate!==null&&settings.dateFormat!==undefined&&settings.minDate===undefined){inst.settings.minDate=this._formatDate(inst,minDate)}if(maxDate!==null&&settings.dateFormat!==undefined&&settings.maxDate===undefined){inst.settings.maxDate=this._formatDate(inst,maxDate)}this._attachments($(target),inst);this._autoSize(inst);this._setDate(inst,date);this._updateAlternate(inst);this._updateDatepicker(inst)}},_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value)},_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date){var inst=this._getInst(target);if(inst){this._setDate(inst,date);this._updateDatepicker(inst);this._updateAlternate(inst)}},_getDateDatepicker:function(target,noDefault){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst,noDefault)}return(inst?this._getDate(inst):null)},_doKeyDown:function(event){var inst=$.datepicker._getInst(event.target);var handled=true;var isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker();handled=false;break;case 13:var sel=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",inst.dpDiv);if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0])}var onSelect=$.datepicker._get(inst,"onSelect");if(onSelect){var dateStr=$.datepicker._formatDate(inst);onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{$.datepicker._hideDatepicker()}return false;break;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M");break;case 34:$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M");break;case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target)}handled=event.ctrlKey||event.metaKey;break;case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target)}handled=event.ctrlKey||event.metaKey;break;case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?+1:-1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M")}break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D")}handled=event.ctrlKey||event.metaKey;break;case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?-1:+1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M")}break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,+7,"D")}handled=event.ctrlKey||event.metaKey;break;default:handled=false}}else{if(event.keyCode==36&&event.ctrlKey){$.datepicker._showDatepicker(this)}else{handled=false}}if(handled){event.preventDefault();event.stopPropagation()}},_doKeyPress:function(event){var inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){var chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));var chr=String.fromCharCode(event.charCode==undefined?event.keyCode:event.charCode);return event.ctrlKey||event.metaKey||(chr<" "||!chars||chars.indexOf(chr)>-1)}},_doKeyUp:function(event){var inst=$.datepicker._getInst(event.target);if(inst.input.val()!=inst.lastVal){try{var date=$.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),(inst.input?inst.input.val():null),$.datepicker._getFormatConfig(inst));if(date){$.datepicker._setDateFromField(inst);$.datepicker._updateAlternate(inst);$.datepicker._updateDatepicker(inst)}}catch(err){$.datepicker.log(err)}}return true},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return}var inst=$.datepicker._getInst(input);if($.datepicker._curInst&&$.datepicker._curInst!=inst){$.datepicker._curInst.dpDiv.stop(true,true);if(inst&&$.datepicker._datepickerShowing){$.datepicker._hideDatepicker($.datepicker._curInst.input[0])}}var beforeShow=$.datepicker._get(inst,"beforeShow");var beforeShowSettings=beforeShow?beforeShow.apply(input,[input,inst]):{};if(beforeShowSettings===false){return}extendRemove(inst.settings,beforeShowSettings);inst.lastVal=null;$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed";return !isFixed});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}var offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;inst.dpDiv.empty();inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute")),display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){var showAnim=$.datepicker._get(inst,"showAnim");var duration=$.datepicker._get(inst,"duration");var postProcess=function(){var cover=inst.dpDiv.find("iframe.ui-datepicker-cover");if(!!cover.length){var borders=$.datepicker._getBorders(inst.dpDiv);cover.css({left:-borders[0],top:-borders[1],width:inst.dpDiv.outerWidth(),height:inst.dpDiv.outerHeight()})}};inst.dpDiv.zIndex($(input).zIndex()+1);$.datepicker._datepickerShowing=true;if($.effects&&$.effects[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[showAnim||"show"]((showAnim?duration:null),postProcess)}if(!showAnim||!duration){postProcess()}if(inst.input.is(":visible")&&!inst.input.is(":disabled")){inst.input.focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){var self=this;self.maxRows=4;var borders=$.datepicker._getBorders(inst.dpDiv);instActive=inst;inst.dpDiv.empty().append(this._generateHTML(inst));this._attachHandlers(inst);var cover=inst.dpDiv.find("iframe.ui-datepicker-cover");if(!!cover.length){cover.css({left:-borders[0],top:-borders[1],width:inst.dpDiv.outerWidth(),height:inst.dpDiv.outerHeight()})}inst.dpDiv.find("."+this._dayOverClass+" a").mouseover();var numMonths=this._getNumberOfMonths(inst);var cols=numMonths[1];var width=17;inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",(width*cols)+"em")}inst.dpDiv[(numMonths[0]!=1||numMonths[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst==$.datepicker._curInst&&$.datepicker._datepickerShowing&&inst.input&&inst.input.is(":visible")&&!inst.input.is(":disabled")&&inst.input[0]!=document.activeElement){inst.input.focus()}if(inst.yearshtml){var origyearshtml=inst.yearshtml;setTimeout(function(){if(origyearshtml===inst.yearshtml&&inst.yearshtml){inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml)}origyearshtml=inst.yearshtml=null},0)}},_getBorders:function(elem){var convert=function(value){return{thin:1,medium:2,thick:3}[value]||value};return[parseFloat(convert(elem.css("border-left-width"))),parseFloat(convert(elem.css("border-top-width")))]},_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth();var dpHeight=inst.dpDiv.outerHeight();var inputWidth=inst.input?inst.input.outerWidth():0;var inputHeight=inst.input?inst.input.outerHeight():0;var viewWidth=document.documentElement.clientWidth+(isFixed?0:$(document).scrollLeft());var viewHeight=document.documentElement.clientHeight+(isFixed?0:$(document).scrollTop());offset.left-=(this._get(inst,"isRTL")?(dpWidth-inputWidth):0);offset.left-=(isFixed&&offset.left==inst.input.offset().left)?$(document).scrollLeft():0;offset.top-=(isFixed&&offset.top==(inst.input.offset().top+inputHeight))?$(document).scrollTop():0;offset.left-=Math.min(offset.left,(offset.left+dpWidth>viewWidth&&viewWidth>dpWidth)?Math.abs(offset.left+dpWidth-viewWidth):0);offset.top-=Math.min(offset.top,(offset.top+dpHeight>viewHeight&&viewHeight>dpHeight)?Math.abs(dpHeight+inputHeight):0);return offset},_findPos:function(obj){var inst=this._getInst(obj);var isRTL=this._get(inst,"isRTL");while(obj&&(obj.type=="hidden"||obj.nodeType!=1||$.expr.filters.hidden(obj))){obj=obj[isRTL?"previousSibling":"nextSibling"]}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input){var inst=this._curInst;if(!inst||(input&&inst!=$.data(input,PROP_NAME))){return}if(this._datepickerShowing){var showAnim=this._get(inst,"showAnim");var duration=this._get(inst,"duration");var postProcess=function(){$.datepicker._tidyDialog(inst)};if($.effects&&$.effects[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide"))]((showAnim?duration:null),postProcess)}if(!showAnim){postProcess()}this._datepickerShowing=false;var onClose=this._get(inst,"onClose");if(onClose){onClose.apply((inst.input?inst.input[0]:null),[(inst.input?inst.input.val():""),inst])}this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(event){if(!$.datepicker._curInst){return}var $target=$(event.target),inst=$.datepicker._getInst($target[0]);if((($target[0].id!=$.datepicker._mainDivId&&$target.parents("#"+$.datepicker._mainDivId).length==0&&!$target.hasClass($.datepicker.markerClassName)&&!$target.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)))||($target.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=inst)){$.datepicker._hideDatepicker()}},_adjustDate:function(id,offset,period){var target=$(id);var inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return}this._adjustInstDate(inst,offset+(period=="M"?this._get(inst,"showCurrentAtPos"):0),period);this._updateDatepicker(inst)},_gotoToday:function(id){var target=$(id);var inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear}else{var date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear()}this._notifyChange(inst);this._adjustDate(target)},_selectMonthYear:function(id,select,period){var target=$(id);var inst=this._getInst(target[0]);inst["selected"+(period=="M"?"Month":"Year")]=inst["draw"+(period=="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target)},_selectDay:function(id,month,year,td){var target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return}var inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=$("a",td).html();inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear))},_clearDate:function(id){var target=$(id);var inst=this._getInst(target[0]);this._selectDate(target,"")},_selectDate:function(id,dateStr){var target=$(id);var inst=this._getInst(target[0]);dateStr=(dateStr!=null?dateStr:this._formatDate(inst));if(inst.input){inst.input.val(dateStr)}this._updateAlternate(inst);var onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{if(inst.input){inst.input.trigger("change")}}if(inst.inline){this._updateDatepicker(inst)}else{this._hideDatepicker();this._lastInput=inst.input[0];if(typeof(inst.input[0])!="object"){inst.input.focus()}this._lastInput=null}},_updateAlternate:function(inst){var altField=this._get(inst,"altField");if(altField){var altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");var date=this._getDate(inst);var dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(altField).each(function(){$(this).val(dateStr)})}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getTime());checkDate.setDate(checkDate.getDate()+4-(checkDate.getDay()||7));var time=checkDate.getTime();checkDate.setMonth(0);checkDate.setDate(1);return Math.floor(Math.round((time-checkDate)/86400000)/7)+1},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var doy=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){var isDoubled=lookAhead(match);var size=(match=="@"?14:(match=="!"?20:(match=="y"&&isDoubled?4:(match=="o"?3:2))));var digits=new RegExp("^\\d{1,"+size+"}");var num=value.substring(iValue).match(digits);if(!num){throw"Missing number at position "+iValue}iValue+=num[0].length;return parseInt(num[0],10)};var getName=function(match,shortNames,longNames){var names=$.map(lookAhead(match)?longNames:shortNames,function(v,k){return[[k,v]]}).sort(function(a,b){return -(a[1].length-b[1].length)});var index=-1;$.each(names,function(i,pair){var name=pair[1];if(value.substr(iValue,name.length).toLowerCase()==name.toLowerCase()){index=pair[0];iValue+=name.length;return false}});if(index!=-1){return index+1}else{throw"Unknown name at position "+iValue}};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"o":doy=getNumber("o");break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"@":var date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"!":var date=new Date((getNumber("!")-this._ticksTo1970)/10000);year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(iValue<value.length){throw"Extra/unparsed characters found in date: "+value.substring(iValue)}if(year==-1){year=new Date().getFullYear()}else{if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}}if(doy>-1){month=1;day=doy;do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}var date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(((1970-1)*365+Math.floor(1970/4)-Math.floor(1970/100)+Math.floor(1970/400))*24*60*60*10000000),formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num}}return num};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate(),2);break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"o":output+=formatNumber("o",Math.round((new Date(date.getFullYear(),date.getMonth(),date.getDate()).getTime()-new Date(date.getFullYear(),0,0).getTime())/86400000),3);break;case"m":output+=formatNumber("m",date.getMonth()+1,2);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"@":output+=date.getTime();break;case"!":output+=date.getTime()*10000+this._ticksTo1970;break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":case"m":case"y":case"@":chars+="0123456789";break;case"D":case"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars},_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name]},_setDateFromField:function(inst,noDefault){if(inst.input.val()==inst.lastVal){return}var dateFormat=this._get(inst,"dateFormat");var dates=inst.lastVal=inst.input?inst.input.val():null;var date,defaultDate;date=defaultDate=this._getDefaultDate(inst);var settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate}catch(event){this.log(event);dates=(noDefault?"":dates)}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=(dates?date.getDate():0);inst.currentMonth=(dates?date.getMonth():0);inst.currentYear=(dates?date.getFullYear():0);this._adjustInstDate(inst)},_getDefaultDate:function(inst){return this._restrictMinMax(inst,this._determineDate(inst,this._get(inst,"defaultDate"),new Date()))},_determineDate:function(inst,date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset){try{return $.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),offset,$.datepicker._getFormatConfig(inst))}catch(e){}var date=(offset.toLowerCase().match(/^c/)?$.datepicker._getDate(inst):null)||new Date();var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();var pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;var matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case"d":case"D":day+=parseInt(matches[1],10);break;case"w":case"W":day+=parseInt(matches[1],10)*7;break;case"m":case"M":month+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break;case"y":case"Y":year+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break}matches=pattern.exec(offset)}return new Date(year,month,day)};var newDate=(date==null||date===""?defaultDate:(typeof date=="string"?offsetString(date):(typeof date=="number"?(isNaN(date)?defaultDate:offsetNumeric(date)):new Date(date.getTime()))));newDate=(newDate&&newDate.toString()=="Invalid Date"?defaultDate:newDate);if(newDate){newDate.setHours(0);newDate.setMinutes(0);newDate.setSeconds(0);newDate.setMilliseconds(0)}return this._daylightSavingAdjust(newDate)},_daylightSavingAdjust:function(date){if(!date){return null}date.setHours(date.getHours()>12?date.getHours()+2:0);return date},_setDate:function(inst,date,noChange){var clear=!date;var origMonth=inst.selectedMonth;var origYear=inst.selectedYear;var newDate=this._restrictMinMax(inst,this._determineDate(inst,date,new Date()));inst.selectedDay=inst.currentDay=newDate.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=newDate.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=newDate.getFullYear();if((origMonth!=inst.selectedMonth||origYear!=inst.selectedYear)&&!noChange){this._notifyChange(inst)}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst))}},_getDate:function(inst){var startDate=(!inst.currentYear||(inst.input&&inst.input.val()=="")?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return startDate},_attachHandlers:function(inst){var stepMonths=this._get(inst,"stepMonths");var id="#"+inst.id.replace(/\\\\/g,"\\");inst.dpDiv.find("[data-handler]").map(function(){var handler={prev:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(id,-stepMonths,"M")},next:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(id,+stepMonths,"M")},hide:function(){window["DP_jQuery_"+dpuuid].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+dpuuid].datepicker._gotoToday(id)},selectDay:function(){window["DP_jQuery_"+dpuuid].datepicker._selectDay(id,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this);return false},selectMonth:function(){window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(id,this,"M");return false},selectYear:function(){window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(id,this,"Y");return false}};$(this).bind(this.getAttribute("data-event"),handler[this.getAttribute("data-handler")])})},_generateHTML:function(inst){var today=new Date();today=this._daylightSavingAdjust(new Date(today.getFullYear(),today.getMonth(),today.getDate()));var isRTL=this._get(inst,"isRTL");var showButtonPanel=this._get(inst,"showButtonPanel");var hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext");var navigationAsDateFormat=this._get(inst,"navigationAsDateFormat");var numMonths=this._getNumberOfMonths(inst);var showCurrentAtPos=this._get(inst,"showCurrentAtPos");var stepMonths=this._get(inst,"stepMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var currentDate=this._daylightSavingAdjust((!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");var drawMonth=inst.drawMonth-showCurrentAtPos;var drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--}if(maxDate){var maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-(numMonths[0]*numMonths[1])+1,maxDate.getDate()));maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;var prevText=this._get(inst,"prevText");prevText=(!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst)));var prev=(this._canAdjustMonth(inst,-1,drawYear,drawMonth)?'<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>"));var nextText=this._get(inst,"nextText");nextText=(!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst)));var next=(this._canAdjustMonth(inst,+1,drawYear,drawMonth)?'<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>"));var currentText=this._get(inst,"currentText");var gotoDate=(this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today);currentText=(!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst)));var controls=(!inst.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">'+this._get(inst,"closeText")+"</button>":"");var buttonPanel=(showButtonPanel)?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(isRTL?controls:"")+(this._isInRange(inst,gotoDate)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click">'+currentText+"</button>":"")+(isRTL?"":controls)+"</div>":"";var firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=(isNaN(firstDay)?0:firstDay);var showWeek=this._get(inst,"showWeek");var dayNames=this._get(inst,"dayNames");var dayNamesShort=this._get(inst,"dayNamesShort");var dayNamesMin=this._get(inst,"dayNamesMin");var monthNames=this._get(inst,"monthNames");var monthNamesShort=this._get(inst,"monthNamesShort");var beforeShowDay=this._get(inst,"beforeShowDay");var showOtherMonths=this._get(inst,"showOtherMonths");var selectOtherMonths=this._get(inst,"selectOtherMonths");var calculateWeek=this._get(inst,"calculateWeek")||this.iso8601Week;var defaultDate=this._getDefaultDate(inst);var html="";for(var row=0;row<numMonths[0];row++){var group="";this.maxRows=4;for(var col=0;col<numMonths[1];col++){var selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));var cornerClass=" ui-corner-all";var calender="";if(isMultiMonth){calender+='<div class="ui-datepicker-group';if(numMonths[1]>1){switch(col){case 0:calender+=" ui-datepicker-group-first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+=" ui-datepicker-group-last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+=" ui-datepicker-group-middle";cornerClass="";break}}calender+='">'}calender+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+cornerClass+'">'+(/all|left/.test(cornerClass)&&row==0?(isRTL?next:prev):"")+(/all|right/.test(cornerClass)&&row==0?(isRTL?prev:next):"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,row>0||col>0,monthNames,monthNamesShort)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var thead=(showWeek?'<th class="ui-datepicker-week-col">'+this._get(inst,"weekHeader")+"</th>":"");for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;thead+="<th"+((dow+firstDay+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+dayNames[day]+'">'+dayNamesMin[day]+"</span></th>"}calender+=thead+"</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==inst.selectedYear&&drawMonth==inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var curRows=Math.ceil((leadDays+daysInMonth)/7);var numRows=(isMultiMonth?this.maxRows>curRows?this.maxRows:curRows:curRows);this.maxRows=numRows;var printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(var dRow=0;dRow<numRows;dRow++){calender+="<tr>";var tbody=(!showWeek?"":'<td class="ui-datepicker-week-col">'+this._get(inst,"calculateWeek")(printDate)+"</td>");for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((inst.input?inst.input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=(otherMonth&&!selectOtherMonths)||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);tbody+='<td class="'+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(otherMonth?" ui-datepicker-other-month":"")+((printDate.getTime()==selectedDate.getTime()&&drawMonth==inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()==printDate.getTime()&&defaultDate.getTime()==selectedDate.getTime())?" "+this._dayOverClass:"")+(unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()==currentDate.getTime()?" "+this._currentClass:"")+(printDate.getTime()==today.getTime()?" ui-datepicker-today":""))+'"'+((!otherMonth||showOtherMonths)&&daySettings[2]?' title="'+daySettings[2]+'"':"")+(unselectable?"":' data-handler="selectDay" data-event="click" data-month="'+printDate.getMonth()+'" data-year="'+printDate.getFullYear()+'"')+">"+(otherMonth&&!showOtherMonths?"&#xa0;":(unselectable?'<span class="ui-state-default">'+printDate.getDate()+"</span>":'<a class="ui-state-default'+(printDate.getTime()==today.getTime()?" ui-state-highlight":"")+(printDate.getTime()==currentDate.getTime()?" ui-state-active":"")+(otherMonth?" ui-priority-secondary":"")+'" href="#">'+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate)}calender+=tbody+"</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}calender+="</tbody></table>"+(isMultiMonth?"</div>"+((numMonths[0]>0&&col==numMonths[1]-1)?'<div class="ui-datepicker-row-break"></div>':""):"");group+=calender}html+=group}html+=buttonPanel+($.browser.msie&&parseInt($.browser.version,10)<7&&!inst.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");inst._keyEvent=false;return html},_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,secondary,monthNames,monthNamesShort){var changeMonth=this._get(inst,"changeMonth");var changeYear=this._get(inst,"changeYear");var showMonthAfterYear=this._get(inst,"showMonthAfterYear");var html='<div class="ui-datepicker-title">';var monthHtml="";if(secondary||!changeMonth){monthHtml+='<span class="ui-datepicker-month">'+monthNames[drawMonth]+"</span>"}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);monthHtml+='<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNamesShort[month]+"</option>"}}monthHtml+="</select>"}if(!showMonthAfterYear){html+=monthHtml+(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")}if(!inst.yearshtml){inst.yearshtml="";if(secondary||!changeYear){html+='<span class="ui-datepicker-year">'+drawYear+"</span>"}else{var years=this._get(inst,"yearRange").split(":");var thisYear=new Date().getFullYear();var determineYear=function(value){var year=(value.match(/c[+-].*/)?drawYear+parseInt(value.substring(1),10):(value.match(/[+-].*/)?thisYear+parseInt(value,10):parseInt(value,10)));return(isNaN(year)?thisYear:year)};var year=determineYear(years[0]);var endYear=Math.max(year,determineYear(years[1]||""));year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);inst.yearshtml+='<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';for(;year<=endYear;year++){inst.yearshtml+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}inst.yearshtml+="</select>";html+=inst.yearshtml;inst.yearshtml=null}}html+=this._get(inst,"yearSuffix");if(showMonthAfterYear){html+=(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")+monthHtml}html+="</div>";return html},_adjustInstDate:function(inst,offset,period){var year=inst.drawYear+(period=="Y"?offset:0);var month=inst.drawMonth+(period=="M"?offset:0);var day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=this._restrictMinMax(inst,this._daylightSavingAdjust(new Date(year,month,day)));inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period=="M"||period=="Y"){this._notifyChange(inst)}},_restrictMinMax:function(inst,date){var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");var newDate=(minDate&&date<minDate?minDate:date);newDate=(maxDate&&newDate>maxDate?maxDate:newDate);return newDate},_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply((inst.input?inst.input[0]:null),[inst.selectedYear,inst.selectedMonth+1,inst])}},_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(inst,minMax){return this._determineDate(inst,this._get(inst,minMax+"Date"),null)},_getDaysInMonth:function(year,month){return 32-this._daylightSavingAdjust(new Date(year,month,32)).getDate()},_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay()},_canAdjustMonth:function(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst);var date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[0]*numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(inst,date)},_isInRange:function(inst,date){var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");return((!minDate||date.getTime()>=minDate.getTime())&&(!maxDate||date.getTime()<=maxDate.getTime()))},_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")}},_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear}var date=(day?(typeof day=="object"?day:this._daylightSavingAdjust(new Date(year,month,day))):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst))}});function bindHover(dpDiv){var selector="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return dpDiv.bind("mouseout",function(event){var elem=$(event.target).closest(selector);if(!elem.length){return}elem.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(event){var elem=$(event.target).closest(selector);if($.datepicker._isDisabledDatepicker(instActive.inline?dpDiv.parent()[0]:instActive.input[0])||!elem.length){return}elem.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");elem.addClass("ui-state-hover");if(elem.hasClass("ui-datepicker-prev")){elem.addClass("ui-datepicker-prev-hover")}if(elem.hasClass("ui-datepicker-next")){elem.addClass("ui-datepicker-next-hover")}})}function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null||props[name]==undefined){target[name]=props[name]}}return target}function isArray(a){return(a&&(($.browser.safari&&typeof a=="object"&&a.length)||(a.constructor&&a.constructor.toString().match(/\Array\(\)/))))}$.fn.datepicker=function(options){if(!this.length){return this}if(!$.datepicker.initialized){$(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv);$.datepicker.initialized=true}var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options=="string"&&(options=="isDisabled"||options=="getDate"||options=="widget")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}if(options=="option"&&arguments.length==2&&typeof arguments[1]=="string"){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}return this.each(function(){typeof options=="string"?$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs)):$.datepicker._attachDatepicker(this,options)})};$.datepicker=new Datepicker();$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.8.24";window["DP_jQuery_"+dpuuid]=$})(jQuery);(function(d,e){var b="ui-dialog ui-widget ui-widget-content ui-corner-all ",a={buttons:true,height:true,maxHeight:true,maxWidth:true,minHeight:true,minWidth:true,width:true},c={maxHeight:true,maxWidth:true,minHeight:true,minWidth:true};d.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:{my:"center",at:"center",collision:"fit",using:function(g){var f=d(this).css(g).offset().top;if(f<0){d(this).css("top",g.top-f)}}},resizable:true,show:null,stack:true,title:"",width:300,zIndex:1000},_create:function(){this.originalTitle=this.element.attr("title");if(typeof this.originalTitle!=="string"){this.originalTitle=""}this.options.title=this.options.title||this.originalTitle;var n=this,o=n.options,l=o.title||"&#160;",g=d.ui.dialog.getTitleId(n.element),m=(n.uiDialog=d("<div></div>")).appendTo(document.body).hide().addClass(b+o.dialogClass).css({zIndex:o.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(p){if(o.closeOnEscape&&!p.isDefaultPrevented()&&p.keyCode&&p.keyCode===d.ui.keyCode.ESCAPE){n.close(p);p.preventDefault()}}).attr({role:"dialog","aria-labelledby":g}).mousedown(function(p){n.moveToTop(false,p)}),i=n.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(m),h=(n.uiDialogTitlebar=d("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(m),k=d('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){k.addClass("ui-state-hover")},function(){k.removeClass("ui-state-hover")}).focus(function(){k.addClass("ui-state-focus")}).blur(function(){k.removeClass("ui-state-focus")}).click(function(p){n.close(p);return false}).appendTo(h),j=(n.uiDialogTitlebarCloseText=d("<span></span>")).addClass("ui-icon ui-icon-closethick").text(o.closeText).appendTo(k),f=d("<span></span>").addClass("ui-dialog-title").attr("id",g).html(l).prependTo(h);if(d.isFunction(o.beforeclose)&&!d.isFunction(o.beforeClose)){o.beforeClose=o.beforeclose}h.find("*").add(h).disableSelection();if(o.draggable&&d.fn.draggable){n._makeDraggable()}if(o.resizable&&d.fn.resizable){n._makeResizable()}n._createButtons(o.buttons);n._isOpen=false;if(d.fn.bgiframe){m.bgiframe()}},_init:function(){if(this.options.autoOpen){this.open()}},destroy:function(){var f=this;if(f.overlay){f.overlay.destroy()}f.uiDialog.hide();f.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");f.uiDialog.remove();if(f.originalTitle){f.element.attr("title",f.originalTitle)}return f},widget:function(){return this.uiDialog},close:function(i){var f=this,h,g;if(false===f._trigger("beforeClose",i)){return}if(f.overlay){f.overlay.destroy()}f.uiDialog.unbind("keypress.ui-dialog");f._isOpen=false;if(f.options.hide){f.uiDialog.hide(f.options.hide,function(){f._trigger("close",i)})}else{f.uiDialog.hide();f._trigger("close",i)}d.ui.dialog.overlay.resize();if(f.options.modal){h=0;d(".ui-dialog").each(function(){if(this!==f.uiDialog[0]){g=d(this).css("z-index");if(!isNaN(g)){h=Math.max(h,g)}}});d.ui.dialog.maxZ=h}return f},isOpen:function(){return this._isOpen},moveToTop:function(j,i){var f=this,h=f.options,g;if((h.modal&&!j)||(!h.stack&&!h.modal)){return f._trigger("focus",i)}if(h.zIndex>d.ui.dialog.maxZ){d.ui.dialog.maxZ=h.zIndex}if(f.overlay){d.ui.dialog.maxZ+=1;f.overlay.$el.css("z-index",d.ui.dialog.overlay.maxZ=d.ui.dialog.maxZ)}g={scrollTop:f.element.scrollTop(),scrollLeft:f.element.scrollLeft()};d.ui.dialog.maxZ+=1;f.uiDialog.css("z-index",d.ui.dialog.maxZ);f.element.attr(g);f._trigger("focus",i);return f},open:function(){if(this._isOpen){return}var g=this,h=g.options,f=g.uiDialog;g.overlay=h.modal?new d.ui.dialog.overlay(g):null;g._size();g._position(h.position);f.show(h.show);g.moveToTop(true);if(h.modal){f.bind("keydown.ui-dialog",function(k){if(k.keyCode!==d.ui.keyCode.TAB){return}var j=d(":tabbable",this),l=j.filter(":first"),i=j.filter(":last");if(k.target===i[0]&&!k.shiftKey){l.focus(1);return false}else{if(k.target===l[0]&&k.shiftKey){i.focus(1);return false}}})}d(g.element.find(":tabbable").get().concat(f.find(".ui-dialog-buttonpane :tabbable").get().concat(f.get()))).eq(0).focus();g._isOpen=true;g._trigger("open");return g},_createButtons:function(i){var h=this,f=false,g=d("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),j=d("<div></div>").addClass("ui-dialog-buttonset").appendTo(g);h.uiDialog.find(".ui-dialog-buttonpane").remove();if(typeof i==="object"&&i!==null){d.each(i,function(){return !(f=true)})}if(f){d.each(i,function(k,m){m=d.isFunction(m)?{click:m,text:k}:m;var l=d('<button type="button"></button>').click(function(){m.click.apply(h.element[0],arguments)}).appendTo(j);d.each(m,function(n,o){if(n==="click"){return}if(n in l){l[n](o)}else{l.attr(n,o)}});if(d.fn.button){l.button()}});g.appendTo(h.uiDialog)}},_makeDraggable:function(){var f=this,i=f.options,j=d(document),h;function g(k){return{position:k.position,offset:k.offset}}f.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(k,l){h=i.height==="auto"?"auto":d(this).height();d(this).height(d(this).height()).addClass("ui-dialog-dragging");f._trigger("dragStart",k,g(l))},drag:function(k,l){f._trigger("drag",k,g(l))},stop:function(k,l){i.position=[l.position.left-j.scrollLeft(),l.position.top-j.scrollTop()];d(this).removeClass("ui-dialog-dragging").height(h);f._trigger("dragStop",k,g(l));d.ui.dialog.overlay.resize()}})},_makeResizable:function(k){k=(k===e?this.options.resizable:k);var g=this,j=g.options,f=g.uiDialog.css("position"),i=(typeof k==="string"?k:"n,e,s,w,se,sw,ne,nw");function h(l){return{originalPosition:l.originalPosition,originalSize:l.originalSize,position:l.position,size:l.size}}g.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:g.element,maxWidth:j.maxWidth,maxHeight:j.maxHeight,minWidth:j.minWidth,minHeight:g._minHeight(),handles:i,start:function(l,m){d(this).addClass("ui-dialog-resizing");g._trigger("resizeStart",l,h(m))},resize:function(l,m){g._trigger("resize",l,h(m))},stop:function(l,m){d(this).removeClass("ui-dialog-resizing");j.height=d(this).height();j.width=d(this).width();g._trigger("resizeStop",l,h(m));d.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var f=this.options;if(f.height==="auto"){return f.minHeight}else{return Math.min(f.minHeight,f.height)}},_position:function(g){var h=[],i=[0,0],f;if(g){if(typeof g==="string"||(typeof g==="object"&&"0" in g)){h=g.split?g.split(" "):[g[0],g[1]];if(h.length===1){h[1]=h[0]}d.each(["left","top"],function(k,j){if(+h[k]===h[k]){i[k]=h[k];h[k]=j}});g={my:h.join(" "),at:h.join(" "),offset:i.join(" ")}}g=d.extend({},d.ui.dialog.prototype.options.position,g)}else{g=d.ui.dialog.prototype.options.position}f=this.uiDialog.is(":visible");if(!f){this.uiDialog.show()}this.uiDialog.css({top:0,left:0}).position(d.extend({of:window},g));if(!f){this.uiDialog.hide()}},_setOptions:function(i){var g=this,f={},h=false;d.each(i,function(j,k){g._setOption(j,k);if(j in a){h=true}if(j in c){f[j]=k}});if(h){this._size()}if(this.uiDialog.is(":data(resizable)")){this.uiDialog.resizable("option",f)}},_setOption:function(i,j){var g=this,f=g.uiDialog;switch(i){case"beforeclose":i="beforeClose";break;case"buttons":g._createButtons(j);break;case"closeText":g.uiDialogTitlebarCloseText.text(""+j);break;case"dialogClass":f.removeClass(g.options.dialogClass).addClass(b+j);break;case"disabled":if(j){f.addClass("ui-dialog-disabled")}else{f.removeClass("ui-dialog-disabled")}break;case"draggable":var h=f.is(":data(draggable)");if(h&&!j){f.draggable("destroy")}if(!h&&j){g._makeDraggable()}break;case"position":g._position(j);break;case"resizable":var k=f.is(":data(resizable)");if(k&&!j){f.resizable("destroy")}if(k&&typeof j==="string"){f.resizable("option","handles",j)}if(!k&&j!==false){g._makeResizable(j)}break;case"title":d(".ui-dialog-title",g.uiDialogTitlebar).html(""+(j||"&#160;"));break}d.Widget.prototype._setOption.apply(g,arguments)},_size:function(){var j=this.options,g,i,f=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0});if(j.minWidth>j.width){j.width=j.minWidth}g=this.uiDialog.css({height:"auto",width:j.width}).height();i=Math.max(0,j.minHeight-g);if(j.height==="auto"){if(d.support.minHeight){this.element.css({minHeight:i,height:"auto"})}else{this.uiDialog.show();var h=this.element.css("height","auto").height();if(!f){this.uiDialog.hide()}this.element.height(Math.max(h,i))}}else{this.element.height(Math.max(j.height-g,0))}if(this.uiDialog.is(":data(resizable)")){this.uiDialog.resizable("option","minHeight",this._minHeight())}}});d.extend(d.ui.dialog,{version:"1.8.24",uuid:0,maxZ:0,getTitleId:function(f){var g=f.attr("id");if(!g){this.uuid+=1;g=this.uuid}return"ui-dialog-title-"+g},overlay:function(f){this.$el=d.ui.dialog.overlay.create(f)}});d.extend(d.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:d.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(f){return f+".dialog-overlay"}).join(" "),create:function(g){if(this.instances.length===0){setTimeout(function(){if(d.ui.dialog.overlay.instances.length){d(document).bind(d.ui.dialog.overlay.events,function(h){if(d(h.target).zIndex()<d.ui.dialog.overlay.maxZ){return false}})}},1);d(document).bind("keydown.dialog-overlay",function(h){if(g.options.closeOnEscape&&!h.isDefaultPrevented()&&h.keyCode&&h.keyCode===d.ui.keyCode.ESCAPE){g.close(h);h.preventDefault()}});d(window).bind("resize.dialog-overlay",d.ui.dialog.overlay.resize)}var f=(this.oldInstances.pop()||d("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});if(d.fn.bgiframe){f.bgiframe()}this.instances.push(f);return f},destroy:function(f){var g=d.inArray(f,this.instances);if(g!=-1){this.oldInstances.push(this.instances.splice(g,1)[0])}if(this.instances.length===0){d([document,window]).unbind(".dialog-overlay")}f.remove();var h=0;d.each(this.instances,function(){h=Math.max(h,this.css("z-index"))});this.maxZ=h},height:function(){var g,f;if(d.browser.msie&&d.browser.version<7){g=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);f=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(g<f){return d(window).height()+"px"}else{return g+"px"}}else{return d(document).height()+"px"}},width:function(){var f,g;if(d.browser.msie){f=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);g=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(f<g){return d(window).width()+"px"}else{return f+"px"}}else{return d(document).width()+"px"}},resize:function(){var f=d([]);d.each(d.ui.dialog.overlay.instances,function(){f=f.add(this)});f.css({width:0,height:0}).css({width:d.ui.dialog.overlay.width(),height:d.ui.dialog.overlay.height()})}});d.extend(d.ui.dialog.overlay.prototype,{destroy:function(){d.ui.dialog.overlay.destroy(this.$el)}})}(jQuery));(function(g,h){g.ui=g.ui||{};var d=/left|center|right/,e=/top|center|bottom/,a="center",f={},b=g.fn.position,c=g.fn.offset;g.fn.position=function(j){if(!j||!j.of){return b.apply(this,arguments)}j=g.extend({},j);var n=g(j.of),m=n[0],p=(j.collision||"flip").split(" "),o=j.offset?j.offset.split(" "):[0,0],l,i,k;if(m.nodeType===9){l=n.width();i=n.height();k={top:0,left:0}}else{if(m.setTimeout){l=n.width();i=n.height();k={top:n.scrollTop(),left:n.scrollLeft()}}else{if(m.preventDefault){j.at="left top";l=i=0;k={top:j.of.pageY,left:j.of.pageX}}else{l=n.outerWidth();i=n.outerHeight();k=n.offset()}}}g.each(["my","at"],function(){var q=(j[this]||"").split(" ");if(q.length===1){q=d.test(q[0])?q.concat([a]):e.test(q[0])?[a].concat(q):[a,a]}q[0]=d.test(q[0])?q[0]:a;q[1]=e.test(q[1])?q[1]:a;j[this]=q});if(p.length===1){p[1]=p[0]}o[0]=parseInt(o[0],10)||0;if(o.length===1){o[1]=o[0]}o[1]=parseInt(o[1],10)||0;if(j.at[0]==="right"){k.left+=l}else{if(j.at[0]===a){k.left+=l/2}}if(j.at[1]==="bottom"){k.top+=i}else{if(j.at[1]===a){k.top+=i/2}}k.left+=o[0];k.top+=o[1];return this.each(function(){var t=g(this),v=t.outerWidth(),s=t.outerHeight(),u=parseInt(g.curCSS(this,"marginLeft",true))||0,r=parseInt(g.curCSS(this,"marginTop",true))||0,x=v+u+(parseInt(g.curCSS(this,"marginRight",true))||0),y=s+r+(parseInt(g.curCSS(this,"marginBottom",true))||0),w=g.extend({},k),q;if(j.my[0]==="right"){w.left-=v}else{if(j.my[0]===a){w.left-=v/2}}if(j.my[1]==="bottom"){w.top-=s}else{if(j.my[1]===a){w.top-=s/2}}if(!f.fractions){w.left=Math.round(w.left);w.top=Math.round(w.top)}q={left:w.left-u,top:w.top-r};g.each(["left","top"],function(A,z){if(g.ui.position[p[A]]){g.ui.position[p[A]][z](w,{targetWidth:l,targetHeight:i,elemWidth:v,elemHeight:s,collisionPosition:q,collisionWidth:x,collisionHeight:y,offset:o,my:j.my,at:j.at})}});if(g.fn.bgiframe){t.bgiframe()}t.offset(g.extend(w,{using:j.using}))})};g.ui.position={fit:{left:function(i,j){var l=g(window),k=j.collisionPosition.left+j.collisionWidth-l.width()-l.scrollLeft();i.left=k>0?i.left-k:Math.max(i.left-j.collisionPosition.left,i.left)},top:function(i,j){var l=g(window),k=j.collisionPosition.top+j.collisionHeight-l.height()-l.scrollTop();i.top=k>0?i.top-k:Math.max(i.top-j.collisionPosition.top,i.top)}},flip:{left:function(j,l){if(l.at[0]===a){return}var n=g(window),m=l.collisionPosition.left+l.collisionWidth-n.width()-n.scrollLeft(),i=l.my[0]==="left"?-l.elemWidth:l.my[0]==="right"?l.elemWidth:0,k=l.at[0]==="left"?l.targetWidth:-l.targetWidth,o=-2*l.offset[0];j.left+=l.collisionPosition.left<0?i+k+o:m>0?i+k+o:0},top:function(j,l){if(l.at[1]===a){return}var n=g(window),m=l.collisionPosition.top+l.collisionHeight-n.height()-n.scrollTop(),i=l.my[1]==="top"?-l.elemHeight:l.my[1]==="bottom"?l.elemHeight:0,k=l.at[1]==="top"?l.targetHeight:-l.targetHeight,o=-2*l.offset[1];j.top+=l.collisionPosition.top<0?i+k+o:m>0?i+k+o:0}}};if(!g.offset.setOffset){g.offset.setOffset=function(m,j){if(/static/.test(g.curCSS(m,"position"))){m.style.position="relative"}var l=g(m),o=l.offset(),i=parseInt(g.curCSS(m,"top",true),10)||0,n=parseInt(g.curCSS(m,"left",true),10)||0,k={top:(j.top-o.top)+i,left:(j.left-o.left)+n};if("using" in j){j.using.call(m,k)}else{l.css(k)}};g.fn.offset=function(i){var j=this[0];if(!j||!j.ownerDocument){return null}if(i){if(g.isFunction(i)){return this.each(function(k){g(this).offset(i.call(this,k,g(this).offset()))})}return this.each(function(){g.offset.setOffset(this,i)})}return c.call(this)}}if(!g.curCSS){g.curCSS=g.css}(function(){var j=document.getElementsByTagName("body")[0],q=document.createElement("div"),n,p,k,o,m;n=document.createElement(j?"div":"body");k={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};if(j){g.extend(k,{position:"absolute",left:"-1000px",top:"-1000px"})}for(var l in k){n.style[l]=k[l]}n.appendChild(q);p=j||document.documentElement;p.insertBefore(n,p.firstChild);q.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;";o=g(q).offset(function(i,r){return r}).offset();n.innerHTML="";p.removeChild(n);m=o.top+o.left+(j?2000:0);f.fractions=m>21&&m<22})()}(jQuery));(function(a,b){a.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()});this.valueDiv=a("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this.oldValue=this._value();this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow");this.valueDiv.remove();a.Widget.prototype.destroy.apply(this,arguments)},value:function(c){if(c===b){return this._value()}this._setOption("value",c);return this},_setOption:function(c,d){if(c==="value"){this.options.value=d;this._refreshValue();if(this._value()===this.options.max){this._trigger("complete")}}a.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var c=this.options.value;if(typeof c!=="number"){c=0}return Math.min(this.options.max,Math.max(this.min,c))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var d=this.value();var c=this._percentage();if(this.oldValue!==d){this.oldValue=d;this._trigger("change")}this.valueDiv.toggle(d>this.min).toggleClass("ui-corner-right",d===this.options.max).width(c.toFixed(0)+"%");this.element.attr("aria-valuenow",d)}});a.extend(a.ui.progressbar,{version:"1.8.24"})})(jQuery);(function(b,c){var a=5;b.widget("ui.slider",b.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var e=this,k=this.options,j=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),h="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",d=(k.values&&k.values.length)||1,g=[];this._keySliding=false;this._mouseSliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all"+(k.disabled?" ui-slider-disabled ui-disabled":""));this.range=b([]);if(k.range){if(k.range===true){if(!k.values){k.values=[this._valueMin(),this._valueMin()]}if(k.values.length&&k.values.length!==2){k.values=[k.values[0],k.values[0]]}}this.range=b("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+((k.range==="min"||k.range==="max")?" ui-slider-range-"+k.range:""))}for(var f=j.length;f<d;f+=1){g.push(h)}this.handles=j.add(b(g.join("")).appendTo(e.element));this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(i){i.preventDefault()}).hover(function(){if(!k.disabled){b(this).addClass("ui-state-hover")}},function(){b(this).removeClass("ui-state-hover")}).focus(function(){if(!k.disabled){b(".ui-slider .ui-state-focus").removeClass("ui-state-focus");b(this).addClass("ui-state-focus")}else{b(this).blur()}}).blur(function(){b(this).removeClass("ui-state-focus")});this.handles.each(function(l){b(this).data("index.ui-slider-handle",l)});this.handles.keydown(function(o){var l=b(this).data("index.ui-slider-handle"),p,m,i,n;if(e.options.disabled){return}switch(o.keyCode){case b.ui.keyCode.HOME:case b.ui.keyCode.END:case b.ui.keyCode.PAGE_UP:case b.ui.keyCode.PAGE_DOWN:case b.ui.keyCode.UP:case b.ui.keyCode.RIGHT:case b.ui.keyCode.DOWN:case b.ui.keyCode.LEFT:o.preventDefault();if(!e._keySliding){e._keySliding=true;b(this).addClass("ui-state-active");p=e._start(o,l);if(p===false){return}}break}n=e.options.step;if(e.options.values&&e.options.values.length){m=i=e.values(l)}else{m=i=e.value()}switch(o.keyCode){case b.ui.keyCode.HOME:i=e._valueMin();break;case b.ui.keyCode.END:i=e._valueMax();break;case b.ui.keyCode.PAGE_UP:i=e._trimAlignValue(m+((e._valueMax()-e._valueMin())/a));break;case b.ui.keyCode.PAGE_DOWN:i=e._trimAlignValue(m-((e._valueMax()-e._valueMin())/a));break;case b.ui.keyCode.UP:case b.ui.keyCode.RIGHT:if(m===e._valueMax()){return}i=e._trimAlignValue(m+n);break;case b.ui.keyCode.DOWN:case b.ui.keyCode.LEFT:if(m===e._valueMin()){return}i=e._trimAlignValue(m-n);break}e._slide(o,l,i)}).keyup(function(l){var i=b(this).data("index.ui-slider-handle");if(e._keySliding){e._keySliding=false;e._stop(l,i);e._change(l,i);b(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy();return this},_mouseCapture:function(f){var g=this.options,j,l,e,h,n,k,m,i,d;if(g.disabled){return false}this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();j={x:f.pageX,y:f.pageY};l=this._normValueFromMouse(j);e=this._valueMax()-this._valueMin()+1;n=this;this.handles.each(function(o){var p=Math.abs(l-n.values(o));if(e>p){e=p;h=b(this);k=o}});if(g.range===true&&this.values(1)===g.min){k+=1;h=b(this.handles[k])}m=this._start(f,k);if(m===false){return false}this._mouseSliding=true;n._handleIndex=k;h.addClass("ui-state-active").focus();i=h.offset();d=!b(f.target).parents().andSelf().is(".ui-slider-handle");this._clickOffset=d?{left:0,top:0}:{left:f.pageX-i.left-(h.width()/2),top:f.pageY-i.top-(h.height()/2)-(parseInt(h.css("borderTopWidth"),10)||0)-(parseInt(h.css("borderBottomWidth"),10)||0)+(parseInt(h.css("marginTop"),10)||0)};if(!this.handles.hasClass("ui-state-hover")){this._slide(f,k,l)}this._animateOff=true;return true},_mouseStart:function(d){return true},_mouseDrag:function(f){var d={x:f.pageX,y:f.pageY},e=this._normValueFromMouse(d);this._slide(f,this._handleIndex,e);return false},_mouseStop:function(d){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(d,this._handleIndex);this._change(d,this._handleIndex);this._handleIndex=null;this._clickOffset=null;this._animateOff=false;return false},_detectOrientation:function(){this.orientation=(this.options.orientation==="vertical")?"vertical":"horizontal"},_normValueFromMouse:function(e){var d,h,g,f,i;if(this.orientation==="horizontal"){d=this.elementSize.width;h=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{d=this.elementSize.height;h=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}g=(h/d);if(g>1){g=1}if(g<0){g=0}if(this.orientation==="vertical"){g=1-g}f=this._valueMax()-this._valueMin();i=this._valueMin()+g*f;return this._trimAlignValue(i)},_start:function(f,e){var d={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){d.value=this.values(e);d.values=this.values()}return this._trigger("start",f,d)},_slide:function(h,g,f){var d,e,i;if(this.options.values&&this.options.values.length){d=this.values(g?0:1);if((this.options.values.length===2&&this.options.range===true)&&((g===0&&f>d)||(g===1&&f<d))){f=d}if(f!==this.values(g)){e=this.values();e[g]=f;i=this._trigger("slide",h,{handle:this.handles[g],value:f,values:e});d=this.values(g?0:1);if(i!==false){this.values(g,f,true)}}}else{if(f!==this.value()){i=this._trigger("slide",h,{handle:this.handles[g],value:f});if(i!==false){this.value(f)}}}},_stop:function(f,e){var d={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){d.value=this.values(e);d.values=this.values()}this._trigger("stop",f,d)},_change:function(f,e){if(!this._keySliding&&!this._mouseSliding){var d={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){d.value=this.values(e);d.values=this.values()}this._trigger("change",f,d)}},value:function(d){if(arguments.length){this.options.value=this._trimAlignValue(d);this._refreshValue();this._change(null,0);return}return this._value()},values:function(e,h){var g,d,f;if(arguments.length>1){this.options.values[e]=this._trimAlignValue(h);this._refreshValue();this._change(null,e);return}if(arguments.length){if(b.isArray(arguments[0])){g=this.options.values;d=arguments[0];for(f=0;f<g.length;f+=1){g[f]=this._trimAlignValue(d[f]);this._change(null,f)}this._refreshValue()}else{if(this.options.values&&this.options.values.length){return this._values(e)}else{return this.value()}}}else{return this._values()}},_setOption:function(e,f){var d,g=0;if(b.isArray(this.options.values)){g=this.options.values.length}b.Widget.prototype._setOption.apply(this,arguments);switch(e){case"disabled":if(f){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.propAttr("disabled",true);this.element.addClass("ui-disabled")}else{this.handles.propAttr("disabled",false);this.element.removeClass("ui-disabled")}break;case"orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case"value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case"values":this._animateOff=true;this._refreshValue();for(d=0;d<g;d+=1){this._change(null,d)}this._animateOff=false;break}},_value:function(){var d=this.options.value;d=this._trimAlignValue(d);return d},_values:function(d){var g,f,e;if(arguments.length){g=this.options.values[d];g=this._trimAlignValue(g);return g}else{f=this.options.values.slice();for(e=0;e<f.length;e+=1){f[e]=this._trimAlignValue(f[e])}return f}},_trimAlignValue:function(g){if(g<=this._valueMin()){return this._valueMin()}if(g>=this._valueMax()){return this._valueMax()}var d=(this.options.step>0)?this.options.step:1,f=(g-this._valueMin())%d,e=g-f;if(Math.abs(f)*2>=d){e+=(f>0)?d:(-d)}return parseFloat(e.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var g=this.options.range,f=this.options,m=this,e=(!this._animateOff)?f.animate:false,h,d={},i,k,j,l;if(this.options.values&&this.options.values.length){this.handles.each(function(o,n){h=(m.values(o)-m._valueMin())/(m._valueMax()-m._valueMin())*100;d[m.orientation==="horizontal"?"left":"bottom"]=h+"%";b(this).stop(1,1)[e?"animate":"css"](d,f.animate);if(m.options.range===true){if(m.orientation==="horizontal"){if(o===0){m.range.stop(1,1)[e?"animate":"css"]({left:h+"%"},f.animate)}if(o===1){m.range[e?"animate":"css"]({width:(h-i)+"%"},{queue:false,duration:f.animate})}}else{if(o===0){m.range.stop(1,1)[e?"animate":"css"]({bottom:(h)+"%"},f.animate)}if(o===1){m.range[e?"animate":"css"]({height:(h-i)+"%"},{queue:false,duration:f.animate})}}}i=h})}else{k=this.value();j=this._valueMin();l=this._valueMax();h=(l!==j)?(k-j)/(l-j)*100:0;d[m.orientation==="horizontal"?"left":"bottom"]=h+"%";this.handle.stop(1,1)[e?"animate":"css"](d,f.animate);if(g==="min"&&this.orientation==="horizontal"){this.range.stop(1,1)[e?"animate":"css"]({width:h+"%"},f.animate)}if(g==="max"&&this.orientation==="horizontal"){this.range[e?"animate":"css"]({width:(100-h)+"%"},{queue:false,duration:f.animate})}if(g==="min"&&this.orientation==="vertical"){this.range.stop(1,1)[e?"animate":"css"]({height:h+"%"},f.animate)}if(g==="max"&&this.orientation==="vertical"){this.range[e?"animate":"css"]({height:(100-h)+"%"},{queue:false,duration:f.animate})}}}});b.extend(b.ui.slider,{version:"1.8.24"})}(jQuery));(function(d,f){var c=0,b=0;function e(){return ++c}function a(){return ++b}d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(true)},_setOption:function(g,h){if(g=="selected"){if(this.options.collapsible&&h==this.options.selected){return}this.select(h)}else{this.options[g]=h;this._tabify()}},_tabId:function(g){return g.title&&g.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(g){return g.replace(/:/g,"\\:")},_cookie:function(){var g=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+a());return d.cookie.apply(null,[g].concat(d.makeArray(arguments)))},_ui:function(h,g){return{tab:h,panel:g,index:this.anchors.index(h)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var g=d(this);g.html(g.data("label.tabs")).removeData("label.tabs")})},_tabify:function(t){var u=this,j=this.options,h=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=d(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);this.anchors.each(function(w,o){var v=d(o).attr("href");var x=v.split("#")[0],y;if(x&&(x===location.toString().split("#")[0]||(y=d("base")[0])&&x===y.href)){v=o.hash;o.href=v}if(h.test(v)){u.panels=u.panels.add(u.element.find(u._sanitizeSelector(v)))}else{if(v&&v!=="#"){d.data(o,"href.tabs",v);d.data(o,"load.tabs",v.replace(/#.*$/,""));var A=u._tabId(o);o.href="#"+A;var z=u.element.find("#"+A);if(!z.length){z=d(j.panelTemplate).attr("id",A).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(u.panels[w-1]||u.list);z.data("destroy.tabs",true)}u.panels=u.panels.add(z)}else{j.disabled.push(w)}}});if(t){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(j.selected===f){if(location.hash){this.anchors.each(function(v,o){if(o.hash==location.hash){j.selected=v;return false}})}if(typeof j.selected!=="number"&&j.cookie){j.selected=parseInt(u._cookie(),10)}if(typeof j.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length){j.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}j.selected=j.selected||(this.lis.length?0:-1)}else{if(j.selected===null){j.selected=-1}}j.selected=((j.selected>=0&&this.anchors[j.selected])||j.selected<0)?j.selected:0;j.disabled=d.unique(j.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(v,o){return u.lis.index(v)}))).sort();if(d.inArray(j.selected,j.disabled)!=-1){j.disabled.splice(d.inArray(j.selected,j.disabled),1)}this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(j.selected>=0&&this.anchors.length){u.element.find(u._sanitizeSelector(u.anchors[j.selected].hash)).removeClass("ui-tabs-hide");this.lis.eq(j.selected).addClass("ui-tabs-selected ui-state-active");u.element.queue("tabs",function(){u._trigger("show",null,u._ui(u.anchors[j.selected],u.element.find(u._sanitizeSelector(u.anchors[j.selected].hash))[0]))});this.load(j.selected)}d(window).bind("unload",function(){u.lis.add(u.anchors).unbind(".tabs");u.lis=u.anchors=u.panels=null})}else{j.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}this.element[j.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");if(j.cookie){this._cookie(j.selected,j.cookie)}for(var m=0,s;(s=this.lis[m]);m++){d(s)[d.inArray(m,j.disabled)!=-1&&!d(s).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled")}if(j.cache===false){this.anchors.removeData("cache.tabs")}this.lis.add(this.anchors).unbind(".tabs");if(j.event!=="mouseover"){var l=function(o,i){if(i.is(":not(.ui-state-disabled)")){i.addClass("ui-state-"+o)}};var p=function(o,i){i.removeClass("ui-state-"+o)};this.lis.bind("mouseover.tabs",function(){l("hover",d(this))});this.lis.bind("mouseout.tabs",function(){p("hover",d(this))});this.anchors.bind("focus.tabs",function(){l("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){p("focus",d(this).closest("li"))})}var g,n;if(j.fx){if(d.isArray(j.fx)){g=j.fx[0];n=j.fx[1]}else{g=n=j.fx}}function k(i,o){i.css("display","");if(!d.support.opacity&&o.opacity){i[0].style.removeAttribute("filter")}}var q=n?function(i,o){d(i).closest("li").addClass("ui-tabs-selected ui-state-active");o.hide().removeClass("ui-tabs-hide").animate(n,n.duration||"normal",function(){k(o,n);u._trigger("show",null,u._ui(i,o[0]))})}:function(i,o){d(i).closest("li").addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");u._trigger("show",null,u._ui(i,o[0]))};var r=g?function(o,i){i.animate(g,g.duration||"normal",function(){u.lis.removeClass("ui-tabs-selected ui-state-active");i.addClass("ui-tabs-hide");k(i,g);u.element.dequeue("tabs")})}:function(o,i,v){u.lis.removeClass("ui-tabs-selected ui-state-active");i.addClass("ui-tabs-hide");u.element.dequeue("tabs")};this.anchors.bind(j.event+".tabs",function(){var o=this,w=d(o).closest("li"),i=u.panels.filter(":not(.ui-tabs-hide)"),v=u.element.find(u._sanitizeSelector(o.hash));if((w.hasClass("ui-tabs-selected")&&!j.collapsible)||w.hasClass("ui-state-disabled")||w.hasClass("ui-state-processing")||u.panels.filter(":animated").length||u._trigger("select",null,u._ui(this,v[0]))===false){this.blur();return false}j.selected=u.anchors.index(this);u.abort();if(j.collapsible){if(w.hasClass("ui-tabs-selected")){j.selected=-1;if(j.cookie){u._cookie(j.selected,j.cookie)}u.element.queue("tabs",function(){r(o,i)}).dequeue("tabs");this.blur();return false}else{if(!i.length){if(j.cookie){u._cookie(j.selected,j.cookie)}u.element.queue("tabs",function(){q(o,v)});u.load(u.anchors.index(this));this.blur();return false}}}if(j.cookie){u._cookie(j.selected,j.cookie)}if(v.length){if(i.length){u.element.queue("tabs",function(){r(o,i)})}u.element.queue("tabs",function(){q(o,v)});u.load(u.anchors.index(this))}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(d.browser.msie){this.blur()}});this.anchors.bind("click.tabs",function(){return false})},_getIndex:function(g){if(typeof g=="string"){g=this.anchors.index(this.anchors.filter("[href$='"+g+"']"))}return g},destroy:function(){var g=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var h=d.data(this,"href.tabs");if(h){this.href=h}var i=d(this).unbind(".tabs");d.each(["href","load","cache"],function(j,k){i.removeData(k+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){if(d.data(this,"destroy.tabs")){d(this).remove()}else{d(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}});if(g.cookie){this._cookie(null,g.cookie)}return this},add:function(j,i,h){if(h===f){h=this.anchors.length}var g=this,l=this.options,n=d(l.tabTemplate.replace(/#\{href\}/g,j).replace(/#\{label\}/g,i)),m=!j.indexOf("#")?j.replace("#",""):this._tabId(d("a",n)[0]);n.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var k=g.element.find("#"+m);if(!k.length){k=d(l.panelTemplate).attr("id",m).data("destroy.tabs",true)}k.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(h>=this.lis.length){n.appendTo(this.list);k.appendTo(this.list[0].parentNode)}else{n.insertBefore(this.lis[h]);k.insertBefore(this.panels[h])}l.disabled=d.map(l.disabled,function(p,o){return p>=h?++p:p});this._tabify();if(this.anchors.length==1){l.selected=0;n.addClass("ui-tabs-selected ui-state-active");k.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){g._trigger("show",null,g._ui(g.anchors[0],g.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[h],this.panels[h]));return this},remove:function(g){g=this._getIndex(g);var i=this.options,j=this.lis.eq(g).remove(),h=this.panels.eq(g).remove();if(j.hasClass("ui-tabs-selected")&&this.anchors.length>1){this.select(g+(g+1<this.anchors.length?1:-1))}i.disabled=d.map(d.grep(i.disabled,function(l,k){return l!=g}),function(l,k){return l>=g?--l:l});this._tabify();this._trigger("remove",null,this._ui(j.find("a")[0],h[0]));return this},enable:function(g){g=this._getIndex(g);var h=this.options;if(d.inArray(g,h.disabled)==-1){return}this.lis.eq(g).removeClass("ui-state-disabled");h.disabled=d.grep(h.disabled,function(k,j){return k!=g});this._trigger("enable",null,this._ui(this.anchors[g],this.panels[g]));return this},disable:function(h){h=this._getIndex(h);var g=this,i=this.options;if(h!=i.selected){this.lis.eq(h).addClass("ui-state-disabled");i.disabled.push(h);i.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[h],this.panels[h]))}return this},select:function(g){g=this._getIndex(g);if(g==-1){if(this.options.collapsible&&this.options.selected!=-1){g=this.options.selected}else{return this}}this.anchors.eq(g).trigger(this.options.event+".tabs");return this},load:function(j){j=this._getIndex(j);var h=this,l=this.options,g=this.anchors.eq(j)[0],i=d.data(g,"load.tabs");this.abort();if(!i||this.element.queue("tabs").length!==0&&d.data(g,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(j).addClass("ui-state-processing");if(l.spinner){var k=d("span",g);k.data("label.tabs",k.html()).html(l.spinner)}this.xhr=d.ajax(d.extend({},l.ajaxOptions,{url:i,success:function(n,m){h.element.find(h._sanitizeSelector(g.hash)).html(n);h._cleanup();if(l.cache){d.data(g,"cache.tabs",true)}h._trigger("load",null,h._ui(h.anchors[j],h.panels[j]));try{l.ajaxOptions.success(n,m)}catch(o){}},error:function(o,m,n){h._cleanup();h._trigger("load",null,h._ui(h.anchors[j],h.panels[j]));try{l.ajaxOptions.error(o,m,j,g)}catch(n){}}}));h.element.dequeue("tabs");return this},abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(h,g){this.anchors.eq(h).removeData("cache.tabs").data("load.tabs",g);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.24"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(i,k){var g=this,l=this.options;var h=g._rotate||(g._rotate=function(m){clearTimeout(g.rotation);g.rotation=setTimeout(function(){var n=l.selected;g.select(++n<g.anchors.length?n:0)},i);if(m){m.stopPropagation()}});var j=g._unrotate||(g._unrotate=!k?function(m){if(m.clientX){g.rotate(null)}}:function(m){h()});if(i){this.element.bind("tabsshow",h);this.anchors.bind(l.event+".tabs",j);h()}else{clearTimeout(g.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(l.event+".tabs",j);delete this._rotate;delete this._unrotate}return this}})})(jQuery); /* * jQuery UI Draggable 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Draggables * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this},_mouseCapture:function(c){var d=this.options;if(this.helper||d.disabled||a(c.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(c);if(!this.handle){return false}if(d.iframeFix){a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})}return true},_mouseStart:function(c){var d=this.options;this.helper=this._createHelper(c);this.helper.addClass("ui-draggable-dragging");this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:c.pageX-this.offset.left,top:c.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(c);this.originalPageX=c.pageX;this.originalPageY=c.pageY;(d.cursorAt&&this._adjustOffsetFromHelper(d.cursorAt));if(d.containment){this._setContainment()}if(this._trigger("start",c)===false){this._clear();return false}this._cacheHelperProportions();if(a.ui.ddmanager&&!d.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,c)}this._mouseDrag(c,true);if(a.ui.ddmanager){a.ui.ddmanager.dragStart(this,c)}return true},_mouseDrag:function(c,e){this.position=this._generatePosition(c);this.positionAbs=this._convertPositionTo("absolute");if(!e){var d=this._uiHash();if(this._trigger("drag",c,d)===false){this._mouseUp({});return false}this.position=d.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,c)}return false},_mouseStop:function(e){var g=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){g=a.ui.ddmanager.drop(this,e)}if(this.dropped){g=this.dropped;this.dropped=false}var d=this.element[0],f=false;while(d&&(d=d.parentNode)){if(d==document){f=true}}if(!f&&this.options.helper==="original"){return false}if((this.options.revert=="invalid"&&!g)||(this.options.revert=="valid"&&g)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,g))){var c=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(c._trigger("stop",e)!==false){c._clear()}})}else{if(this._trigger("stop",e)!==false){this._clear()}}return false},_mouseUp:function(c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});if(a.ui.ddmanager){a.ui.ddmanager.dragStop(this,c)}return a.ui.mouse.prototype._mouseUp.call(this,c)},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp({})}else{this._clear()}return this},_getHandle:function(c){var d=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==c.target){d=true}});return d},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d])):(e.helper=="clone"?this.element.clone().removeAttr("id"):this.element);if(!c.parents("body").length){c.appendTo((e.appendTo=="parent"?this.element[0].parentNode:e.appendTo))}if(c[0]!=this.element[0]&&!(/(fixed|absolute)/).test(c.css("position"))){c.css("position","absolute")}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.element.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0),right:(parseInt(this.element.css("marginRight"),10)||0),bottom:(parseInt(this.element.css("marginBottom"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var g=this.options;if(g.containment=="parent"){g.containment=this.helper[0].parentNode}if(g.containment=="document"||g.containment=="window"){this.containment=[g.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,g.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(g.containment=="document"?0:a(window).scrollLeft())+a(g.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(g.containment=="document"?0:a(window).scrollTop())+(a(g.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(g.containment)&&g.containment.constructor!=Array){var h=a(g.containment);var e=h[0];if(!e){return}var f=h.offset();var d=(a(e).css("overflow")!="hidden");this.containment=[(parseInt(a(e).css("borderLeftWidth"),10)||0)+(parseInt(a(e).css("paddingLeft"),10)||0),(parseInt(a(e).css("borderTopWidth"),10)||0)+(parseInt(a(e).css("paddingTop"),10)||0),(d?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(a(e).css("borderLeftWidth"),10)||0)-(parseInt(a(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(d?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(a(e).css("borderTopWidth"),10)||0)-(parseInt(a(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=h}else{if(g.containment.constructor==Array){this.containment=g.containment}}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(d){var e=this.options,l=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(l[0].tagName);var h=d.pageX;var g=d.pageY;if(this.originalPosition){var c;if(this.containment){if(this.relative_container){var k=this.relative_container.offset();c=[this.containment[0]+k.left,this.containment[1]+k.top,this.containment[2]+k.left,this.containment[3]+k.top]}else{c=this.containment}if(d.pageX-this.offset.click.left<c[0]){h=c[0]+this.offset.click.left}if(d.pageY-this.offset.click.top<c[1]){g=c[1]+this.offset.click.top}if(d.pageX-this.offset.click.left>c[2]){h=c[2]+this.offset.click.left}if(d.pageY-this.offset.click.top>c[3]){g=c[3]+this.offset.click.top}}if(e.grid){var j=e.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/e.grid[1])*e.grid[1]:this.originalPageY;g=c?(!(j-this.offset.click.top<c[1]||j-this.offset.click.top>c[3])?j:(!(j-this.offset.click.top<c[1])?j-e.grid[1]:j+e.grid[1])):j;var f=e.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/e.grid[0])*e.grid[0]:this.originalPageX;h=c?(!(f-this.offset.click.left<c[0]||f-this.offset.click.left>c[2])?f:(!(f-this.offset.click.left<c[0])?f-e.grid[0]:f+e.grid[0])):f}}return{top:(g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:l.scrollTop())))),left:(h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:l.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(c,d,e){e=e||this._uiHash();a.ui.plugin.call(this,c,[d,e]);if(c=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.Widget.prototype._trigger.call(this,c,d,e)},plugins:{},_uiHash:function(c){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});a.extend(a.ui.draggable,{version:"1.8.24"});a.ui.plugin.add("draggable","connectToSortable",{start:function(d,f){var e=a(this).data("draggable"),g=e.options,c=a.extend({},f,{item:e.element});e.sortables=[];a(g.connectToSortable).each(function(){var h=a.data(this,"sortable");if(h&&!h.options.disabled){e.sortables.push({instance:h,shouldRevert:h.options.revert});h.refreshPositions();h._trigger("activate",d,c)}})},stop:function(d,f){var e=a(this).data("draggable"),c=a.extend({},f,{item:e.element});a.each(e.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;e.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(d);this.instance.options.helper=this.instance.options._helper;if(e.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",d,c)}})},drag:function(d,g){var f=a(this).data("draggable"),c=this;var e=function(j){var p=this.offset.click.top,n=this.offset.click.left;var h=this.positionAbs.top,l=this.positionAbs.left;var k=j.height,m=j.width;var q=j.top,i=j.left;return a.ui.isOver(h+p,l+n,q,i,k,m)};a.each(f.sortables,function(h){this.instance.positionAbs=f.positionAbs;this.instance.helperProportions=f.helperProportions;this.instance.offset.click=f.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(c).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return g.helper[0]};d.target=this.instance.currentItem[0];this.instance._mouseCapture(d,true);this.instance._mouseStart(d,true,true);this.instance.offset.click.top=f.offset.click.top;this.instance.offset.click.left=f.offset.click.left;this.instance.offset.parent.left-=f.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=f.offset.parent.top-this.instance.offset.parent.top;f._trigger("toSortable",d);f.dropped=this.instance.element;f.currentItem=f.element;this.instance.fromOutside=f}if(this.instance.currentItem){this.instance._mouseDrag(d)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",d,this.instance._uiHash(this.instance));this.instance._mouseStop(d,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}f._trigger("fromSortable",d);f.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(d,e){var c=a("body"),f=a(this).data("draggable").options;if(c.css("cursor")){f._cursor=c.css("cursor")}c.css("cursor",f.cursor)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._cursor){a("body").css("cursor",e._cursor)}}});a.ui.plugin.add("draggable","opacity",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("opacity")){f._opacity=c.css("opacity")}c.css("opacity",f.opacity)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._opacity){a(d.helper).css("opacity",e._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(d,e){var c=a(this).data("draggable");if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){c.overflowOffset=c.scrollParent.offset()}},drag:function(e,f){var d=a(this).data("draggable"),g=d.options,c=false;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!g.axis||g.axis!="x"){if((d.overflowOffset.top+d.scrollParent[0].offsetHeight)-e.pageY<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop+g.scrollSpeed}else{if(e.pageY-d.overflowOffset.top<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop-g.scrollSpeed}}}if(!g.axis||g.axis!="y"){if((d.overflowOffset.left+d.scrollParent[0].offsetWidth)-e.pageX<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(e.pageX-d.overflowOffset.left<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft-g.scrollSpeed}}}}else{if(!g.axis||g.axis!="x"){if(e.pageY-a(document).scrollTop()<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(e.pageY-a(document).scrollTop())<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}}if(!g.axis||g.axis!="y"){if(e.pageX-a(document).scrollLeft()<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(e.pageX-a(document).scrollLeft())<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}}if(c!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(d,e)}}});a.ui.plugin.add("draggable","snap",{start:function(d,e){var c=a(this).data("draggable"),f=c.options;c.snapElements=[];a(f.snap.constructor!=String?(f.snap.items||":data(draggable)"):f.snap).each(function(){var h=a(this);var g=h.offset();if(this!=c.element[0]){c.snapElements.push({item:this,width:h.outerWidth(),height:h.outerHeight(),top:g.top,left:g.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(d,e){var g=a(this).data("draggable").options;var f=a.makeArray(a(g.stack)).sort(function(i,h){return(parseInt(a(i).css("zIndex"),10)||0)-(parseInt(a(h).css("zIndex"),10)||0)});if(!f.length){return}var c=parseInt(f[0].style.zIndex)||0;a(f).each(function(h){this.style.zIndex=c+h});this[0].style.zIndex=c+f.length}});a.ui.plugin.add("draggable","zIndex",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("zIndex")){f._zIndex=c.css("zIndex")}c.css("zIndex",f.zIndex)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._zIndex){a(d.helper).css("zIndex",e._zIndex)}}})})(jQuery); /* * jQuery UI Mouse 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Mouse * * Depends: * jquery.ui.widget.js */ (function(b,c){var a=false;b(document).mouseup(function(d){a=false});b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var d=this;this.element.bind("mousedown."+this.widgetName,function(e){return d._mouseDown(e)}).bind("click."+this.widgetName,function(e){if(true===b.data(e.target,d.widgetName+".preventClickEvent")){b.removeData(e.target,d.widgetName+".preventClickEvent");e.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);if(this._mouseMoveDelegate){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)}},_mouseDown:function(f){if(a){return}(this._mouseStarted&&this._mouseUp(f));this._mouseDownEvent=f;var e=this,g=(f.which==1),d=(typeof this.options.cancel=="string"&&f.target.nodeName?b(f.target).closest(this.options.cancel).length:false);if(!g||d||!this._mouseCapture(f)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(f)&&this._mouseDelayMet(f)){this._mouseStarted=(this._mouseStart(f)!==false);if(!this._mouseStarted){f.preventDefault();return true}}if(true===b.data(f.target,this.widgetName+".preventClickEvent")){b.removeData(f.target,this.widgetName+".preventClickEvent")}this._mouseMoveDelegate=function(h){return e._mouseMove(h)};this._mouseUpDelegate=function(h){return e._mouseUp(h)};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);f.preventDefault();a=true;return true},_mouseMove:function(d){if(b.browser.msie&&!(document.documentMode>=9)&&!d.button){return this._mouseUp(d)}if(this._mouseStarted){this._mouseDrag(d);return d.preventDefault()}if(this._mouseDistanceMet(d)&&this._mouseDelayMet(d)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,d)!==false);(this._mouseStarted?this._mouseDrag(d):this._mouseUp(d))}return !this._mouseStarted},_mouseUp:function(d){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(d.target==this._mouseDownEvent.target){b.data(d.target,this.widgetName+".preventClickEvent",true)}this._mouseStop(d)}return false},_mouseDistanceMet:function(d){return(Math.max(Math.abs(this._mouseDownEvent.pageX-d.pageX),Math.abs(this._mouseDownEvent.pageY-d.pageY))>=this.options.distance)},_mouseDelayMet:function(d){return this.mouseDelayMet},_mouseStart:function(d){},_mouseDrag:function(d){},_mouseStop:function(d){},_mouseCapture:function(d){return true}})})(jQuery); /* * jQuery UI Sortable 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Sortables * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000},_create:function(){var c=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?c.axis==="x"||(/left|right/).test(this.items[0].item.css("float"))||(/inline|table-cell/).test(this.items[0].item.css("display")):false;this.offset=this.element.offset();this._mouseInit();this.ready=true},destroy:function(){a.Widget.prototype.destroy.call(this);this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var c=this.items.length-1;c>=0;c--){this.items[c].item.removeData(this.widgetName+"-item")}return this},_setOption:function(c,d){if(c==="disabled"){this.options[c]=d;this.widget()[d?"addClass":"removeClass"]("ui-sortable-disabled")}else{a.Widget.prototype._setOption.apply(this,arguments)}},_mouseCapture:function(g,h){var f=this;if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(g);var e=null,d=this,c=a(g.target).parents().each(function(){if(a.data(this,f.widgetName+"-item")==d){e=a(this);return false}});if(a.data(g.target,f.widgetName+"-item")==d){e=a(g.target)}if(!e){return false}if(this.options.handle&&!h){var i=false;a(this.options.handle,e).find("*").andSelf().each(function(){if(this==g.target){i=true}});if(!i){return false}}this.currentItem=e;this._removeCurrentsFromItems();return true},_mouseStart:function(f,g,c){var h=this.options,d=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(f);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:f.pageX-this.offset.left,top:f.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(f);this.originalPageX=f.pageX;this.originalPageY=f.pageY;(h.cursorAt&&this._adjustOffsetFromHelper(h.cursorAt));this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(h.containment){this._setContainment()}if(h.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",h.cursor)}if(h.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",h.opacity)}if(h.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",h.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",f,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!c){for(var e=this.containers.length-1;e>=0;e--){this.containers[e]._trigger("activate",f,d._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(f);return true},_mouseDrag:function(g){this.position=this._generatePosition(g);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var h=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-g.pageY<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+h.scrollSpeed}else{if(g.pageY-this.overflowOffset.top<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-h.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-g.pageX<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+h.scrollSpeed}else{if(g.pageX-this.overflowOffset.left<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-h.scrollSpeed}}}else{if(g.pageY-a(document).scrollTop()<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-h.scrollSpeed)}else{if(a(window).height()-(g.pageY-a(document).scrollTop())<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+h.scrollSpeed)}}if(g.pageX-a(document).scrollLeft()<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-h.scrollSpeed)}else{if(a(window).width()-(g.pageX-a(document).scrollLeft())<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+h.scrollSpeed)}}}if(c!==false&&a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,g)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],d=f.item[0],j=this._intersectsWithPointer(f);if(!j){continue}if(f.instance!==this.currentContainer){continue}if(d!=this.currentItem[0]&&this.placeholder[j==1?"next":"prev"]()[0]!=d&&!a.ui.contains(this.placeholder[0],d)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],d):true)){this.direction=j==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f)){this._rearrange(g,f)}else{break}this._trigger("change",g,this._uiHash());break}}this._contactContainers(g);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,g)}this._trigger("sort",g,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(d,e){if(!d){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,d)}if(this.options.revert){var c=this;var f=c.placeholder.offset();c.reverting=true;a(this.helper).animate({left:f.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:f.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(d)})}else{this._clear(d,e)}return false},cancel:function(){var c=this;if(this.dragging){this._mouseUp({target:null});if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("deactivate",null,c._uiHash(this));if(this.containers[d].containerCache.over){this.containers[d]._trigger("out",null,c._uiHash(this));this.containers[d].containerCache.over=0}}}if(this.placeholder){if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}}return this},serialize:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};a(c).each(function(){var f=(a(e.item||this).attr(e.attribute||"id")||"").match(e.expression||(/(.+)[-=_](.+)/));if(f){d.push((e.key||f[1]+"[]")+"="+(e.key&&e.expression?f[1]:f[2]))}});if(!d.length&&e.key){d.push(e.key+"=")}return d.join("&")},toArray:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};c.each(function(){d.push(a(e.item||this).attr(e.attribute||"id")||"")});return d},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(e){var f=(this.options.axis==="x")||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),d=(this.options.axis==="y")||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),h=f&&d,c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(!h){return false}return this.floating?(((g&&g=="right")||c=="down")?2:1):(c&&(c=="down"?2:1))},_intersectsWithSides:function(f){var d=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,f.top+(f.height/2),f.height),e=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,f.left+(f.width/2),f.width),c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(this.floating&&g){return((g=="right"&&e)||(g=="left"&&!e))}else{return c&&((c=="down"&&d)||(c=="up"&&!d))}},_getDragVerticalDirection:function(){var c=this.positionAbs.top-this.lastPositionAbs.top;return c!=0&&(c>0?"down":"up")},_getDragHorizontalDirection:function(){var c=this.positionAbs.left-this.lastPositionAbs.left;return c!=0&&(c>0?"right":"left")},refresh:function(c){this._refreshItems(c);this.refreshPositions();return this},_connectWith:function(){var c=this.options;return c.connectWith.constructor==String?[c.connectWith]:c.connectWith},_getItemsAsjQuery:function(c){var m=this;var h=[];var f=[];var k=this._connectWith();if(k&&c){for(var e=k.length-1;e>=0;e--){var l=a(k[e]);for(var d=l.length-1;d>=0;d--){var g=a.data(l[d],this.widgetName);if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element):a(g.options.items,g.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),g])}}}}f.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var e=f.length-1;e>=0;e--){f[e][0].each(function(){h.push(this)})}return a(h)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");for(var d=0;d<this.items.length;d++){for(var c=0;c<e.length;c++){if(e[c]==this.items[d].item[0]){this.items.splice(d,1)}}}},_refreshItems:function(c){this.items=[];this.containers=[this];var k=this.items;var q=this;var g=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],c,{item:this.currentItem}):a(this.options.items,this.element),this]];var m=this._connectWith();if(m&&this.ready){for(var f=m.length-1;f>=0;f--){var n=a(m[f]);for(var e=n.length-1;e>=0;e--){var h=a.data(n[e],this.widgetName);if(h&&h!=this&&!h.options.disabled){g.push([a.isFunction(h.options.items)?h.options.items.call(h.element[0],c,{item:this.currentItem}):a(h.options.items,h.element),h]);this.containers.push(h)}}}}for(var f=g.length-1;f>=0;f--){var l=g[f][1];var d=g[f][0];for(var e=0,o=d.length;e<o;e++){var p=a(d[e]);p.data(this.widgetName+"-item",l);k.push({item:p,instance:l,width:0,height:0,left:0,top:0})}}},refreshPositions:function(c){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e];if(f.instance!=this.currentContainer&&this.currentContainer&&f.item[0]!=this.currentItem[0]){continue}var d=this.options.toleranceElement?a(this.options.toleranceElement,f.item):f.item;if(!c){f.width=d.outerWidth();f.height=d.outerHeight()}var g=d.offset();f.left=g.left;f.top=g.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var e=this.containers.length-1;e>=0;e--){var g=this.containers[e].element.offset();this.containers[e].containerCache.left=g.left;this.containers[e].containerCache.top=g.top;this.containers[e].containerCache.width=this.containers[e].element.outerWidth();this.containers[e].containerCache.height=this.containers[e].element.outerHeight()}}return this},_createPlaceholder:function(e){var c=e||this,f=c.options;if(!f.placeholder||f.placeholder.constructor==String){var d=f.placeholder;f.placeholder={element:function(){var g=a(document.createElement(c.currentItem[0].nodeName)).addClass(d||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!d){g.style.visibility="hidden"}return g},update:function(g,h){if(d&&!f.forcePlaceholderSize){return}if(!h.height()){h.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10))}if(!h.width()){h.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}}c.placeholder=a(f.placeholder.element.call(c.element,c.currentItem));c.currentItem.after(c.placeholder);f.placeholder.update(c,c.placeholder)},_contactContainers:function(c){var e=null,l=null;for(var g=this.containers.length-1;g>=0;g--){if(a.ui.contains(this.currentItem[0],this.containers[g].element[0])){continue}if(this._intersectsWith(this.containers[g].containerCache)){if(e&&a.ui.contains(this.containers[g].element[0],e.element[0])){continue}e=this.containers[g];l=g}else{if(this.containers[g].containerCache.over){this.containers[g]._trigger("out",c,this._uiHash(this));this.containers[g].containerCache.over=0}}}if(!e){return}if(this.containers.length===1){this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}else{if(this.currentContainer!=this.containers[l]){var k=10000;var h=null;var d=this.positionAbs[this.containers[l].floating?"left":"top"];for(var f=this.items.length-1;f>=0;f--){if(!a.ui.contains(this.containers[l].element[0],this.items[f].item[0])){continue}var m=this.containers[l].floating?this.items[f].item.offset().left:this.items[f].item.offset().top;if(Math.abs(m-d)<k){k=Math.abs(m-d);h=this.items[f];this.direction=(m-d>0)?"down":"up"}}if(!h&&!this.options.dropOnEmpty){return}this.currentContainer=this.containers[l];h?this._rearrange(c,h,null,true):this._rearrange(c,null,this.containers[l].element,true);this._trigger("change",c,this._uiHash());this.containers[l]._trigger("change",c,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}}},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d,this.currentItem])):(e.helper=="clone"?this.currentItem.clone():this.currentItem);if(!c.parents("body").length){a(e.appendTo!="parent"?e.appendTo:this.currentItem[0].parentNode)[0].appendChild(c[0])}if(c[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(c[0].style.width==""||e.forceHelperSize){c.width(this.currentItem.width())}if(c[0].style.height==""||e.forceHelperSize){c.height(this.currentItem.height())}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.currentItem.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var f=this.options;if(f.containment=="parent"){f.containment=this.helper[0].parentNode}if(f.containment=="document"||f.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(f.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(f.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(f.containment)){var d=a(f.containment)[0];var e=a(f.containment).offset();var c=(a(d).css("overflow")!="hidden");this.containment=[e.left+(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0)-this.margins.left,e.top+(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0)-this.margins.top,e.left+(c?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,e.top+(c?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(f){var i=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,j=(/(html|body)/i).test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var e=f.pageX;var d=f.pageY;if(this.originalPosition){if(this.containment){if(f.pageX-this.offset.click.left<this.containment[0]){e=this.containment[0]+this.offset.click.left}if(f.pageY-this.offset.click.top<this.containment[1]){d=this.containment[1]+this.offset.click.top}if(f.pageX-this.offset.click.left>this.containment[2]){e=this.containment[2]+this.offset.click.left}if(f.pageY-this.offset.click.top>this.containment[3]){d=this.containment[3]+this.offset.click.top}}if(i.grid){var h=this.originalPageY+Math.round((d-this.originalPageY)/i.grid[1])*i.grid[1];d=this.containment?(!(h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3])?h:(!(h-this.offset.click.top<this.containment[1])?h-i.grid[1]:h+i.grid[1])):h;var g=this.originalPageX+Math.round((e-this.originalPageX)/i.grid[0])*i.grid[0];e=this.containment?(!(g-this.offset.click.left<this.containment[0]||g-this.offset.click.left>this.containment[2])?g:(!(g-this.offset.click.left<this.containment[0])?g-i.grid[0]:g+i.grid[0])):g}}return{top:(d-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(j?0:c.scrollTop())))),left:(e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():j?0:c.scrollLeft())))}},_rearrange:function(h,g,d,f){d?d[0].appendChild(this.placeholder[0]):g.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?g.item[0]:g.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var e=this,c=this.counter;window.setTimeout(function(){if(c==e.counter){e.refreshPositions(!f)}},0)},_clear:function(e,f){this.reverting=false;var g=[],c=this;if(!this._noFinalSort&&this.currentItem.parent().length){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var d in this._storedCSS){if(this._storedCSS[d]=="auto"||this._storedCSS[d]=="static"){this._storedCSS[d]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!f){g.push(function(h){this._trigger("receive",h,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!f){g.push(function(h){this._trigger("update",h,this._uiHash())})}if(this!==this.currentContainer){if(!f){g.push(function(h){this._trigger("remove",h,this._uiHash())});g.push((function(h){return function(i){h._trigger("receive",i,this._uiHash(this))}}).call(this,this.currentContainer));g.push((function(h){return function(i){h._trigger("update",i,this._uiHash(this))}}).call(this,this.currentContainer))}}for(var d=this.containers.length-1;d>=0;d--){if(!f){g.push((function(h){return function(i){h._trigger("deactivate",i,this._uiHash(this))}}).call(this,this.containers[d]))}if(this.containers[d].containerCache.over){g.push((function(h){return function(i){h._trigger("out",i,this._uiHash(this))}}).call(this,this.containers[d]));this.containers[d].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!f){this._trigger("beforeStop",e,this._uiHash());for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return false}if(!f){this._trigger("beforeStop",e,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!f){for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(d){var c=d||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:d?d.element:null}}});a.extend(a.ui.sortable,{version:"1.8.24"})})(jQuery); /* * jQuery UI Widget 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function(b,d){if(b.cleanData){var c=b.cleanData;b.cleanData=function(f){for(var g=0,h;(h=f[g])!=null;g++){try{b(h).triggerHandler("remove")}catch(j){}}c(f)}}else{var a=b.fn.remove;b.fn.remove=function(e,f){return this.each(function(){if(!f){if(!e||b.filter(e,[this]).length){b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove")}catch(g){}})}}return a.call(b(this),e,f)})}}b.widget=function(f,h,e){var g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return !!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var i=new h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])};b.widget.bridge=function(f,e){b.fn[f]=function(i){var g=typeof i==="string",h=Array.prototype.slice.call(arguments,1),j=this;i=!g&&h.length?b.extend.apply(null,[true,i].concat(h)):i;if(g&&i.charAt(0)==="_"){return j}if(g){this.each(function(){var k=b.data(this,f),l=k&&b.isFunction(k[i])?k[i].apply(k,h):k;if(l!==k&&l!==d){j=l;return false}})}else{this.each(function(){var k=b.data(this,f);if(k){k.option(i||{})._init()}else{b.data(this,f,new e(i,this))}})}return j}};b.Widget=function(e,f){if(arguments.length){this._createWidget(e,f)}};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(f,g){b.data(g,this.widgetName,this);this.element=b(g);this.options=b.extend(true,{},this.options,this._getCreateOptions(),f);var e=this;this.element.bind("remove."+this.widgetName,function(){e.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(f,g){var e=f;if(arguments.length===0){return b.extend({},this.options)}if(typeof f==="string"){if(g===d){return this.options[f]}e={};e[f]=g}this._setOptions(e);return this},_setOptions:function(f){var e=this;b.each(f,function(g,h){e._setOption(g,h)});return this},_setOption:function(e,f){this.options[e]=f;if(e==="disabled"){this.widget()[f?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",f)}return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(e,f,g){var j,i,h=this.options[e];g=g||{};f=b.Event(f);f.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();f.target=this.element[0];i=f.originalEvent;if(i){for(j in i){if(!(j in f)){f[j]=i[j]}}}this.element.trigger(f,g);return !(b.isFunction(h)&&h.call(this.element[0],f,g)===false||f.isDefaultPrevented())}}})(jQuery);
packages/material-ui-icons/src/LocationDisabledSharp.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M23 13v-2h-2.06c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-.98.11-1.91.38-2.77.78l1.53 1.53C10.46 5.13 11.22 5 12 5c3.87 0 7 3.13 7 7 0 .79-.13 1.54-.37 2.24l1.53 1.53c.4-.86.67-1.79.78-2.77H23zM4.41 2.86L3 4.27l2.04 2.04C3.97 7.62 3.26 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21l1.41-1.41L4.41 2.86zM12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81C15.09 18.45 13.61 19 12 19z" /></g></React.Fragment> , 'LocationDisabledSharp');
ajax/libs/yui/3.5.0/event-custom-base/event-custom-base-debug.js
rigdern/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']});
src/client/containers/AddTodo.js
wpcfan/calltalent_web
import React from 'react'; import { connect } from 'react-redux'; import { addTodo } from '../actions'; const AddingTodo = ({ dispatch }) => { let input; return ( <div> <form onSubmit={e => { e.preventDefault(); if (!input.value.trim()) { return; } dispatch(addTodo(input.value)); input.value = ''; }}> <input ref={node => { input = node; }} /> <button type="submit"> Add Todo </button> </form> </div> ); }; const AddTodo = connect()(AddingTodo); export default AddTodo;
app/views/components/item-column/placeholder-cards.js
jeffreymoya/sprintly-kanban
import _ from 'lodash'; import React from 'react'; import OwnerAvatar from '../item-card/owner'; // Flux import HeaderActions from '../../../actions/header-actions' import HeaderStore from '../../../stores/header-store' const CURRENT_COL_STATUS = 'in-progress'; var PlaceholderCards = React.createClass({ propTypes: { status: React.PropTypes.string.isRequired }, ipsumBlocks() { var length = _.sample([1, 2, 3]); return _.times(length, (n) => { var width = (n === length-1) ? Math.floor((Math.random() * (100 - 50) + 50)) : 100; return <div style={ {width: `${width}%`} } className="ipsum-block" key={n}></div> }) }, actionContent() { return ([ <div className="prompt__create-item" key="add-item-label">Add an Item to get started!</div>, <button style={ {width: "100%"} } key="add-item-button" className="btn btn-primary" onClick={this.triggerModal}>Add an Item</button> ] ) }, triggerModal() { HeaderActions.openAddModal(); }, placeholderCards() { return _.times(8, (n) => { var content; if (n === 2 && this.props.status === CURRENT_COL_STATUS) { content = this.actionContent(); } else { content = this.ipsumBlocks(); } return ( <div className="item-card placeholder" key={n}> <div className="row"> <div className="item-card__header col-sm-12"> <div className="item-card__header-right"> <span><OwnerAvatar person="placeholder-light" /></span> </div> </div> <div className="item-card__title col-sm-12"> {content} </div> </div> </div> ) }) }, render() { return ( <div className='placeholder-cards'> {this.placeholderCards()} </div> ); } }); module.exports = PlaceholderCards;
ajax/libs/react/0.6.3/react.js
janpaepke/cdnjs
;!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); /*global define:true EventEmitter2:true */ define('react/eventemitter',['eventemitter2'], function (EventEmitterMod) { /** Abstract the details of getting an EventEmitter */ // EventEmitter doesn't return itself in browser so need to get the global // EventEmitter api changed, so accomodate which ever version is available var EventEmitter = (EventEmitterMod) ? ((EventEmitterMod.EventEmitter2) ? EventEmitterMod.EventEmitter2 : EventEmitterMod) : EventEmitter2; return EventEmitter; }); /*global define:true */ // 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. define('util',['require','exports','module'],function (require, exports, module) { /*jshint white:false */ var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (typeof f !== 'string') { var objects = []; for (var j = 0; j < arguments.length; j++) { objects.push(inspect(arguments[j])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': return JSON.stringify(args[i++]); default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (x === null || typeof x !== 'object') { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; exports.print = function() { for (var i = 0, len = arguments.length; i < len; ++i) { process.stdout.write(String(arguments[i])); } }; exports.puts = function() { for (var i = 0, len = arguments.length; i < len; ++i) { process.stdout.write(arguments[i] + '\n'); } }; exports.debug = function(x) { process.stderr.write('DEBUG: ' + x + '\n'); }; var error = exports.error = function(x) { for (var i = 0, len = arguments.length; i < len; ++i) { process.stderr.write(arguments[i] + '\n'); } }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Boolean} showHidden Flag that shows hidden (not enumerable) * properties of objects. * @param {Number} depth Depth in which to descend in object. Default is 2. * @param {Boolean} colors Flag to turn on ANSI escape codes to color the * output. Default is false (no coloring). */ function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: colors ? stylizeWithColor : stylizeNoColor }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics var 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] }; // Don't use 'blue' not visible on cmd.exe var styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = styles[styleType]; if (style) { return '\033[' + colors[style][0] + 'm' + str + '\033[' + colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { return value.inspect(recurseTimes); } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var visibleKeys = Object.keys(value); var keys = ctx.showHidden ? Object.getOwnPropertyNames(value) : visibleKeys; // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (typeof value === 'function') { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (typeof value === 'function') { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length === 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { switch (typeof value) { case 'undefined': return ctx.stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); case 'number': return ctx.stylize('' + value, 'number'); case 'boolean': return ctx.stylize('' + value, 'boolean'); } // For some reason typeof null is "object", so special case here. if (value === null) { return ctx.stylize('null', 'null'); } } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (Object.prototype.hasOwnProperty.call(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (visibleKeys.indexOf(key) < 0) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (recurseTimes === null) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); } exports.isArray = isArray; function isRegExp(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isDate(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return typeof e === 'object' && objectToString(e) === '[object Error]'; } exports.isError = isError; function objectToString(o) { return Object.prototype.toString.call(o); } // exports.p = function() { // for (var i = 0, len = arguments.length; i < len; ++i) { // error(exports.inspect(arguments[i])); // } // }; // module.deprecate('p', 'Use `util.puts(util.inspect())` instead.'); function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } exports.log = function(msg) { exports.puts(timestamp() + ' - ' + msg.toString()); }; // exports.exec = function() { // return require('child_process').exec.apply(this, arguments); // }; // module.deprecate('exec', 'It is now called `child_process.exec`.'); exports.pump = function(readStream, writeStream, callback) { var callbackCalled = false; function call(a, b, c) { if (callback && !callbackCalled) { callback(a, b, c); callbackCalled = true; } } readStream.addListener('data', function(chunk) { if (writeStream.write(chunk) === false) readStream.pause(); }); writeStream.addListener('drain', function() { readStream.resume(); }); readStream.addListener('end', function() { writeStream.end(); }); readStream.addListener('close', function() { call(); }); readStream.addListener('error', function(err) { writeStream.end(); call(err); }); writeStream.addListener('error', function(err) { readStream.destroy(); call(err); }); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; }); /*global define:true */ define('react/error',['util'], function (util) { function ensureStackTraceLimitSet(stackTraceLimit) { if (!Error.stackTraceLimit || Error.stackTraceLimit < stackTraceLimit) { Error.stackTraceLimit = stackTraceLimit; } } function fName(fn) { if (!fn) return 'undefined'; return (fn && fn.name) ? fn.name : fn; } function formatErrorMeta(err) { if (!err.meta) return; var vcon = err.meta.vcon; var task = err.meta.task; var errString = '\n\n'; if (task && task.f && task.a) { errString += ('Error occurs in Task function: ' + fName(task.f) + '(' + task.a.join(',') + ')\n\n'); } if (vcon) { errString += 'Variable Context: \n'; errString += util.inspect(vcon); errString += '\n\n'; } if (task && task.f) { errString += 'Task Source:\n\n'; errString += task.f.toString(); //TODO need to pretty print function, gets collapsed errString += '\n\n'; } return errString; } function augmentError(err, meta) { if (typeof(err) === 'string') { err = new Error(err); } //props will be lost on non-objects var origMsg = err.toString(); err.meta = meta; err.toString = function () { return origMsg + formatErrorMeta(err); }; return err; } return { ensureStackTraceLimitSet: ensureStackTraceLimitSet, augmentError: augmentError }; }); /*global define:true sprint:true */ define('react/sprintf',['util'], function (util) { /** Abstract the details of getting a sprintf function. Currently using the simple format capabilities of node's util.format */ var sprintf = util.format; return sprintf; }); (function (root, factory) { /*global define:true */ if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define('ensure-array',[], factory); } else { // Browser globals root.ensureArray = factory(); } }(this, function () { function ensureArray(a, b, n) { if (arguments.length === 0) return []; //no args, ret [] if (arguments.length === 1) { //single argument if (a === undefined || a === null) return []; // undefined or null, ret [] if (Array.isArray(a)) return a; // isArray, return it } return Array.prototype.slice.call(arguments); //return array with copy of all arguments } return ensureArray; })); /*global define:true */ define('react/status',[], function () { var STATUS = { READY: 'ready', RUNNING: 'running', ERRORED: 'errored', COMPLETE: 'complete' }; return STATUS; }); /*global define:true process:false*/ define('react/event-manager',['./eventemitter'], function (EventEmitter) { /*jshint regexp:false */ var EVENT_EMITTER2_CONFIG = { wildcard: true, // should the event emitter use wildcards. delimiter: '.', // the delimiter used to segment namespaces, defaults to `.`. maxListeners: 30 // the max number of listeners that can be assigned to an event, defaults to 10. }; var PASS_EVENTS_PROCESS_RE = /^ast.defined$/; // events to pass up to global process var TYPES = { // Flow monitoring events and their params AST_DEFINED: 'ast.defined', // ast FLOW_BEGIN: 'flow.begin', // env TASK_BEGIN: 'task.begin', // task TASK_COMPLETE: 'task.complete', // task TASK_ERRORED: 'task.errored', // task FLOW_COMPLETE: 'flow.complete', // env FLOW_ERRORED: 'flow.errored', // env // Internal Hooks EXEC_FLOW_START: 'exec.flow.start', // env EXEC_INPUT_PREPROCESS: 'exec.input.preprocess', // parsedInput EXEC_TASKS_PRECREATE: 'exec.tasks.precreate', // env EXEC_OUTTASK_CREATE: 'exec.outTask.create', // outTaskOptions EXEC_TASK_START: 'exec.task.start', // task EXEC_TASK_COMPLETE: 'exec.task.complete', // task EXEC_TASK_ERRORED: 'exec.task.errored', // task EXEC_FLOW_COMPLETE: 'exec.flow.complete', // env EXEC_FLOW_ERRORED: 'exec.flow.errored' // env }; /** Event manager which emits events up to its parent if exists. Allows a hierarchy of emitters, which communicate up the chain. */ function EventManager() { } EventManager.create = function () { return new EventManager(); }; EventManager.TYPES = TYPES; EventManager.prototype.TYPES = TYPES; EventManager.prototype.isEnabled = function () { // if has listener or an ancestor has listener return !!(this.emitter || (this.parent && this.parent.isEnabled())); }; /** Add listener. Wildcard events are allowed like 'foo.*' Use '*' to listen to any event */ EventManager.prototype.on = function (event, listener) { if (!this.emitter) this.emitter = new EventEmitter(EVENT_EMITTER2_CONFIG); if (event === '*') this.emitter.onAny(listener); else this.emitter.on(event, listener); }; EventManager.prototype.emit = function (event, arg1, arg2, argN) { if (event === undefined) throw new Error('event is undefined'); if (this.emitter) this.emitter.emit.apply(this.emitter, arguments); if (this.parent && this.parent.isEnabled()) this.parent.emit.apply(this.parent, arguments); if (PASS_EVENTS_PROCESS_RE.test(event) && typeof(process) !== 'undefined' && process.emit) { process.emit.apply(process, arguments); // pass some to process } }; EventManager.prototype.removeListener = function (event, listener) { if (this.emitter) this.emitter.removeListener.apply(this.emitter, arguments); }; EventManager.prototype.removeAllListeners = function (event) { if (this.emitter) this.emitter.removeAllListeners.apply(this.emitter, arguments); }; EventManager.global = EventManager.create(); // create one top level emitter return EventManager; }); /*global define:true */ define('react/base-task',['ensure-array', './status', './event-manager'], function (array, STATUS, EventManager) { function BaseTask() { } /** Getter Fn to retrieveAn array of the output param names for this task. */ BaseTask.prototype.getOutParams = function () { return array(this.out); // ensure array }; BaseTask.prototype.isComplete = function () { return (this.status === STATUS.COMPLETE); }; BaseTask.prototype.start = function (args) { // mark task as started with args and note time /*jshint validthis: true */ this.args = args; this.env.currentTask = this; this.env.flowEmitter.emit(EventManager.TYPES.EXEC_TASK_START, this); }; BaseTask.prototype.complete = function (args) { //args that were used are available /*jshint validthis: true */ this.status = STATUS.COMPLETE; this.results = args; this.env.currentTask = this; this.env.flowEmitter.emit(EventManager.TYPES.EXEC_TASK_COMPLETE, this); }; BaseTask.prototype.functionExists = function (vCon) { var fn = this.f; if (!fn) return false; if (fn instanceof Function) return true; if (typeof(fn) === 'string') { var f = vCon.getVar(fn); // fn/method by string if (f && f instanceof Function) return true; } return false; }; BaseTask.prototype.areAllDepArgsDefined = function (vCon) { return this.a.every(function (k) { return (vCon.getVar(k) !== undefined); }); }; BaseTask.prototype.depTasksAreDone = function (tasksByName) { return (!this.after || !this.after.length || // no dep tasks OR this.after.every(function (n) { return tasksByName[n].isComplete(); })); //all done }; function isObjProperty(str) { return (str.indexOf('.') !== -1); } /** check that obj parent is def and not null so writing to obj.prop will not fail. ex: 'b.c' checks that b is def and not null. Also returns true if not obj.prop but simple var ex: 'b'. Tasks will implement outParentsExist() passing each out str to this if they want to do this check. */ BaseTask.prototype.parentExists = function (objPropStr, vCon) { if (!isObjProperty(objPropStr)) return true; // NOT obj prop, just simple arg, ret true var nameAndProps = objPropStr.split('.'); nameAndProps.pop(); // pop off final prop var parent = nameAndProps.reduce(function (accObj, prop) { if (accObj === undefined || accObj === null) return undefined; // prevent exception return accObj[prop]; }, vCon.values); // vCon['foo']['bar'] return (parent !== undefined && parent !== null); }; /** If params are obj property writes make sure the dst objects are defined and not null. cb: ['b.c'] -> b is def and not null. If null is specified then param is valid and will be ignored. @returns true if all obj prop parents are def and non null */ BaseTask.prototype.outParentsExist = function (vCon) { var self = this; return this.getOutParams().every(function (x) { if (x === null) return true; return self.parentExists(x, vCon); }); }; BaseTask.prototype.isReady = function (vCon, tasksByName) { return !this.status && // not started AND this.functionExists(vCon) && // function/method exists AND this.areAllDepArgsDefined(vCon) && // all dep vars defined AND this.depTasksAreDone(tasksByName) && // all dep tasks are done AND (!this.outParentsExist || // (task does not implement outParentsExist method OR this.outParentsExist(vCon)); // output parents exists (for obj property writes) }; BaseTask.prototype.isMethodCall = function () { /*jshint regexp: false */ return (typeof(this.f) === 'string' && /^.*\..*$/.test(this.f)); //str contains . }; BaseTask.prototype.getMethodObj = function (vCon) { //obj.prop.prop2, returns obj.prop or undefined var name = this.f; if (!name) return undefined; var nameAndProps = name.split('.'); nameAndProps.pop(); // pop off last one if (!nameAndProps.length) return undefined; var result = nameAndProps.reduce(function (accObj, prop) { if (accObj === undefined || accObj === null) return undefined; // prevent exception return accObj[prop]; }, vCon.values); // vCon['foo']['bar'] return result; }; return BaseTask; }); /*global define:true */ define('react/cb-task',['util', './sprintf', './base-task'], function (util, sprintf, BaseTask) { function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } var REQ = 'cbTask requires f, a, out'; var FN_REQ = 'cbTask requires f to be a function or string'; var A_REQ = 'cbTask requires a to be an array of string param names'; var CB_REQ = 'cbTask requires out to be an array of string param names'; function CbTask(taskDef) { var self = this; Object.keys(taskDef).forEach(function (k) { self[k] = taskDef[k]; }); } CbTask.prototype = new BaseTask(); CbTask.prototype.constructor = CbTask; CbTask.validate = function (taskDef) { var errors = []; if (!taskDef.f || !taskDef.a || !taskDef.out) { errors.push(format_error(REQ, taskDef)); } else { var ftype = typeof(taskDef.f); if (! ((taskDef.f instanceof Function) || (ftype === 'string'))) { errors.push(format_error(FN_REQ, taskDef)); } if (! (Array.isArray(taskDef.a) && taskDef.a.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(A_REQ, taskDef)); } if (! (Array.isArray(taskDef.out) && taskDef.out.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(CB_REQ, taskDef)); } } return errors; }; CbTask.prototype.prepare = function prepare(handleTaskError, vCon, contExec) { var self = this; this.cbFun = function (err, arg0, arg1, argn) { var args = Array.prototype.slice.call(arguments, 1); if (err) { handleTaskError(self, err); return; } //handle error and return, we are done //no error, save callback args to vCon context, then continue execution vCon.saveResults(self.out, args); self.complete(args); contExec(); }; }; CbTask.prototype.exec = function exec(vCon, handleError, contExec) { try { var args = this.a.map(function (k) { return vCon.getVar(k); }); //get args from vCon //console.error('CbTask.exec.args=', args); //console.error('CbTask.exec.vCon=', vCon); this.start(args); //note the start time, args args.push(this.cbFun); // push callback fn on end var func = this.f; var bindObj = vCon.getVar('this'); //global space or the original this if (this.isMethodCall()) { //if method call then reset func and bindObj func = vCon.getVar(this.f); bindObj = this.getMethodObj(vCon); } else if (typeof(func) === 'string') { func = vCon.getVar(func); // we want the actual fn from this string } func.apply(bindObj, args); } catch (err) { //catch and handle the task error, calling final cb handleError(this, err); } }; return CbTask; }); /*global define:true */ define('react/promise-task',['util', './sprintf', './base-task'], function (util, sprintf, BaseTask) { /** PromiseTask is a task which executes a fn that returns a promise and when it completes it sets the values in vCon */ function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } var REQ = 'promiseTask requires f, a, out'; var FN_REQ = 'promiseTask requires f to be a function or string'; var A_REQ = 'promiseTask requires a to be an array of string param names'; var OUT_REQ = 'promiseTask requires out to be an array[1] of string param names'; function PromiseTask(taskDef) { var self = this; Object.keys(taskDef).forEach(function (k) { self[k] = taskDef[k]; }); } PromiseTask.prototype = new BaseTask(); PromiseTask.prototype.constructor = PromiseTask; PromiseTask.validate = function (taskDef) { var errors = []; if (!taskDef.f || !taskDef.a || !taskDef.out) { errors.push(format_error(REQ, taskDef)); } else { var ftype = typeof(taskDef.f); if (! ((taskDef.f instanceof Function) || (ftype === 'string'))) { errors.push(format_error(FN_REQ, taskDef)); } if (! (Array.isArray(taskDef.a) && taskDef.a.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(A_REQ, taskDef)); } if (! (Array.isArray(taskDef.out) && taskDef.out.length <= 1 && taskDef.out.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(OUT_REQ, taskDef)); } } return errors; }; PromiseTask.prototype.prepare = function prepare(handleTaskError, vCon, contExec) { var self = this; this.nextFn = function (arg) { var args = Array.prototype.slice.call(arguments); vCon.saveResults(self.out, args); self.complete(args); contExec(); }; this.failFn = function (err) { handleTaskError(self, err); }; }; PromiseTask.prototype.exec = function exec(vCon, handleError, contExec) { try { var args = this.a.map(function (k) { return vCon.getVar(k); }); //get args from vCon //console.error('PromiseTask.exec.args=', args); //console.error('PromiseTask.exec.vCon=', vCon); this.start(args); //note the start time, args var func = this.f; var bindObj = vCon.getVar('this'); //global space or the original this if (this.isMethodCall()) { //if method call then reset func and bindObj func = vCon.getVar(this.f); bindObj = this.getMethodObj(vCon); } else if (typeof(func) === 'string') { func = vCon.getVar(func); // we want the actual fn from this string } var retValue = func.apply(bindObj, args); if (retValue && typeof(retValue.then) === 'function') { // is a promise retValue.then(this.nextFn, this.failFn); } else { // just a value, proceed now this.nextFn(retValue); } } catch (err) { //catch and handle the task error, calling final cb handleError(this, err); } }; return PromiseTask; }); /*global define:true */ define('react/ret-task',['util', './sprintf', './base-task'], function (util, sprintf, BaseTask) { function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } var REQ = 'retTask requires f, a, out'; var FN_REQ = 'retTask requires f to be a function or string'; var A_REQ = 'retTask requires a to be an array of string param names'; var RET_REQ = 'retTask requires out to be an array with single string param name or []'; function RetTask(taskDef) { var self = this; Object.keys(taskDef).forEach(function (k) { self[k] = taskDef[k]; }); } RetTask.prototype = new BaseTask(); RetTask.prototype.constructor = RetTask; RetTask.validate = function (taskDef) { var errors = []; if (!taskDef.f || !taskDef.a || !taskDef.out) { errors.push(format_error(REQ, taskDef)); } else { var ftype = typeof(taskDef.f); if (! ((taskDef.f instanceof Function) || (ftype === 'string'))) { errors.push(format_error(FN_REQ, taskDef)); } if (! (Array.isArray(taskDef.a) && taskDef.a.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(A_REQ, taskDef)); } if (! (Array.isArray(taskDef.out) && (taskDef.out.length === 0 || (taskDef.out.length === 1 && typeof(taskDef.out[0] === 'string'))))) { errors.push(format_error(RET_REQ, taskDef)); } } return errors; }; RetTask.prototype.exec = function exec(vCon, handleError, contExec) { try { var args = this.a.map(function (k) { return vCon.getVar(k); }); //get args from vCon this.start(args); //note the start time, args var func = this.f; var bindObj = vCon.getVar('this'); //global space or the original this if (this.isMethodCall()) { //if method call then reset func and bindObj func = vCon.getVar(this.f); bindObj = this.getMethodObj(vCon); } else if (typeof(func) === 'string') { func = vCon.getVar(func); // we want the actual fn from this string } var results = [func.apply(bindObj, args)]; vCon.saveResults(this.out, results); // save retval, takes arrays this.complete(results); contExec(); // continue since no callback to run this } catch (err) { handleError(this, err); } // catch and handle the task error, calling final cb }; return RetTask; }); /*global define:true */ define('react/when-task',['util', './sprintf', './base-task'], function (util, sprintf, BaseTask) { /** When task which checks if is a promise (has a then method) and waits for it to resolve. If argument does not have a then method, it resolves immediately */ function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } var REQ = 'whenTask requires a, out'; var A_REQ = 'whenTask requires a to be an array[1] of string param names'; var OUT_REQ = 'whenTask requires out to be an array[1] of string param names'; function WhenTask(taskDef) { var self = this; Object.keys(taskDef).forEach(function (k) { self[k] = taskDef[k]; }); } WhenTask.prototype = new BaseTask(); WhenTask.prototype.constructor = WhenTask; WhenTask.prototype.f = function when() { // just here to keep validations happy } WhenTask.validate = function (taskDef) { var errors = []; if (!taskDef.a || !taskDef.out) { errors.push(format_error(REQ, taskDef)); } else { if (! (Array.isArray(taskDef.a) && taskDef.a.length === 1 && taskDef.a.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(A_REQ, taskDef)); } if (! (Array.isArray(taskDef.out) && taskDef.out.length <= 1 && taskDef.out.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(OUT_REQ, taskDef)); } } return errors; }; WhenTask.prototype.prepare = function prepare(handleTaskError, vCon, contExec) { var self = this; this.nextFn = function (arg) { var args = Array.prototype.slice.call(arguments); vCon.saveResults(self.out, args); self.complete(args); contExec(); }; this.failFn = function (err) { handleTaskError(self, err); }; }; WhenTask.prototype.exec = function exec(vCon, handleError, contExec) { try { var args = this.a.map(function (k) { return vCon.getVar(k); }); //get args from vCon //console.error('WhenTask.exec.args=', args); //console.error('WhenTask.exec.vCon=', vCon); this.start(args); //note the start time, args var arg = args[0]; // one value allowed if (arg && typeof(arg.then) === 'function') { // is a promise arg.then(this.nextFn, this.failFn); } else { // not a promise continue immediately this.nextFn(arg); } } catch (err) { //catch and handle the task error, calling final cb handleError(this, err); } }; return WhenTask; }); /*global define:true */ define('react/finalcb-task',['./sprintf', 'util', './status', './event-manager'], function (sprintf, util, STATUS, EventManager) { var OUTTASK_A_REQ = 'ast.outTask.a should be an array of string param names'; function FinalCbTask(outTaskOptions) { var taskDef = outTaskOptions.taskDef; if (typeof(outTaskOptions.cbFunc) !== 'function') throw new Error('callback is not a function'); var self = this; for (var k in taskDef) { if (true) self[k] = taskDef[k]; // if to make jshint happy } this.f = outTaskOptions.cbFunc; this.tasks = outTaskOptions.tasks; this.vCon = outTaskOptions.vCon; this.retValue = outTaskOptions.retValue; this.execOptions = outTaskOptions.execOptions; this.env = outTaskOptions.env; } function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } FinalCbTask.validate = function (taskDef) { var errors = []; if (! (Array.isArray(taskDef.a) && taskDef.a.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(OUTTASK_A_REQ, taskDef)); } return errors; }; FinalCbTask.prototype.isReady = function () { return (this.tasks.every(function (t) { return (t.status === STATUS.COMPLETE); })); }; FinalCbTask.prototype.exec = function (err) { if (!this.f) return; //must have already been called if (err) { this.env.error = err; this.env.flowEmitter.emit(EventManager.TYPES.EXEC_FLOW_ERRORED, this.env); this.f.call(null, err); //call the final callback with the first error hit } else { // no error, call with args var vCon = this.vCon; var finalArgs = this.a.map(function (k) { return vCon.getVar(k); }); finalArgs.unshift(null); //unshift err=null to front this.env.results = finalArgs; this.env.flowEmitter.emit(EventManager.TYPES.EXEC_FLOW_COMPLETE, this.env); this.f.apply(null, finalArgs); } this.f = null; // prevent multiple calls }; return FinalCbTask; }); /*global define:true */ define('react/vcon',[], function () { var LAST_RESULTS_KEY = ':LAST_RESULTS'; function VContext() { } VContext.prototype.getLastResults = function () { return this.getVar(LAST_RESULTS_KEY); }; VContext.prototype.setLastResults = function (args) { this.setVar(LAST_RESULTS_KEY, args); }; VContext.prototype.getVar = function (name) { //name might be simple or obj.prop, also literals /*jshint regexp: false */ var vConValues = this.values; if (typeof(name) !== 'string') return name; // literal boolean or number name = name.trim(); // literal checks need to match what is in validate.js if (name === 'true') return true; if (name === 'false') return false; if (name === 'null') return null; if (/^-?[0-9]+$/.test(name)) return parseInt(name, 10); //int if (/^-?[0-9.]+$/.test(name)) return parseFloat(name); //float var m = /^("|')([^\1]*)\1$/.exec(name); //check for quoted string " or ' if (m) return m[2]; // if is quoted str, return inside of the quotes var nameAndProps = name.split('.'); return nameAndProps.reduce(function (accObj, prop) { if (accObj === undefined || accObj === null) return undefined; // prevent exception return accObj[prop]; }, vConValues); // vCon['foo']['bar'] }; /** Saves all the results from a task as a unit, also sets special variable :LAST_RESULTS which keeps an array of the last values which can be used for chaining and testing last results, etc. */ VContext.prototype.saveResults = function (paramArr, valuesArr) { // set values for params var self = this; paramArr.forEach(function (k, idx) { //save values to v context self.setVar(k, (valuesArr[idx] !== undefined) ? valuesArr[idx] : null); //upgrade any undefined to null }); this.setLastResults(valuesArr); }; VContext.prototype.setVar = function (name, value) { //name might be simple or obj.prop if (!name) return; // if name is undefined or null, then discard var vConValues = this.values; var nameAndProps = name.split('.'); var lastProp = nameAndProps.pop(); var obj = nameAndProps.reduce(function (accObj, prop) { var o = accObj[prop]; if (o === undefined || o === null) { // if doesn't exist create it o = accObj[prop] = { }; } return o; }, vConValues); // vCon['foo']['bar'] obj[lastProp] = value; }; /** Create Variable Context using arguments passed in. Ignore extra arguments passed in. Locals can be passed into seed the VContext otherwise empty {} will be used @param self used to pass 'this' context in */ VContext.create = function (args, inParams, locals, self) { var initValues = {}; if (self) initValues['this'] = self; if (locals) Object.keys(locals).forEach(function (k) { initValues[k] = locals[k]; }); // copy over keys var vContext = new VContext(); vContext.values = args.reduce(function (vcon, x, idx) { // create vCon start with input args var param = inParams[idx]; if (param) vcon[param] = (x !== undefined) ? x : null; // upgrade undefined to null return vcon; }, initValues); return vContext; }; return VContext; }); /*global define:true */ define('react/finalcb-first-task',['./sprintf', 'util', './status', './vcon', './event-manager'], function (sprintf, util, STATUS, VContext, EventManager) { var OUTTASK_A_REQ = 'ast.outTask.a should be an array of string param names'; function FinalCbFirstSuccTask(outTaskOptions) { var taskDef = outTaskOptions.taskDef; if (typeof(outTaskOptions.cbFunc) !== 'function') throw new Error('callback is not a function'); var self = this; for (var k in taskDef) { if (true) self[k] = taskDef[k]; // if to make jshint happy } this.f = outTaskOptions.cbFunc; this.tasks = outTaskOptions.tasks; this.vCon = outTaskOptions.vCon; this.retValue = outTaskOptions.retValue; this.env = outTaskOptions.env; } function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } FinalCbFirstSuccTask.validate = function (taskDef) { var errors = []; if (! (Array.isArray(taskDef.a) && taskDef.a.every(function (x) { return (typeof(x) === 'string'); }))) { errors.push(format_error(OUTTASK_A_REQ, taskDef)); } return errors; }; /** is ready to exit when any task comes back with non-null defined value */ FinalCbFirstSuccTask.prototype.isReady = function () { var lastres = this.vCon.getLastResults(); if (!lastres) return false; // no results yet return (lastres.some(function (v) { return (v !== undefined && v !== null); })); }; FinalCbFirstSuccTask.prototype.exec = function (err) { if (!this.f) return; //must have already been called if (err) { this.env.error = err; this.env.flowEmitter.emit(EventManager.TYPES.EXEC_FLOW_ERRORED, this.env); this.f.call(null, err); //call the final callback with the first error hit } else { // no error, call with args var vCon = this.vCon; var finalArgs = this.a.map(function (k) { return vCon.getVar(k); }); finalArgs.unshift(null); //unshift err=null to front this.env.results = finalArgs; this.env.flowEmitter.emit(EventManager.TYPES.EXEC_FLOW_COMPLETE, this.env); this.f.apply(null, finalArgs); } this.f = null; // prevent multiple calls }; return FinalCbFirstSuccTask; }); /*global define:true */ define('react/task',['util', './sprintf', 'ensure-array', './cb-task', './promise-task', './ret-task', './when-task', './finalcb-task', './finalcb-first-task', './status', './error', './vcon', './event-manager'], function (util, sprintf, array, CbTask, PromiseTask, RetTask, WhenTask, FinalCbTask, FinalCbFirstSuccTask, STATUS, error, VContext, EventManager) { var TASK_TYPES = { cb: CbTask, ret: RetTask, promise: PromiseTask, when: WhenTask }; var DEFAULT_TASK_NAME = 'task_%s'; // for unnamed tasks use task_idx, like task_0 function taskTypeKeys() { return Object.keys(TASK_TYPES); } var OUT_TASK_TYPES = { finalcb: FinalCbTask, //first task is the default if no type specified in taskDef finalcbFirst: FinalCbFirstSuccTask }; function outTaskTypeKeys() { return Object.keys(OUT_TASK_TYPES); } var LOCAL_FN_MISSING = 'function: %s not found in locals or input params - task[%s]'; var TASKDEF_IS_OBJECT = 'task must be an object'; var NO_TASKS_RUNNING_WONT_COMPLETE = 'no tasks running, flow will not complete, remaining tasks: %s'; var TASK_TYPE_SHOULD_MATCH = 'task.type should match one of ' + Object.keys(TASK_TYPES).join(', '); function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } /** guess the missing types from params. Augments in place but also returns taskDef. If not specified then is 'cb' */ function setMissingType(taskDef) { if (taskDef.type) return taskDef; //already set, return taskDef.type = 'cb'; return taskDef; } function setMissingOutTaskType(taskDef) { if (!taskDef.type) taskDef.type = Object.keys(OUT_TASK_TYPES)[0]; //use first outTask type as default } function ensureAfterArrStrings(taskDef) { // convert any fn to str, and make sure is array if (!taskDef.after) return; var afterArr = array(taskDef.after); // ensure is array, null becomes [] afterArr = afterArr.map(function (a) { return (typeof(a) === 'function') ? a.name : a; }); taskDef.after = afterArr; } /** @returns array of errors for taskDef, could be empty */ function validate(taskDef) { if (!taskDef || typeof(taskDef) !== 'object') { return [format_error(TASKDEF_IS_OBJECT, taskDef)]; } setMissingType(taskDef); ensureAfterArrStrings(taskDef); var errors = []; errors = errors.concat(validateTaskType(taskDef)); errors = errors.concat(validateTask(taskDef)); return errors; } function validateTaskType(taskDef) { var errors = []; if (!Object.keys(TASK_TYPES).some( function (type) { return (taskDef.type === type); })) { errors.push(format_error(TASK_TYPE_SHOULD_MATCH, taskDef)); } return errors; } function validateTask(taskDef) { var errors = []; var taskCons = TASK_TYPES[taskDef.type]; if (taskCons) { errors = errors.concat(taskCons.validate(taskDef)); } return errors; } function validateOutTask(taskDef) { var errors = []; setMissingOutTaskType(taskDef); var taskCons = OUT_TASK_TYPES[taskDef.type]; errors = errors.concat(taskCons.validate(taskDef)); return errors; } function validateLocalFunctions(inParams, taskDefs, locals) { var errors = []; function foo() { } //used to mock args as fns for validation check var mock_args = inParams.map(function (p) { return foo; }); //mock args with fns var vCon = VContext.create(mock_args, inParams, locals); var tasks = taskDefs.map(create); var tasksWFunctions = tasks.filter(function (t) { return (t.type !== 'when'); }); // non-when tasks need f tasksWFunctions.forEach(function (t, idx) { if (!t.functionExists(vCon)) { // error if function doesnt exist AND if (!t.isMethodCall()) errors.push(sprintf(LOCAL_FN_MISSING, t.f, idx)); // not method OR else { var obj = t.getMethodObj(vCon); if (obj && obj !== foo) { // (has parent but not our mock) errors.push(sprintf(LOCAL_FN_MISSING, t.f, idx)); } } } }); return errors; } function fName(fn) { if (typeof(fn) === 'function') { return fn.name; } return (fn) ? fn : ''; } /** Name tasks that are not already named. Prenamed task uniquness validation will be done in validate. This modifies the tasks with the new names. @returns map of names to tasks */ function nameTasks(tasks) { //name tasks that are not already named, validation done elsewhere, ret map var namesMap = tasks.reduce(function (map, t) { if (t.name) { map[t.name] = t; } return map; }, {}); tasks.forEach(function (t, idx) { if (!t.name) { //not already named var name = fName(t.f); if (!name) name = sprintf(DEFAULT_TASK_NAME, idx); if (!name || namesMap[name]) { name = sprintf('%s_%s', name, idx); //if empty or already used, postfix with _idx } t.name = name; namesMap[name] = t; } }); return namesMap; } function create(taskDef) { var TaskConstructor = TASK_TYPES[taskDef.type]; return new TaskConstructor(taskDef); } function createOutTask(taskDef, cbFunc, tasks, vCon, execOptions, env) { setMissingOutTaskType(taskDef); var outTaskOptions = { taskDef: taskDef, cbFunc: cbFunc, tasks: tasks, vCon: vCon, execOptions: execOptions, env: env, TaskConstructor: OUT_TASK_TYPES[taskDef.type] }; EventManager.global.emit(EventManager.TYPES.EXEC_OUTTASK_CREATE, outTaskOptions); // hook var TaskConstructor = outTaskOptions.TaskConstructor; // hook could have changed return new TaskConstructor(outTaskOptions); } function createErrorHandler(vCon, outTask) { return function handleError(task, err) { task.status = STATUS.ERRORED; task.error = err; outTask.env.currentTask = task; outTask.env.flowEmitter.emit(EventManager.TYPES.EXEC_TASK_ERRORED, task); var errWithMeta = error.augmentError(err, {task: task, vcon: vCon}); outTask.exec(errWithMeta); //call the final callback with the first error hit }; } function findTasksReady(vCon, tasks, tasksByName) { return tasks.filter(function (t) { return t.isReady(vCon, tasksByName); }); } function execTasks(tasksReady, vCon, handleError, contExec) { tasksReady.forEach(function (t) { t.status = STATUS.READY; }); //set ready first, no double exec tasksReady.forEach(function (t) { t.exec(vCon, handleError, contExec); }); } /** this will be called if there are no tasks found to run, and it will check if there are still tasks running or ready (which means they will be running shortly), in which case everything is fine. If no tasks are running then call handleError since this will never complete. */ function checkIfTasksRunning(vCon, tasks, handleError, env) { var tasksRunning = tasks.filter(function (t) { return (t.status === STATUS.RUNNING || t.status === STATUS.READY); }); if (!tasksRunning.length) { var remainingTasks = tasks.filter(function (t) { return (!t.status); }); var remainingTNames = remainingTasks.map(function (t) { return t.name; }); var errMsg = sprintf(NO_TASKS_RUNNING_WONT_COMPLETE, remainingTNames.join(', ')); var emptyTask = { env: env }; handleError(emptyTask, new Error(errMsg)); } } function findReadyAndExec(vCon, tasks, tasksByName, handleError, contExec, env) { var tasksReady = findTasksReady(vCon, tasks, tasksByName); if (!tasksReady.length) checkIfTasksRunning(vCon, tasks, handleError, env); // no tasks to run, check if ok execTasks(tasksReady, vCon, handleError, contExec); } function serializeTasks(tasks) { // conveniently set after for each task idx > 0 nameTasks(tasks); tasks.forEach(function (t, idx, arr) { if (idx !== 0) t.after = [arr[idx - 1].name]; }); return tasks; } return { serializeTasks: serializeTasks, TASK_TYPES: TASK_TYPES, taskTypeKeys: taskTypeKeys, OUT_TASK_TYPES: OUT_TASK_TYPES, outTaskTypeKeys: outTaskTypeKeys, setMissingType: setMissingType, validate: validate, validateOutTask: validateOutTask, validateLocalFunctions: validateLocalFunctions, nameTasks: nameTasks, create: create, createOutTask: createOutTask, createErrorHandler: createErrorHandler, findReadyAndExec: findReadyAndExec }; }); /*global define:true */ define('react/validate',['util', './sprintf', 'ensure-array', './task'], function (util, sprintf, array, taskUtil) { /*jshint latedef:false */ var AST_IS_OBJECT = 'ast must be an object with inParams, tasks, and outTask'; var INPARAMS_ARR_STR = 'ast.inParams must be an array of strings'; var TASKS_ARR = 'ast.tasks must be an array of tasks'; var NAMES_UNIQUE = 'ast.tasks that specify name need to be unique, duplicate:'; var LOCALS_NOTNULL = 'ast.locals should not be null'; var DUP_OUTPUTS = 'multiple tasks output the same param, must be unique. param'; var MISSING_INPUTS = 'missing or mispelled variable referenced in flow definition: %s'; // match any of our literals true, false, int, float, quoted strings, or is property (has dot), match vcon.js var LITERAL_OR_PROP_RE = /^(true|false|this|null|\-?[0-9\.]+)$|'|"|\./i; function format_error(errmsg, obj) { return sprintf('%s - %s', errmsg, util.inspect(obj)); } /** true if is a literal name */ function isLiteralOrProp(name) { // need to match what is in vcon.js, TODO consolidate? return LITERAL_OR_PROP_RE.test(name); } /** validate the AST return Errors @example var validate = require('./validate'); var errors = validate(ast); @returns array of errors, could be empty */ function validate(ast) { if (!ast || !ast.inParams || !ast.tasks || !ast.outTask) return [AST_IS_OBJECT]; var errors = []; errors = errors.concat(validateInParams(ast.inParams)); errors = errors.concat(validateTasks(ast.tasks)); errors = errors.concat(validateTaskNamesUnique(ast.tasks)); errors = errors.concat(taskUtil.validateOutTask(ast.outTask)); errors = errors.concat(validateLocals(ast.locals)); if (errors.length === 0) { // if no errors do additional validation if (ast.outTask.type !== 'finalcbFirst') errors = errors.concat(validateOuputsUnique(ast.tasks)); errors = errors.concat(taskUtil.validateLocalFunctions(ast.inParams, ast.tasks, ast.locals)); errors = errors.concat(validateNoMissingNames(ast)); } return errors; } /** @returns array of errors, could be empty */ function validateInParams(inParams) { if (!Array.isArray(inParams) || !inParams.every(function (x) { return (typeof(x) === 'string'); })) { return [INPARAMS_ARR_STR]; } return []; } /** @returns array of errors, could be empty */ function validateTasks(tasks) { if (!Array.isArray(tasks)) return [TASKS_ARR]; var errors = []; tasks.forEach(function (t) { errors = errors.concat(taskUtil.validate(t)); }); return errors; } function validateTaskNamesUnique(tasks) { if (!Array.isArray(tasks)) return []; var errors = []; var namedTasks = tasks.filter(function (t) { return (t.name); }); var names = namedTasks.map(function (t) { return t.name; }); names.reduce(function (accum, name) { if (accum[name]) errors.push(sprintf('%s %s', NAMES_UNIQUE, name)); else accum[name] = true; return accum; }, {}); return errors; } function validateLocals(locals) { var errors = []; if (locals === null) errors.push(LOCALS_NOTNULL); return errors; } function getOutputParams(taskDef) { return array(taskDef.out); //ensure array } function validateOuputsUnique(taskDefs) { var errors = []; taskDefs.reduce(function (accum, t) { getOutputParams(t).forEach(function (param) { if (accum[param] !== undefined) errors.push(sprintf('%s: %s', DUP_OUTPUTS, param)); else accum[param] = true; }); return accum; }, {}); return errors; } /** validate there are no missing or mispelled param names in any task inputs or the final task output @return array of errors, or empty array if none */ function validateNoMissingNames(ast) { var errors = []; var names = {}; if (ast.locals) { names = Object.keys(ast.locals).reduce(function (accum, k) { // start with locals accum[k] = true; return accum; }, names); } ast.inParams.reduce(function (accum, p) { // add input params accum[p] = true; return accum; }, names); ast.tasks.reduce(function (accum, t) { // add task outputs return t.out.reduce(function (innerAccum, p) { innerAccum[p] = true; return innerAccum; }, accum); }, names); // now we have all possible provided vars, check task inputs are accounted for ast.tasks.reduce(function (accum, t) { // for all tasks return t.a.reduce(function (innerAccum, p) { // for all in params, except property if (!isLiteralOrProp(p) && !names[p]) innerAccum.push(sprintf(MISSING_INPUTS, p)); // add error if missing return innerAccum; }, accum); }, errors); // now check the final task outputs ast.outTask.a.reduce(function (accum, p) { // for final task out params if (!isLiteralOrProp(p) && !names[p]) accum.push(sprintf(MISSING_INPUTS, p)); // add error if missing return accum; }, errors); return errors; } return validate; }); /*global define:true */ define('react/input-parser',['./event-manager'], function (EventManager) { var defaultExecOptions = { reactExecOptions: true, outputStyle: 'cb', }; var OUTPUT_STYLES = { CALLBACK: 'cb', NONE: 'none' }; function isExecOptions(x) { return (x && x.reactExecOptions); } function execOptionsFilter(x) { return isExecOptions(x); } function nonExecOptionsFilter(x) { return !isExecOptions(x); } function mergeExecOptions(accum, options) { Object.keys(options).forEach(function (k) { accum[k] = options[k]; }); return accum; } function splitArgs(args, inParams, style) { var result = { }; result.args = inParams.map(function (p) { return args.shift(); }); // take args for input params first if (style === OUTPUT_STYLES.CALLBACK && args.length) result.cb = args.shift(); // next take the cb result.extra = args; // these remaining were after the callback return result; } function inputParser(inputArgs, ast) { var parsedInput = { }; var execOptionsArr = inputArgs.filter(execOptionsFilter); execOptionsArr.unshift(defaultExecOptions); parsedInput.options = execOptionsArr.reduce(mergeExecOptions, {}); var args = inputArgs.filter(nonExecOptionsFilter); var splitResult = splitArgs(args, ast.inParams, parsedInput.options.outputStyle); parsedInput.args = splitResult.args; parsedInput.cb = splitResult.cb; if (splitResult.outputStyle) parsedInput.options.outputStyle = splitResult.outputStyle; if (splitResult.extra) parsedInput.extraArgs = splitResult.extra; EventManager.global.emit(EventManager.TYPES.EXEC_INPUT_PREPROCESS, parsedInput); // hook return parsedInput; } inputParser.defaultExecOptions = defaultExecOptions; return inputParser; }); /*global define:true */ define('react/id',[], function () { var startingId = 0; function createUniqueId() { startingId += 1; if (startingId === Number.MAX_VALUE) startingId = 0; // if hits this start over //TODO need something better? return startingId; } return { createUniqueId: createUniqueId }; }); /*global define:true */ define('react/core',['./eventemitter', './error', './validate', './task', './status', './vcon', './event-manager', './input-parser', './id', './sprintf'], function (EventEmitter, error, validate, taskUtil, STATUS, VContext, EventManager, inputParser, idGenerator, sprintf) { var reactOptions = { stackTraceLimitMin: 30 }; var reactEmitter = EventManager.global; // the top emitter /** merge global react options with parsed options */ function mergeOptions(parsedOptions) { return Object.keys(reactOptions).reduce(function (accum, k) { if (!accum[k]) accum[k] = reactOptions[k]; return accum; }, parsedOptions); } /** generate a flow name when one is not provided */ function generateFlowName() { return sprintf('flow_%s', idGenerator.createUniqueId()); } /** Creates react function which the AST can be manipulated and then is ready to be executed. Can be used directly or a DSL can wrap this to provide the AST. @example var react = require('react'); var fn = react(); var valid2 = fn.setAndValidateAST({ name: 'optionalName', inParams: ['a', 'b'], tasks: [ { type: 'cb', f: multiply, a: ['a', 'b'], out: ['c'] } ], outTask: { a: ['c'] } }); console.log(fn.ast); // view fn(123, 456, cb); */ function reactFactory() { if (arguments.length) throw new Error('react() takes no args, check API'); error.ensureStackTraceLimitSet(reactOptions.stackTraceLimitMin); var flowEmitter = EventManager.create(); flowEmitter.parent = reactEmitter; var ast = { name: undefined, inParams: [], tasks: [], outTask: {}, locals: {} }; function setAndValidateAST(newAST) { //set AST then validate, ret error[] Object.keys(newAST).forEach(function (k) { ast[k] = newAST[k]; }); // copy all properties var errors = validate(ast); if (!errors.length) { if (!ast.name) ast.name = generateFlowName(); taskUtil.nameTasks(ast.tasks); //run this so names can be checked in ast } if (Object.freeze) { //lets freeze the AST so plugin writers don't accidentally manip the ast Object.keys(newAST).forEach(function (k) { if (typeof(newAST[k]) === 'object') Object.freeze(newAST[k]); }); Object.freeze(newAST); } flowEmitter.emit(EventManager.TYPES.AST_DEFINED, ast); return errors; } function exec(arg1, arg2, argN, cb) { // called to execute the flow /*jshint validthis: true */ var args = Array.prototype.slice.call(arguments); var env = { execId: idGenerator.createUniqueId(), args: args, ast: ast, flowEmitter: flowEmitter }; env.name = ast.name || env.execId; flowEmitter.emit(EventManager.TYPES.EXEC_FLOW_START, env); // hook var parsedInput = inputParser(args, ast); var vCon = VContext.create(parsedInput.args, ast.inParams, ast.locals, this); // create var ctx with in args & locals env.parsedInput = parsedInput; env.options = mergeOptions(parsedInput.options); env.vCon = vCon; env.taskDefs = ast.tasks.slice(); // create copy env.outTaskDef = Object.create(ast.outTask); // create copy reactEmitter.emit(EventManager.TYPES.EXEC_TASKS_PRECREATE, env); // hook var tasks = env.taskDefs.map(taskUtil.create); var tasksByName = taskUtil.nameTasks(tasks); // map names to working tasks var outTask = taskUtil.createOutTask(env.outTaskDef, parsedInput.cb, tasks, vCon, env.options, env); var handleError = taskUtil.createErrorHandler(vCon, outTask); function contExec() { if (!outTask.f) { return; } //stop execution, we already hit an error, f was cleared if (outTask.isReady()) return outTask.exec(); // all tasks done, exec cb, return taskUtil.findReadyAndExec(vCon, tasks, tasksByName, handleError, contExec, env); //exec tasks that ready to run } tasks.forEach(function (t) { t.id = idGenerator.createUniqueId(); t.env = env; if (t.prepare) t.prepare(handleError, vCon, contExec, flowEmitter); }); // create callbacks contExec(); // start things off return outTask.retValue; // could return promise } var reactFn = exec; // make the exec() the function returned reactFn.ast = ast; // put AST hanging off the fn so it can be inspected reactFn.setAndValidateAST = setAndValidateAST; // call to set AST and then validate reactFn.events = flowEmitter; // used to listen to execution events for this flow return reactFn; } reactFactory.options = reactOptions; // global react options reactFactory.events = reactEmitter; // global react emitter return reactFactory; // module returns reactFactory to create a react fn }); /*global define:true */ define('react/parse',['./sprintf'], function (sprintf) { function splitTrimFilterArgs(commaSepArgs) { //parse 'one, two' into ['one', 'two'] if (!commaSepArgs) return []; return commaSepArgs.split(',') //split on commas .map(function (s) { return s.trim(); }) //trim .filter(function (s) { return (s); }); //filter out empty strings } /** @param patternFn regex + fn or splitStr + fn */ function parseReduce(accum, patternFn) { if (typeof(accum) !== 'string') return accum; // already matched var m = (patternFn.regex) ? patternFn.regex.exec(accum) : accum.split(patternFn.splitStr); if (m) return patternFn.fn(m, accum); // pass in matches and origStr, return result obj return accum; // no match, return str, will try next matcher } function parseStr(str, parseMatchers, errStr) { var result = parseMatchers.reduce(parseReduce, str); if (typeof(result) !== 'string') { // matched return result; } else { // no match throw new Error(sprintf(errStr, str)); } } return { splitTrimFilterArgs: splitTrimFilterArgs, parseStr: parseStr }; }); /*global define:true */ define('react/dsl',['./sprintf', './core', './parse', './task'], function (sprintf, core, parse, taskUtil) { /*jshint regexp: false */ var MISSING_NAME = 'first flow parameter should be the flow name, but found in/out def: %s'; var INOUT_PARAMS_NO_MATCH = 'params in wrong format, wanted "foo, bar, cb -> err, baz" - found: %s'; var MISSING_ERR = 'callback specified, but first out param was not "err", use for clarity. Found in/out def: %s'; var MISSING_CB = 'found err param, but cb/callback is not specified, is this cb-style async or sync function? Found in/out def: %s'; var EXTRA_TASKARG = 'extra unmatched task arg: %s'; var INOUT_RE = /\->/; // used to detect missing name, in/out as first arg var CB_NAMES_RE = /^cb|callback$/i; //cb, Cb, CB, callback, Callback var ERR_NAMES_RE = /^err$/i; // err, ERR, Err, ... function filterOutTrailingCbParam(args) { // if has trailing cb | callback param, filter it out if (args.length && args[args.length - 1].match(CB_NAMES_RE)) args.pop(); return args; } function filterOutLeadingErrParam(args) { // if leading err param, filter it out if (args.length && args[0].match(ERR_NAMES_RE)) args.shift(); return args; } var inOutDefParse = { splitStr: '->', fn: function (m, origStr) { var inParams = parse.splitTrimFilterArgs(m[0]); var lastParam = inParams[inParams.length - 1]; var type = (lastParam && CB_NAMES_RE.test(lastParam)) ? 'cb' : 'ret'; var outParams = parse.splitTrimFilterArgs(m[1]); var firstOutParam = outParams[0]; if (type === 'cb' && (!firstOutParam || !ERR_NAMES_RE.test(firstOutParam))) { throw new Error(sprintf(MISSING_ERR, origStr)); // found cb, but no err param } else if (type === 'ret' && firstOutParam && ERR_NAMES_RE.test(firstOutParam)) { throw new Error(sprintf(MISSING_CB, origStr)); // found err but not cb param } return { type: type, inDef: filterOutTrailingCbParam(inParams), outDef: filterOutLeadingErrParam(outParams) }; } }; function parseInOutParams(str) { var objDef = parse.parseStr(str, [inOutDefParse], INOUT_PARAMS_NO_MATCH); objDef.inDef = filterOutTrailingCbParam(objDef.inDef); return objDef; } function parseTasks(arr) { var tasks = []; var fn, obj, result; while (arr.length >= 2) { obj = {}; fn = arr.shift(); result = parseInOutParams(arr.shift()); if (typeof(arr[0]) === 'object') obj = arr.shift(); // has options, use as obj obj.f = fn; obj.a = result.inDef; var type = result.type; obj.out = result.outDef; obj.type = type; tasks.push(obj); } if (arr.length) throw new Error(sprintf(EXTRA_TASKARG, arr[0])); return tasks; } /** Parse the variable arguments into in/out params, options, tasks */ function parseVargs(vargs) { var inOutParamStr = vargs.shift() || ''; // if next arg is object, shift it off as options var options = (vargs.length && typeof(vargs[0]) === 'object') ? vargs.shift() : { }; var taskDefArr = vargs; // rest are for the tasks var defObj = { inOutParamStr: inOutParamStr, taskDefArr: taskDefArr, options: options }; return defObj; } function dslDefine(name, arg1, arg2, argN) { var reactFn = core(); if (name && INOUT_RE.test(name)) throw new Error(sprintf(MISSING_NAME, name)); var defObj = parseVargs(Array.prototype.slice.call(arguments, 1)); // name, already used var inOutDef = parseInOutParams(defObj.inOutParamStr); var ast = { name: name, inParams: inOutDef.inDef, tasks: parseTasks(defObj.taskDefArr), outTask: { a: inOutDef.outDef } }; if (defObj.options) Object.keys(defObj.options).forEach(function (k) { ast[k] = defObj.options[k]; }); var errors = reactFn.setAndValidateAST(ast); if (errors.length) { var errorStr = errors.join('\n'); throw new Error(errorStr); } return reactFn; } function selectFirst(name, arg1, arg2, argN) { var reactFn = core(); var defObj = parseVargs(Array.prototype.slice.call(arguments, 1)); // name, already used var inOutDef = parseInOutParams(defObj.inOutParamStr); var tasks = taskUtil.serializeTasks(parseTasks(defObj.taskDefArr)); var ast = { name: name, inParams: inOutDef.inDef, tasks: tasks, outTask: { type: 'finalcbFirst', a: inOutDef.outDef }, }; if (defObj.options) Object.keys(defObj.options).forEach(function (k) { ast[k] = defObj.options[k]; }); var errors = reactFn.setAndValidateAST(ast); if (errors.length) { var errorStr = errors.join('\n'); throw new Error(errorStr); } return reactFn; } dslDefine.selectFirst = selectFirst; return dslDefine; }); /*global define:true */ define('react/track-tasks',[], function () { /** Track the tasks, start, complete, args, results, elapsed time Emits events that can be monitored - track start and complete - record args each task was called with - record results at completion - record start, end, and calc elapsed time - emits flow.begin with flowEnv - emits task.begin with task - emits task.complete with task - emits flow complete with flowEnv - emits flow errored with flowEnv @example var react = require('react'); react.trackTasks(); // enable task and flow tracking */ var trackingTasks = false; function trackTasks(react) { if (trackingTasks) return; // already tracking trackingTasks = true; react.events.on(react.events.TYPES.EXEC_FLOW_START, function (env) { env.startTime = Date.now(); env.flowEmitter.emit(react.events.TYPES.FLOW_BEGIN, env); //fire public ev }); react.events.on(react.events.TYPES.EXEC_TASK_START, function (task) { task.startTime = Date.now(); task.env.flowEmitter.emit(react.events.TYPES.TASK_BEGIN, task); //fire public ev }); react.events.on(react.events.TYPES.EXEC_TASK_COMPLETE, function (task) { task.endTime = Date.now(); task.elapsedTime = task.endTime - task.startTime; task.env.flowEmitter.emit(react.events.TYPES.TASK_COMPLETE, task); // fire public ev }); react.events.on(react.events.TYPES.EXEC_TASK_ERRORED, function (task) { task.endTime = Date.now(); task.elapsedTime = task.endTime - task.startTime; task.env.flowEmitter.emit(react.events.TYPES.TASK_ERRORED, task); // fire public ev }); react.events.on(react.events.TYPES.EXEC_FLOW_COMPLETE, function (env) { env.endTime = Date.now(); env.elapsedTime = env.endTime - env.startTime; env.flowEmitter.emit(react.events.TYPES.FLOW_COMPLETE, env); //fire public ev }); react.events.on(react.events.TYPES.EXEC_FLOW_ERRORED, function (env) { env.endTime = Date.now(); env.elapsedTime = env.endTime - env.startTime; env.flowEmitter.emit(react.events.TYPES.FLOW_ERRORED, env); //fire public ev }); } return trackTasks; }); /*global define:true */ define('react/log-events',['util'], function (util) { // TODO replace util.inspect with something portable to browser var logEventsMod = { }; /** Log events to console.error @example var react = require('react'); react.logEvents(); // log all task and flow events on all react functions react.logEvents('task.*'); // log all task events on all react functions react.logEvents(flowFn); // log all task and flow events on flowFn only react.logEvents(flowFn, 'flow.*'); // log all flow events on flowFn only */ var ALL_FLOW_EVENTS = 'flow.*'; var ALL_TASK_EVENTS = 'task.*'; var FLOW_RE = /^flow\./; function flowLog(obj) { /*jshint validthis: true */ var time = new Date(); time.setTime(obj.startTime); var argsNoCb = obj.args.filter(function (a) { return (typeof(a) !== 'function'); }); var eventTimeStr = time.toISOString(); if (this.event === 'flow.complete') { var env = obj; console.error('%s: %s \tmsecs: %s \n\targs: %s \n\tresults: %s\n', this.event, env.name, env.elapsedTime, util.inspect(argsNoCb), util.inspect(env.results)); } else { var name = obj.name; var args = obj.args; console.error('%s: %s \n\targs: %s\n', this.event, name, util.inspect(argsNoCb)); } } function taskLog(obj) { /*jshint validthis: true */ var time = new Date(); time.setTime(obj.startTime); var argsNoCb = obj.args.filter(function (a) { return (typeof(a) !== 'function'); }); var eventTimeStr = time.toISOString(); if (this.event === 'task.complete') { var task = obj; console.error('%s: %s:%s \tmsecs: %s \n\targs: %s \n\tresults: %s\n', this.event, task.env.name, task.name, task.elapsedTime, util.inspect(argsNoCb), util.inspect(task.results)); } else { var name = obj.name; var args = obj.args; console.error('%s: %s:%s \n\targs: %s\n', this.event, obj.env.name, obj.name, util.inspect(argsNoCb)); } } /** Log flow and task events for a flowFn or all of react. If called multiple times, remove previous listener (if any) before adding. @example var react = require('react'); react.logEvents(flowFn, eventWildcard); //log events on flowfn matching wildcard @param flowFn Flow function or global react object @param eventWildcard wildcarded event type, if not provided use flow.* and task.* */ function logEvents(flowFn, eventWildcard) { if (!flowFn) throw new Error('flowFn is required'); if (!flowFn.events._loggingEvents) flowFn.events._loggingEvents = []; if (eventWildcard === false) { // turn off logging flowFn.events._loggingEvents.forEach(function (evt) { flowFn.events.removeAllListeners(evt); }); flowFn.events._loggingEvents.length = 0; // clear } else if (eventWildcard && eventWildcard !== '*') { var logFn = (FLOW_RE.test(eventWildcard)) ? flowLog : taskLog; flowFn.events.removeListener(eventWildcard, logFn); flowFn.events.on(eventWildcard, logFn); flowFn.events._loggingEvents.push(eventWildcard); } else { // none provided, use flow.* and task.* //output events as tasks start and complete flowFn.events.removeListener(ALL_FLOW_EVENTS, flowLog); flowFn.events.on(ALL_FLOW_EVENTS, flowLog); flowFn.events._loggingEvents.push(ALL_FLOW_EVENTS); flowFn.events.removeListener(ALL_TASK_EVENTS, taskLog); flowFn.events.on(ALL_TASK_EVENTS, taskLog); flowFn.events._loggingEvents.push(ALL_TASK_EVENTS); } } logEventsMod.logEvents = logEvents; return logEventsMod; }); /*global define:true */ define('react/promise-resolve',[], function () { /** Auto resolve promises passed in as arguments to the flow - Detects promises by checking for .then() - Create promise name for param (param__promise) - moves existing vCon promise into the param__promise - creates WhenTask which resolves param__promise into param */ var PROMISE_SUFFIX = '__promise'; // added to param names that are promises var resolvingPromises = false; function resolvePromises(react) { if (resolvingPromises) return; // already resolving resolvingPromises = true; react.events.on(react.events.TYPES.EXEC_TASKS_PRECREATE, function (env) { var vConValues = env.vCon.values; var promiseParams = env.ast.inParams.filter(function (p) { var value = vConValues[p]; return (value && typeof(value.then) === 'function'); }); promiseParams.forEach(function (p) { var promiseName = p + PROMISE_SUFFIX; vConValues[promiseName] = vConValues[p]; vConValues[p] = undefined; env.taskDefs.push({ type: 'when', a: [promiseName], out: [p] }); }); }); } return resolvePromises; }); /*global define:true */ define('react/event-collector',[], function () { /** create an instance of the event collector */ function instantiate(react) { react.trackTasks(); // enable task tracking var AST_EVENTS_RE = /^ast\./; var TASK_EVENTS_RE = /^task\./; var FLOW_EVENTS_RE = /^flow\./; /** Accumulator to make it easy to capture events @example var react = require('react'); var collector = react.createEventCollector(); collector.capture(); // capture all flow and task events for all react flows collector.capture('flow.*'); // capture all flow events for all react flows collector.capture(flowFn, 'task.*'); // capture task events on a flow collector.capture(flowFn, 'flow.*'); // add capture flow events on a flow var events = collector.list(); // retrieve the list of events collector.clear(); // clear the list of events; */ function EventCollector() { this.events = []; } /** register listener to capture events for a specific flow @param flowFn the react flow function or can pass global react @param eventId event id or wildcarded id */ EventCollector.prototype.capture = function (flowFn, eventId) { /*jshint validthis: true */ if (!eventId && typeof(flowFn) === 'string') { // only eventId provided eventId = flowFn; flowFn = react; // global react } else if (!flowFn) flowFn = react; // global react if (!eventId) eventId = '*'; // default to all var emitter = flowFn.events; var self = this; function accumEvents(obj) { var eventObject = { event: this.event, time: Date.now() }; if (FLOW_EVENTS_RE.test(this.event)) { eventObject.env = obj; } else if (TASK_EVENTS_RE.test(this.event)) { eventObject.task = obj; } else if (AST_EVENTS_RE.test(this.event)) { eventObject.ast = obj; } self.events.push(eventObject); } emitter.on(eventId, accumEvents); }; EventCollector.prototype.list = function () { return this.events; }; EventCollector.prototype.clear = function () { this.events = []; // clear }; return new EventCollector(); } return instantiate; // return the factory for creating EventCollector }); /*global define:true */ define('react/react',['./core', './dsl', './track-tasks', './log-events', './promise-resolve', './event-collector'], function (core, dsl, trackTasksFn, logEventsMod, resolvePromisesFn, eventCollectorFactory) { var react = dsl; // core + default dsl /** Enable detection of promises and resolution */ function resolvePromises() { resolvePromisesFn(react); } /** Enable tracking of tasks and flow execution, emitting events and tracking start, end, elapsed time */ function trackTasks() { trackTasksFn(react); } /** If called, load the built-in plugin for log events and invoke @param flowFn [function] if not provided uses global react @param eventWildcard [string] pattern to log events for */ function logEvents(flowFn, eventWildcard) { if (typeof(flowFn) !== 'function') { // only wildcard provided eventWildcard = flowFn; flowFn = undefined; } if (!flowFn) flowFn = react; // use global trackTasks(); return logEventsMod.logEvents(flowFn, eventWildcard); } /** Instantiate an event collector */ function createEventCollector() { return eventCollectorFactory(react); } react.options = core.options; // global react options react.events = core.events; // global react event emitter react.logEvents = logEvents; // enable event logging react.resolvePromises = resolvePromises; // enable promise resolution react.trackTasks = trackTasks; // enable tracking of tasks react.createEventCollector = createEventCollector; // create instance of EventCollector return react; }); define('react', ['react/react'], function (main) { return main; });
docs/app/Examples/collections/Grid/Variations/GridExamplePaddedVertically.js
koenvg/Semantic-UI-React
import React from 'react' import { Grid, Image } from 'semantic-ui-react' const GridExamplePaddedVertically = () => ( <div> <p>The following grid has vertical gutters.</p> <Grid columns={2} padded='vertically'> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> <Grid.Column> <Image src='http://semantic-ui.com/images/wireframe/paragraph.png' /> </Grid.Column> </Grid> </div> ) export default GridExamplePaddedVertically
src/app.js
howardjing/chess-calculator
// @flow import React, { Component } from 'react'; import Chess from 'chess.js'; import styled from 'styled-components'; import URLSearchParams from 'url-search-params'; import Game from './game'; import GameLoader, { loadGame } from './game-loader'; // http://www.mark-weeks.com/aboutcom/aa02j12.htm const GAME_OF_CENTURY = '1.Nf3 Nf6 2.c4 g6 3.Nc3 Bg7 4.d4 O-O 5.Bf4 d5 6.Qb3 dxc4 7.Qxc4 c6 8.e4 Nbd7 9.Rd1 Nb6 10.Qc5 Bg4 11.Bg5 Na4 12.Qa3 Nxc3 13.bxc3 Nxe4 14.Bxe7 Qb6 15.Bc4 Nxc3 16.Bc5 Rfe8+ 17.Kf1 Be6 18.Bxb6 Bxc4+ 19.Kg1 Ne2+ 20.Kf1 Nxd4+ 21.Kg1 Ne2+ 22.Kf1 Nc3+ 23.Kg1 axb6 24.Qb4 Ra4 25.Qxb6 Nxd1 26.h3 Rxa2 27.Kh2 Nxf2 28.Re1 Rxe1 29.Qd8+ Bf8 30.Nxe1 Bd5 31.Nf3 Ne4 32.Qb8 b5 33.h4 h5 34.Ne5 Kg7 35.Kg1 Bc5+ 36.Kf1 Ng3+ 37.Ke1 Bb4+ 38.Kd1 Bb3+ 39.Kc1 Ne2+ 40.Kb1 Nc3+ 41.Kc1 Rc2+ 0-1'; const INITIAL_CHESS = new Chess(); INITIAL_CHESS.load_pgn(GAME_OF_CENTURY); type State = { chess: Chess, }; class App extends Component<{}, State> { state = { chess: INITIAL_CHESS, }; componentWillMount() { const search = new URLSearchParams(window.location.search); const game = search.get('game'); if (game) { const chess = loadGame(game); if (chess) { this.handleNewGame(chess); } } } handleNewGame = (chess: Chess) => { this.setState(() => ({ chess, })); } render() { const { chess } = this.state; return ( <Wrapper> <div> <Game chess={chess} /> <GameLoader onNewGame={this.handleNewGame} /> </div> </Wrapper> ); } }; const Wrapper = styled.div` display: flex; justify-content: center; padding-top: 20px; `; export default App;
node_modules/react-bootstrap/es/Row.js
geng890518/editor-ui
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 elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var Row = function (_React$Component) { _inherits(Row, _React$Component); function Row() { _classCallCheck(this, Row); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } Row.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return Row; }(React.Component); Row.propTypes = propTypes; Row.defaultProps = defaultProps; export default bsClass('row', Row);
client/main.js
morepath/morepath_cerebral_todomvc
import 'todomvc-common/base.css' import 'todomvc-app-css/index.css' import './styles.css' import 'file?name=[name].[ext]!./index.html' import React from 'react' import ReactDOM from 'react-dom' import {Container} from 'cerebral-view-react' import controller from './controller' import App from './components/App' ReactDOM.render( <Container controller={controller}> <App /> </Container>, document.querySelector('#app'))
src/components/pub-key-list/pub-key-list-item.js
dylanlott/bridge-gui
import React from 'react'; const PubKeyListItem = (props) => { return ( <tr> <td> <input type = "checkbox" onClick = {(e) => props.itemSelectAction(props.rowItem)} checked = {props.isSelected}/> </td> <td onClick = {(e) => {e.preventDefault(); props.editRowItemAction(props.rowItem)}}> <a href="#noop"> {props.rowItem} </a> <span className="glyphicon glyphicon-pencil pull-right"></span> </td> </tr> ); }; export default PubKeyListItem;
src/components/Field/TimePicker/TimePicker.js
thomasthiebaud/lundalogik
import React from 'react' import PropTypes from 'prop-types' import moment from 'moment' import { TimePicker, Form } from 'antd' import { formLayout } from 'components/Field/layout' const format = 'HH:mm' function disableMinutes(keep = []) { const disabledMinutes = [] for (let i = 0; i < 60; i += 1) { if (!keep.includes(i)) { disabledMinutes.push(i) } } return disabledMinutes } class TimePickerInput extends React.Component { handleChange(values) { this.props.input.onChange(values) } render() { return ( <Form.Item {...formLayout} validateStatus={this.props.error ? 'error' : ''} help={this.props.error} label={this.props.placeholder} > <TimePicker value={this.props.input.value} defaultValue={moment('12:00', format)} format={format} onChange={value => this.handleChange(value)} hideDisabledOptions disabledMinutes={() => disableMinutes([0, 30])} /> </Form.Item> ) } } TimePickerInput.propTypes = { error: PropTypes.string.isRequired, placeholder: PropTypes.string.isRequired, input: PropTypes.shape({ onChange: PropTypes.func.isRequired, value: PropTypes.object.isRequired, }).isRequired, } export default TimePickerInput
fields/types/html/HtmlField.js
naustudio/keystone
import Field from '../Field'; import React from 'react'; import tinymce from 'tinymce'; import { FormInput } from '../../../admin/client/App/elemental'; import evalDependsOn from '../../utils/evalDependsOn'; /** * TODO: * - Remove dependency on underscore */ var lastId = 0; function getId () { return 'keystone-html-' + lastId++; } // Workaround for #2834 found here https://github.com/tinymce/tinymce/issues/794#issuecomment-203701329 function removeTinyMCEInstance (editor) { var oldLength = tinymce.editors.length; tinymce.remove(editor); if (oldLength === tinymce.editors.length) { tinymce.editors.remove(editor); } } module.exports = Field.create({ displayName: 'HtmlField', statics: { type: 'Html', }, getInitialState () { return { id: getId(), isFocused: false, wysiwygActive: false, }; }, initWysiwyg () { if (!this.props.wysiwyg) return; var self = this; var opts = this.getOptions(); opts.setup = function (editor) { self.editor = editor; editor.on('change', self.valueChanged); editor.on('focus', self.focusChanged.bind(self, true)); editor.on('blur', self.focusChanged.bind(self, false)); }; this._currentValue = this.props.value; tinymce.init(opts); if (evalDependsOn(this.props.dependsOn, this.props.values)) { this.setState({ wysiwygActive: true }); } }, removeWysiwyg (state) { removeTinyMCEInstance(tinymce.get(state.id)); this.setState({ wysiwygActive: false }); }, componentDidUpdate (prevProps, prevState) { if (prevState.isCollapsed && !this.state.isCollapsed) { this.initWysiwyg(); } if (this.props.wysiwyg) { if (evalDependsOn(this.props.dependsOn, this.props.values)) { if (!this.state.wysiwygActive) { this.initWysiwyg(); } } else if (this.state.wysiwygActive) { this.removeWysiwyg(prevState); } } }, componentDidMount () { this.initWysiwyg(); }, componentWillReceiveProps (nextProps) { if (this.editor && this._currentValue !== nextProps.value) { this.editor.setContent(nextProps.value); } }, focusChanged (focused) { this.setState({ isFocused: focused, }); }, valueChanged (event) { var content; if (this.editor) { content = this.editor.getContent(); } else { content = event.target.value; } this._currentValue = content; this.props.onChange({ path: this.props.path, value: content, }); }, getOptions () { var plugins = ['code', 'link']; var options = Object.assign( {}, Keystone.wysiwyg.options, this.props.wysiwyg ); var toolbar = options.overrideToolbar ? '' : 'bold italic | alignleft aligncenter alignright | bullist numlist | outdent indent | removeformat | link '; var i; if (options.enableImages) { plugins.push('image'); toolbar += ' | image'; } if (options.enableCloudinaryUploads || options.enableS3Uploads) { plugins.push('uploadimage'); toolbar += options.enableImages ? ' uploadimage' : ' | uploadimage'; } if (options.additionalButtons) { var additionalButtons = options.additionalButtons.split(','); for (i = 0; i < additionalButtons.length; i++) { toolbar += (' | ' + additionalButtons[i]); } } if (options.additionalPlugins) { var additionalPlugins = options.additionalPlugins.split(','); for (i = 0; i < additionalPlugins.length; i++) { plugins.push(additionalPlugins[i]); } } if (options.importcss) { plugins.push('importcss'); var importcssOptions = { content_css: options.importcss, importcss_append: true, importcss_merge_classes: true, }; Object.assign(options.additionalOptions, importcssOptions); } if (!options.overrideToolbar) { toolbar += ' | code'; } var opts = { selector: '#' + this.state.id, toolbar: toolbar, plugins: plugins, menubar: options.menubar || false, skin: options.skin || 'keystone', }; if (this.shouldRenderField()) { opts.uploadimage_form_url = options.enableS3Uploads ? Keystone.adminPath + '/api/s3/upload' : Keystone.adminPath + '/api/cloudinary/upload'; } else { Object.assign(opts, { mode: 'textareas', readonly: true, menubar: false, toolbar: 'code', statusbar: false, }); } if (options.additionalOptions) { Object.assign(opts, options.additionalOptions); } return opts; }, renderField () { var className = this.state.isFocused ? 'is-focused' : ''; var style = { height: this.props.height, }; return ( <div className={className}> <FormInput id={this.state.id} multiline name={this.getInputName(this.props.path)} onChange={this.valueChanged} className={this.props.wysiwyg ? 'wysiwyg' : 'code'} style={style} value={this.props.value} /> </div> ); }, renderValue () { return ( <FormInput multiline noedit> {this.props.value} </FormInput> ); }, });
test/integration/export-serverless/pages/counter.js
zeit/next.js
import React from 'react' import Link from 'next/link' let counter = 0 export default class Counter extends React.Component { increaseCounter() { counter++ this.forceUpdate() } render() { return ( <div id="counter-page"> <div> <Link href="/"> <a id="go-back">Go Back</a> </Link> </div> <p>Counter: {counter}</p> <button id="counter-increase" onClick={() => this.increaseCounter()}> Increase </button> </div> ) } }
hunt/src/common/RuleToggleModal.js
StamusNetworks/scirius
import React from 'react'; import PropTypes from 'prop-types'; import axios from 'axios'; import { Modal, Button, Checkbox, Col, Form, FormControl, FormGroup, Icon } from 'patternfly-react'; import * as config from 'hunt_common/config/Api'; import { buildQFilter } from 'hunt_common/buildQFilter'; import { buildFilterParams } from 'hunt_common/buildFilterParams'; import { supportedActions, setDefaultOptions } from 'hunt_common/supportedActions'; import HuntRestError from '../components/HuntRestError'; export default class RuleToggleModal extends React.Component { constructor(props) { super(props); this.state = { selected: [], supported_filters: [], comment: '', options: {}, errors: undefined, submitting: false, }; this.submit = this.submit.bind(this); this.close = this.close.bind(this); this.handleChange = this.handleChange.bind(this); this.handleCommentChange = this.handleCommentChange.bind(this); this.handleFieldChange = this.handleFieldChange.bind(this); this.handleOptionsChange = this.handleOptionsChange.bind(this); this.updateActionDialog = this.updateActionDialog.bind(this); this.setDefaultOptions = setDefaultOptions.bind(this); this.onFieldKeyPress = this.onFieldKeyPress.bind(this); this.toggleFilter = this.toggleFilter.bind(this); } componentDidMount() { this.updateActionDialog(); this.setDefaultOptions(); } componentDidUpdate(prevProps) { if (prevProps.filters !== this.props.filters || prevProps.action !== this.props.action) { this.updateActionDialog(); this.setDefaultOptions(); } } onFieldKeyPress = (keyEvent) => { if (keyEvent.key === 'Enter') { keyEvent.stopPropagation(); keyEvent.preventDefault(); } }; setDefaultOptions() { let options = {}; switch (this.props.action) { case 'threshold': options = { type: 'both', count: 1, seconds: 60, track: 'by_src', }; break; case 'tag': case 'tagkeep': options = { tag: 'relevant' }; break; default: break; } this.setState({ options }); } updateActionDialog() { if (['enable', 'disable'].indexOf(this.props.action) !== -1) { this.setState({ supported_filters: [], noaction: false, errors: undefined }); return; } if (this.props.filters && this.props.filters.length > 0) { const wantedFilters = Array.from(this.props.filters, (x) => x.id); const reqData = { fields: wantedFilters, action: this.props.action }; axios .post(`${config.API_URL + config.PROCESSING_PATH}test/`, reqData) .then((res) => { const suppFilters = []; let notfound = true; for (let i = 0; i < this.props.filters.length; i += 1) { if (this.props.action === 'threshold' && this.props.filters[i].negated) { // Negated filters on threshold are not supported // eslint-disable-next-line no-continue continue; } if (res.data.fields.indexOf(this.props.filters[i].id) !== -1) { const filter = JSON.parse(JSON.stringify(this.props.filters[i])); if (this.props.filters[i].negated === false) { filter.operator = 'equal'; } else if (res.data.operators.indexOf('different') !== -1) { filter.operator = 'different'; } filter.isChecked = true; filter.key = filter.id; filter.id = `filter${i}`; suppFilters.push(filter); notfound = false; } } let errors; if (notfound) { if (!res.data.supported_fields) { errors = { filters: ['No filters available'] }; } else { const negatedError = this.props.action === 'threshold' ? ' (negated filter are not supported)' : ''; errors = { filters: [`Supported filters are ${res.data.supported_fields}${negatedError}`] }; } } this.setState({ supported_filters: suppFilters, noaction: notfound, errors }); }) .catch((error) => { if (error.response.status === 403) { this.setState({ errors: { permission: ['Insufficient permissions'] }, noaction: true }); } }); } else { this.setState({ errors: { filters: ['No filters available'] }, noaction: true }); } } close() { this.setState({ errors: undefined, selected: [] }); this.props.close(); } submit() { this.setState({ submitting: true }); if (['enable', 'disable'].indexOf(this.props.action) !== -1) { this.state.selected.map((ruleset) => { const data = { ruleset }; if (this.state.comment.length > 0) { data.comment = this.state.comment; } let url = config.API_URL + config.RULE_PATH + this.props.config.rule.sid; if (this.props.action === 'enable') { url = `${url}/enable/`; } else { url = `${url}/disable/`; } axios .post(url, data) .then(() => { // Fixme notification or something if (this.props.refresh_callback) { this.props.refresh_callback(); } this.close(); }) .catch((error) => { this.setState({ errors: error.response.data }); }); return true; }); } else if (supportedActions.concat(['suppress']).indexOf(this.props.action) !== -1) { // {"filter_defs": [{"key": "src_ip", "value": "192.168.0.1", "operator": "equal"}], "action": "suppress", "rulesets": [1]} const filters = []; for (let j = 0; j < this.state.supported_filters.length; j += 1) { if (this.state.supported_filters[j].isChecked) { filters.push({ ...this.state.supported_filters[j], full_string: this.state.supported_filters[j].fullString, }); } } const data = { filter_defs: filters, action: this.props.action, rulesets: this.state.selected, comment: this.state.comment, }; if (supportedActions.indexOf(this.props.action) !== -1) { data.options = this.state.options; } const url = `${config.API_URL}${config.PROCESSING_PATH}?${buildFilterParams(this.props.filterParams)}${buildQFilter( this.props.filters, this.props.systemSettings, )}`; axios .post(url, data) .then(() => { this.setState({ submitting: false }); this.close(); }) .catch((error) => { this.setState({ errors: error.response.data, submitting: false }); }); } } handleChange(event) { const { target } = event; const value = target.type === 'checkbox' ? target.checked : target.value; const { name } = target; const selList = this.state.selected; if (value === false) { // pop element const index = selList.indexOf(name); if (index >= 0) { selList.splice(index, 1); this.setState({ selected: selList }); } } else if (selList.indexOf(name) < 0) { selList.push(name); this.setState({ selected: selList }); } } handleCommentChange(event) { this.setState({ comment: event.target.value }); } handleFieldChange(event, i) { const sfilters = Object.assign([], this.state.supported_filters); sfilters[i].value = event.target.value; this.setState({ supported_filters: sfilters }); } handleOptionsChange(event) { const options = Object.assign({}, this.state.options); options[event.target.id] = event.target.value; this.setState({ options }); } toggleFilter(i) { const sfilters = Object.assign([], this.state.supported_filters); sfilters[i].isChecked = !sfilters[i].isChecked; this.setState({ supported_filters: sfilters }); } render() { let title = null; if (this.props.action === 'threat') { title = 'Define custom Declaration(s) of Compromise'; } else if (this.props.config.rule) { title = `${this.props.action} Rule ${this.props.config.rule.sid}`; } else { title = `Add a ${this.props.action} action`; } return ( <Modal show={this.props.show} onHide={this.close}> <Modal.Header> <button type="button" className="close" onClick={this.close} aria-hidden="true" aria-label="Close"> <Icon type="pf" name="close" /> </button> <Modal.Title>{title}</Modal.Title> </Modal.Header> <Modal.Body> {this.props.action === 'threat' && ( <div style={{ marginBottom: '30px' }}> These Declaration(s) of Compromise (DoC) will appear in the Custom Threats family</div> )} <HuntRestError errors={this.state.errors} /> {!this.state.noaction && ( <Form horizontal> {this.state.supported_filters && this.state.supported_filters.map((item, i) => ( <FormGroup key={item.id} controlId={item.id}> <Col sm={4}> <Checkbox defaultChecked onChange={() => this.toggleFilter(i)}> <strong> {item.negated && 'Not '} {item.key} </strong> </Checkbox> </Col> <Col sm={8}> <FormControl type={item.id} disabled={!item.isChecked} defaultValue={item.value} onChange={(e) => this.handleFieldChange(e, i)} onKeyPress={(e) => this.onFieldKeyPress(e)} /> </Col> </FormGroup> ))} {this.props.action === 'threshold' && ( <React.Fragment> <FormGroup key="count" controlId="count" disabled={false}> <Col sm={4}> <strong>Count</strong> </Col> <Col sm={8}> <FormControl type="integer" disabled={false} defaultValue={1} onChange={this.handleOptionsChange} /> </Col> </FormGroup> <FormGroup key="seconds" controlId="seconds" disabled={false}> <Col sm={4}> <strong>Seconds</strong> </Col> <Col sm={8}> <FormControl type="integer" disabled={false} defaultValue={60} onChange={this.handleOptionsChange} /> </Col> </FormGroup> <FormGroup key="track" controlId="track" disabled={false}> <Col sm={4}> <strong>Track by</strong> </Col> <Col sm={8}> <FormControl componentClass="select" placeholder="by_src" onChange={this.handleOptionsChange}> <option value="by_src">By Source</option> <option value="by_dst">By Destination</option> </FormControl> </Col> </FormGroup> </React.Fragment> )} {this.props.children && this.props.children(this)} <hr /> { <FormGroup controlId="ruleset" disabled={false}> <Col sm={12}> <label> <strong>Ruleset{this.props.rulesets.length > 1 && 's'}:</strong> </label> {this.props.rulesets && this.props.rulesets.map((ruleset) => ( <div className="row" key={ruleset.pk}> <div className="col-sm-9"> <label htmlFor={ruleset.pk}> <input type="checkbox" id={ruleset.pk} name={ruleset.pk} onChange={this.handleChange} /> {ruleset.name} </label> {ruleset.warnings && <div style={{ marginLeft: '5%' }}>• {ruleset.warnings}</div>} {/* ignore_utf8_check 8226 8214 */} {ruleset[`warnings_${this.props.action}`] && ( <React.Fragment> <div style={{ marginLeft: '5%' }}>• {ruleset[`warnings_${this.props.action}`]}</div> {/* ignore_utf8_check 8226 */} </React.Fragment> )}{' '} </div> </div> ))} </Col> </FormGroup> } <hr /> <div className="form-group"> <div className="col-sm-9"> <strong>Optional comment</strong> <textarea value={this.state.comment} cols={70} onChange={this.handleCommentChange} /> </div> </div> </Form> )} {this.state.noaction && <p>You need enough permissions and at least a filter supported by the ruleset backend to define an action</p>} </Modal.Body> <Modal.Footer> <Button bsStyle="default" className="btn-cancel" onClick={this.close}> Cancel </Button> {!this.state.noaction && ( <Button bsStyle="primary" onClick={this.submit} disabled={this.state.submitting}> Submit </Button> )} </Modal.Footer> </Modal> ); } } RuleToggleModal.propTypes = { filters: PropTypes.any, action: PropTypes.any, rulesets: PropTypes.any, refresh_callback: PropTypes.any, show: PropTypes.any, config: PropTypes.any, close: PropTypes.func, children: PropTypes.any, systemSettings: PropTypes.any, filterParams: PropTypes.any, };
src/pages/SGGS/index.js
bogas04/SikhJS
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { withRouter } from 'react-router-dom'; import { isBookmarked, toggleBookmark } from '../../bookmarks'; import { Loader } from '../../components'; import constants from './constants'; import AngBar from './AngBar'; import AngContent from './AngContent'; import RaagAng from './RaagAng'; const STORAGE_KEYS = { ANG: 'sggs-ang', LARIVAAR: 'sggs-larivaar', LARIVAAR_ASSIST: 'sggs-larivaar-assist', TRANSLATION: 'sggs-translation', }; class SGGS extends Component { constructor (props) { super(props); const ang = parseInt(this.props.match.params.ang || localStorage.getItem(STORAGE_KEYS.ANG) || 1); this.state = { error: false, lines: [], ang, larivaar: localStorage.getItem(STORAGE_KEYS.LARIVAAR) === 'true', larivaarAssist: localStorage.getItem(STORAGE_KEYS.LARIVAAR_ASSIST) === 'true', showTranslation: localStorage.getItem(STORAGE_KEYS.TRANSLATION) === 'true', isBookmarked: false, }; this.setAng = this.setAng.bind(this); this.handleDecrementAng = this.handleDecrementAng.bind(this); this.handleIncrementAng = this.handleIncrementAng.bind(this); this.handleRandomAng = this.handleRandomAng.bind(this); this.handleToggleLarivaar = this.handleToggleLarivaar.bind(this); this.handleToggleLarivaarAssist = this.handleToggleLarivaarAssist.bind(this); this.handleToggleTranslation = this.handleToggleTranslation.bind(this); this.handleToggleBookmark = this.handleToggleBookmark.bind(this); } componentDidMount () { if (this.props.match.params.ang) { this.updateLines(); isBookmarked({ key: 'sggs', value: this.state.ang }) .then(isBookmarked => this.setState({ isBookmarked })) .catch(err => { console.error(err); this.setState({ error: true }); }); } else { this.props.history.push(`/sggs/${this.state.ang}`); } } render () { const { isBookmarked, lines, ang, larivaar, larivaarAssist, showTranslation, error } = this.state; return ( <div> <AngBar isBookmarked={isBookmarked} totalLines={lines.length} ang={ang} larivaar={larivaar} larivaarAssist={larivaarAssist} showTranslation={showTranslation} onSetAng={this.setAng} onDecrementAng={this.handleDecrementAng} onIncrementAng={this.handleIncrementAng} onRandomAng={this.handleRandomAng} onToggleLarivaar={this.handleToggleLarivaar} onToggleLarivaarAssist={this.handleToggleLarivaarAssist} onToggleTranslation={this.handleToggleTranslation} onToggleBookmark={this.handleToggleBookmark} /> { error ? <h2> Can't find the ang {ang} </h2> : ( <Loader loading={lines.length === 0}> <RaagAng enabled={constants.RAAG_ANGS.indexOf(ang) > -1}> <AngContent lines={lines} larivaar={larivaar} larivaarAssist={larivaarAssist} showTranslation={showTranslation} /> </RaagAng> </Loader> ) } </div> ); } updateLines (ang = this.state.ang) { this.setState({ lines: [] }); return fetch(`assets/docs/json/SGGS/Ang ${ang}.json`) .then(r => r.json()) .then(lines => this.setState({ lines, error: false, ang })) .catch(err => { console.error(err); this.setState({ error: true }); }); } setAng (ang) { if (ang) { localStorage.setItem(STORAGE_KEYS.ANG, ang); this.props.history.push(`/sggs/${ang}`); } } handleRandomAng () { this.setAng(parseInt(1 + (Math.random() * 1430), 10)); } handleIncrementAng () { this.setAng(parseInt(this.state.ang, 10) + 1); } handleDecrementAng () { this.setAng(parseInt(this.state.ang, 10) - 1); } handleToggleLarivaar () { localStorage.setItem(STORAGE_KEYS.LARIVAAR, !this.state.larivaar); this.setState({ larivaar: !this.state.larivaar, }); } handleToggleLarivaarAssist () { localStorage.setItem(STORAGE_KEYS.LARIVAAR_ASSIST, !this.state.larivaarAssist); this.setState({ larivaarAssist: !this.state.larivaarAssist }); } handleToggleTranslation () { localStorage.setItem(STORAGE_KEYS.TRANSLATION, !this.state.showTranslation); this.setState({ showTranslation: !this.state.showTranslation }); } handleToggleBookmark () { const { isBookmarked, ang } = this.state; const title = `Sri Guru Granth Sahib ${ang}`; toggleBookmark({ isBookmarked, title, key: 'sggs', value: ang }) .then(isBookmarked => this.setState({ isBookmarked })) .catch(err => { console.error(err); this.setState({ error: true }); }); } } SGGS.propTypes = { match: PropTypes.object, }; export default withRouter(SGGS);
src/components/IntroButton/IntroButton.js
askd/animakit
import React from 'react'; import PropTypes from 'prop-types'; import styles from './IntroButton.css'; const IntroButton = (props) => { if (props.link) { return ( <a href={ props.link } target="_blank" rel="noopener noreferrer" className={ `${styles.button} ${props.className}` } > { props.children } </a> ); } return ( <button type="button" className={ `${styles.button} ${props.className}` } onClick={ props.handleClick } > { props.children } </button> ); }; IntroButton.propTypes = { children: PropTypes.any, className: PropTypes.string, link: PropTypes.string, handleClick: PropTypes.func, }; IntroButton.defaultProps = { className: '', }; export default IntroButton;
src/components/Layout/Menu/Menu.js
mmrath/react-app
'use strict'; import './Menu.less'; import React from 'react'; import ReactBootstrap from 'react-bootstrap'; import Router from 'react-router'; export default React.createClass({ render() { var Accordion = ReactBootstrap.Accordion; var Panel = ReactBootstrap.Panel; var Link = Router.Link; return ( <Accordion> <Panel header="Item#1" eventKey='1'> <Link to="notification" className="list-group-item">Notifications</Link> <Link to="user" className="list-group-item">Users</Link> <a href="" className="list-group-item">Subitem 1</a> </Panel> <Panel header="Item#2" eventKey='2'> <a href="" className="list-group-item">Subitem 1</a> <a href="" className="list-group-item">Subitem 1</a> </Panel> <Panel header="Item #3" eventKey='3'> <a href="" className="list-group-item">Subitem 1</a> <a href="" className="list-group-item">Subitem 1</a> </Panel> </Accordion> ); } });
client/src/components/header/menu.js
OpenChemistry/materialsdatabank
import React, { Component } from 'react'; import { connect } from 'react-redux' import MenuItem from '@material-ui/core/MenuItem'; import MenuList from '@material-ui/core/MenuList'; import Popover, { PopoverAnimationVertical } from '@material-ui/core/Popover'; import Button from '@material-ui/core/Button'; import DropDownIcon from '@material-ui/icons/ArrowDropDown'; import ExitToAppIcon from '@material-ui/icons/ExitToApp'; import selectors from '../../redux/selectors'; import { invalidateToken } from '../../redux/ducks/girder' class Menu extends Component { constructor(props) { super(props); this.state = { open: false, }; } handleTouchTap = (event) => { this.setState({ open: true, anchorEl: event.currentTarget, }); }; handleRequestClose = () => { this.setState({ open: false, }); }; handleSignOut = (event) => { // This prevents ghost click. event.preventDefault(); this.props.dispatch(invalidateToken()) }; render = () => { const {me} = this.props; return ( <div> <Button onClick={this.handleTouchTap}> {me ? me.login : 'user' } <DropDownIcon /> </Button> <Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={{horizontal: 'left', vertical: 'bottom'}} onClose={this.handleRequestClose} animation={PopoverAnimationVertical} > <MenuList> <MenuItem onClick={this.handleSignOut} > <ExitToAppIcon/> Sign out </MenuItem> </MenuList> </Popover> </div> ); } } function mapStateToProps(state, ownProps) { const me = selectors.girder.getMe(state); return { me, } } export default connect(mapStateToProps)(Menu)
ajax/libs/react/0.14.0-alpha1/react.min.js
jdh8/cdnjs
/** * React v0.14.0-alpha1 * * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;t="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,t.React=e()}}(function(){return function e(t,n,r){function o(a,u){if(!n[a]){if(!t[a]){var s="function"==typeof require&&require;if(!u&&s)return s(a,!0);if(i)return i(a,!0);var l=new Error("Cannot find module '"+a+"'");throw l.code="MODULE_NOT_FOUND",l}var c=n[a]={exports:{}};t[a][0].call(c.exports,function(e){var n=t[a][1][e];return o(n?n:e)},c,c.exports,e,t,n,r)}return n[a].exports}for(var i="function"==typeof require&&require,a=0;a<r.length;a++)o(r[a]);return o}({1:[function(e,t,n){"use strict";var r=e(31),o=e(33),i=e(32),a=e(38),u=e(54),s=(e(55),e(39)),l=e(50),c=e(53),p=e(63),d=e(67),f=e(72),h=e(75),m=e(77),v=e(80),g=e(26),y=e(113),C=e(139);e(148);c.inject();var E=u.createElement,b=u.createFactory,_=u.cloneElement,x=f.measure("React","render",d.render),D={Children:{map:r.map,forEach:r.forEach,count:r.count,only:C},Component:o,DOM:s,PropTypes:h,createClass:i.createClass,createElement:E,cloneElement:_,createFactory:b,createMixin:function(e){return e},constructAndRenderComponent:d.constructAndRenderComponent,constructAndRenderComponentByID:d.constructAndRenderComponentByID,findDOMNode:y,render:x,renderToString:v.renderToString,renderToStaticMarkup:v.renderToStaticMarkup,unmountComponentAtNode:d.unmountComponentAtNode,isValidElement:u.isValidElement,__spread:g};"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject&&__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({CurrentOwner:a,InstanceHandles:p,Mount:d,Reconciler:m,TextComponent:l});D.version="0.14.0-alpha1",t.exports=D},{113:113,139:139,148:148,26:26,31:31,32:32,33:33,38:38,39:39,50:50,53:53,54:54,55:55,63:63,67:67,72:72,75:75,77:77,80:80}],2:[function(e,t,n){"use strict";var r=e(113),o=e(115),i={componentDidMount:function(){this.props.autoFocus&&o(r(this))}};t.exports=i},{113:113,115:115}],3:[function(e,t,n){"use strict";function r(){var e=window.opera;return"object"==typeof e&&"function"==typeof e.version&&parseInt(e.version(),10)<=12}function o(e){return(e.ctrlKey||e.altKey||e.metaKey)&&!(e.ctrlKey&&e.altKey)}function i(e){switch(e){case T.topCompositionStart:return R.compositionStart;case T.topCompositionEnd:return R.compositionEnd;case T.topCompositionUpdate:return R.compositionUpdate}}function a(e,t){return e===T.topKeyDown&&t.keyCode===b}function u(e,t){switch(e){case T.topKeyUp:return-1!==E.indexOf(t.keyCode);case T.topKeyDown:return t.keyCode!==b;case T.topKeyPress:case T.topMouseDown:case T.topBlur:return!0;default:return!1}}function s(e){var t=e.detail;return"object"==typeof t&&"data"in t?t.data:null}function l(e,t,n,r){var o,l;if(_?o=i(e):w?u(e,r)&&(o=R.compositionEnd):a(e,r)&&(o=R.compositionStart),!o)return null;M&&(w||o!==R.compositionStart?o===R.compositionEnd&&w&&(l=w.getData()):w=v.getPooled(t));var c=g.getPooled(o,n,r);if(l)c.data=l;else{var p=s(r);null!==p&&(c.data=p)}return h.accumulateTwoPhaseDispatches(c),c}function c(e,t){switch(e){case T.topCompositionEnd:return s(t);case T.topKeyPress:var n=t.which;return n!==I?null:(P=!0,N);case T.topTextInput:var r=t.data;return r===N&&P?null:r;default:return null}}function p(e,t){if(w){if(e===T.topCompositionEnd||u(e,t)){var n=w.getData();return v.release(w),w=null,n}return null}switch(e){case T.topPaste:return null;case T.topKeyPress:return t.which&&!o(t)?String.fromCharCode(t.which):null;case T.topCompositionEnd:return M?null:t.data;default:return null}}function d(e,t,n,r){var o;if(o=D?c(e,r):p(e,r),!o)return null;var i=y.getPooled(R.beforeInput,n,r);return i.data=o,h.accumulateTwoPhaseDispatches(i),i}var f=e(15),h=e(20),m=e(21),v=e(22),g=e(89),y=e(93),C=e(136),E=[9,13,27,32],b=229,_=m.canUseDOM&&"CompositionEvent"in window,x=null;m.canUseDOM&&"documentMode"in document&&(x=document.documentMode);var D=m.canUseDOM&&"TextEvent"in window&&!x&&!r(),M=m.canUseDOM&&(!_||x&&x>8&&11>=x),I=32,N=String.fromCharCode(I),T=f.topLevelTypes,R={beforeInput:{phasedRegistrationNames:{bubbled:C({onBeforeInput:null}),captured:C({onBeforeInputCapture:null})},dependencies:[T.topCompositionEnd,T.topKeyPress,T.topTextInput,T.topPaste]},compositionEnd:{phasedRegistrationNames:{bubbled:C({onCompositionEnd:null}),captured:C({onCompositionEndCapture:null})},dependencies:[T.topBlur,T.topCompositionEnd,T.topKeyDown,T.topKeyPress,T.topKeyUp,T.topMouseDown]},compositionStart:{phasedRegistrationNames:{bubbled:C({onCompositionStart:null}),captured:C({onCompositionStartCapture:null})},dependencies:[T.topBlur,T.topCompositionStart,T.topKeyDown,T.topKeyPress,T.topKeyUp,T.topMouseDown]},compositionUpdate:{phasedRegistrationNames:{bubbled:C({onCompositionUpdate:null}),captured:C({onCompositionUpdateCapture:null})},dependencies:[T.topBlur,T.topCompositionUpdate,T.topKeyDown,T.topKeyPress,T.topKeyUp,T.topMouseDown]}},P=!1,w=null,O={eventTypes:R,extractEvents:function(e,t,n,r){return[l(e,t,n,r),d(e,t,n,r)]}};t.exports=O},{136:136,15:15,20:20,21:21,22:22,89:89,93:93}],4:[function(e,t,n){"use strict";function r(e,t){return e+t.charAt(0).toUpperCase()+t.substring(1)}var o={boxFlex:!0,boxFlexGroup:!0,columnCount:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,strokeDashoffset:!0,strokeOpacity:!0,strokeWidth:!0},i=["Webkit","ms","Moz","O"];Object.keys(o).forEach(function(e){i.forEach(function(t){o[r(t,e)]=o[e]})});var a={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},u={isUnitlessNumber:o,shorthandPropertyExpansions:a};t.exports=u},{}],5:[function(e,t,n){"use strict";var r=e(4),o=e(21),i=(e(104),e(109)),a=e(128),u=e(138),s=(e(148),u(function(e){return a(e)})),l="cssFloat";o.canUseDOM&&void 0===document.documentElement.style.cssFloat&&(l="styleFloat");var c={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];null!=r&&(t+=s(n)+":",t+=i(n,r)+";")}return t||null},setValueForStyles:function(e,t){var n=e.style;for(var o in t)if(t.hasOwnProperty(o)){var a=i(o,t[o]);if("float"===o&&(o=l),a)n[o]=a;else{var u=r.shorthandPropertyExpansions[o];if(u)for(var s in u)n[s]="";else n[o]=""}}}};t.exports=c},{104:104,109:109,128:128,138:138,148:148,21:21,4:4}],6:[function(e,t,n){"use strict";function r(){this._callbacks=null,this._contexts=null}var o=e(27),i=e(26),a=e(130);i(r.prototype,{enqueue:function(e,t){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(e),this._contexts.push(t)},notifyAll:function(){var e=this._callbacks,t=this._contexts;if(e){a(e.length===t.length),this._callbacks=null,this._contexts=null;for(var n=0;n<e.length;n++)e[n].call(t[n]);e.length=0,t.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),o.addPoolingTo(r),t.exports=r},{130:130,26:26,27:27}],7:[function(e,t,n){"use strict";function r(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function o(e){var t=x.getPooled(T.change,P,e);E.accumulateTwoPhaseDispatches(t),_.batchedUpdates(i,t)}function i(e){C.enqueueEvents(e),C.processEventQueue()}function a(e,t){R=e,P=t,R.attachEvent("onchange",o)}function u(){R&&(R.detachEvent("onchange",o),R=null,P=null)}function s(e,t,n){return e===N.topChange?n:void 0}function l(e,t,n){e===N.topFocus?(u(),a(t,n)):e===N.topBlur&&u()}function c(e,t){R=e,P=t,w=e.value,O=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(R,"value",A),R.attachEvent("onpropertychange",d)}function p(){R&&(delete R.value,R.detachEvent("onpropertychange",d),R=null,P=null,w=null,O=null)}function d(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==w&&(w=t,o(e))}}function f(e,t,n){return e===N.topInput?n:void 0}function h(e,t,n){e===N.topFocus?(p(),c(t,n)):e===N.topBlur&&p()}function m(e,t,n){return e!==N.topSelectionChange&&e!==N.topKeyUp&&e!==N.topKeyDown||!R||R.value===w?void 0:(w=R.value,P)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function g(e,t,n){return e===N.topClick?n:void 0}var y=e(15),C=e(17),E=e(20),b=e(21),_=e(83),x=e(91),D=e(131),M=e(133),I=e(136),N=y.topLevelTypes,T={change:{phasedRegistrationNames:{bubbled:I({onChange:null}),captured:I({onChangeCapture:null})},dependencies:[N.topBlur,N.topChange,N.topClick,N.topFocus,N.topInput,N.topKeyDown,N.topKeyUp,N.topSelectionChange]}},R=null,P=null,w=null,O=null,S=!1;b.canUseDOM&&(S=D("change")&&(!("documentMode"in document)||document.documentMode>8));var k=!1;b.canUseDOM&&(k=D("input")&&(!("documentMode"in document)||document.documentMode>9));var A={get:function(){return O.get.call(this)},set:function(e){w=""+e,O.set.call(this,e)}},U={eventTypes:T,extractEvents:function(e,t,n,o){var i,a;if(r(t)?S?i=s:a=l:M(t)?k?i=f:(i=m,a=h):v(t)&&(i=g),i){var u=i(e,t,n);if(u){var c=x.getPooled(T.change,u,o);return E.accumulateTwoPhaseDispatches(c),c}}a&&a(e,t,n)}};t.exports=U},{131:131,133:133,136:136,15:15,17:17,20:20,21:21,83:83,91:91}],8:[function(e,t,n){"use strict";var r=0,o={createReactRootIndex:function(){return r++}};t.exports=o},{}],9:[function(e,t,n){"use strict";function r(e,t,n){var r=n>=e.childNodes.length?null:e.childNodes.item(n);e.insertBefore(t,r)}var o=e(12),i=e(69),a=e(142),u=e(130),s={dangerouslyReplaceNodeWithMarkup:o.dangerouslyReplaceNodeWithMarkup,updateTextContent:a,processUpdates:function(e,t){for(var n,s=null,l=null,c=0;c<e.length;c++)if(n=e[c],n.type===i.MOVE_EXISTING||n.type===i.REMOVE_NODE){var p=n.fromIndex,d=n.parentNode.childNodes[p],f=n.parentID;u(d),s=s||{},s[f]=s[f]||[],s[f][p]=d,l=l||[],l.push(d)}var h=o.dangerouslyRenderMarkup(t);if(l)for(var m=0;m<l.length;m++)l[m].parentNode.removeChild(l[m]);for(var v=0;v<e.length;v++)switch(n=e[v],n.type){case i.INSERT_MARKUP:r(n.parentNode,h[n.markupIndex],n.toIndex);break;case i.MOVE_EXISTING:r(n.parentNode,s[n.parentID][n.fromIndex],n.toIndex);break;case i.TEXT_CONTENT:a(n.parentNode,n.textContent);break;case i.REMOVE_NODE:}}};t.exports=s},{12:12,130:130,142:142,69:69}],10:[function(e,t,n){"use strict";function r(e,t){return(e&t)===t}var o=e(130),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 t=e.Properties||{},n=e.DOMAttributeNamespaces||{},a=e.DOMAttributeNames||{},s=e.DOMPropertyNames||{},l=e.DOMMutationMethods||{};e.isCustomAttribute&&u._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var c in t){o(!u.isStandardName.hasOwnProperty(c)),u.isStandardName[c]=!0;var p=c.toLowerCase();if(u.getPossibleStandardName[p]=c,a.hasOwnProperty(c)){var d=a[c];u.getPossibleStandardName[d]=c,u.getAttributeName[c]=d}else u.getAttributeName[c]=p;n.hasOwnProperty(c)?u.getAttributeNamespace[c]=n[c]:u.getAttributeNamespace[c]=null,u.getPropertyName[c]=s.hasOwnProperty(c)?s[c]:c,l.hasOwnProperty(c)?u.getMutationMethod[c]=l[c]:u.getMutationMethod[c]=null;var f=t[c];u.mustUseAttribute[c]=r(f,i.MUST_USE_ATTRIBUTE),u.mustUseProperty[c]=r(f,i.MUST_USE_PROPERTY),u.hasSideEffects[c]=r(f,i.HAS_SIDE_EFFECTS),u.hasBooleanValue[c]=r(f,i.HAS_BOOLEAN_VALUE),u.hasNumericValue[c]=r(f,i.HAS_NUMERIC_VALUE),u.hasPositiveNumericValue[c]=r(f,i.HAS_POSITIVE_NUMERIC_VALUE),u.hasOverloadedBooleanValue[c]=r(f,i.HAS_OVERLOADED_BOOLEAN_VALUE),o(!u.mustUseAttribute[c]||!u.mustUseProperty[c]),o(u.mustUseProperty[c]||!u.hasSideEffects[c]),o(!!u.hasBooleanValue[c]+!!u.hasNumericValue[c]+!!u.hasOverloadedBooleanValue[c]<=1)}}},a={},u={ID_ATTRIBUTE_NAME:"data-reactid",isStandardName:{},getPossibleStandardName:{},getAttributeName:{},getAttributeNamespace:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasSideEffects:{},hasBooleanValue:{},hasNumericValue:{},hasPositiveNumericValue:{},hasOverloadedBooleanValue:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){for(var t=0;t<u._isCustomAttributeFunctions.length;t++){var n=u._isCustomAttributeFunctions[t];if(n(e))return!0}return!1},getDefaultValueForProperty:function(e,t){var n,r=a[e];return r||(a[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:i};t.exports=u},{130:130}],11:[function(e,t,n){"use strict";function r(e,t){return null==t||o.hasBooleanValue[e]&&!t||o.hasNumericValue[e]&&isNaN(t)||o.hasPositiveNumericValue[e]&&1>t||o.hasOverloadedBooleanValue[e]&&t===!1}var o=e(10),i=e(140),a=(e(148),{createMarkupForID:function(e){return o.ID_ATTRIBUTE_NAME+"="+i(e)},createMarkupForProperty:function(e,t){if(o.isStandardName.hasOwnProperty(e)&&o.isStandardName[e]){if(r(e,t))return"";var n=o.getAttributeName[e];return o.hasBooleanValue[e]||o.hasOverloadedBooleanValue[e]&&t===!0?n+'=""':n+"="+i(t)}return o.isCustomAttribute(e)?null==t?"":e+"="+i(t):null},setValueForProperty:function(e,t,n){if(o.isStandardName.hasOwnProperty(t)&&o.isStandardName[t]){var i=o.getMutationMethod[t];if(i)i(e,n);else if(r(t,n))this.deleteValueForProperty(e,t);else if(o.mustUseAttribute[t]){var a=o.getAttributeName[t],u=o.getAttributeNamespace[t];u?e.setAttributeNS(u,a,""+n):e.setAttribute(a,""+n)}else{var s=o.getPropertyName[t];o.hasSideEffects[t]&&""+e[s]==""+n||(e[s]=n)}}else o.isCustomAttribute(t)&&(null==n?e.removeAttribute(t):e.setAttribute(t,""+n))},deleteValueForProperty:function(e,t){if(o.isStandardName.hasOwnProperty(t)&&o.isStandardName[t]){var n=o.getMutationMethod[t];if(n)n(e,void 0);else if(o.mustUseAttribute[t])e.removeAttribute(o.getAttributeName[t]);else{var r=o.getPropertyName[t],i=o.getDefaultValueForProperty(e.nodeName,r);o.hasSideEffects[t]&&""+e[r]===i||(e[r]=i)}}else o.isCustomAttribute(t)&&e.removeAttribute(t)}});t.exports=a},{10:10,140:140,148:148}],12:[function(e,t,n){"use strict";function r(e){return e.substring(1,e.indexOf(" "))}var o=e(21),i=e(108),a=e(110),u=e(123),s=e(130),l=/^(<[^ \/>]+)/,c="data-danger-index",p={dangerouslyRenderMarkup:function(e){s(o.canUseDOM);for(var t,n={},p=0;p<e.length;p++)s(e[p]),t=r(e[p]),t=u(t)?t:"*",n[t]=n[t]||[],n[t][p]=e[p];var d=[],f=0;for(t in n)if(n.hasOwnProperty(t)){var h,m=n[t];for(h in m)if(m.hasOwnProperty(h)){var v=m[h];m[h]=v.replace(l,"$1 "+c+'="'+h+'" ')}for(var g=i(m.join(""),a),y=0;y<g.length;++y){var C=g[y];C.hasAttribute&&C.hasAttribute(c)&&(h=+C.getAttribute(c),C.removeAttribute(c),s(!d.hasOwnProperty(h)),d[h]=C,f+=1)}}return s(f===d.length),s(d.length===e.length),d},dangerouslyReplaceNodeWithMarkup:function(e,t){s(o.canUseDOM),s(t),s("html"!==e.tagName.toLowerCase());var n=i(t,a)[0];e.parentNode.replaceChild(n,e)}};t.exports=p},{108:108,110:110,123:123,130:130,21:21}],13:[function(e,t,n){"use strict";var r=e(136),o=[r({ResponderEventPlugin:null}),r({SimpleEventPlugin:null}),r({TapEventPlugin:null}),r({EnterLeaveEventPlugin:null}),r({ChangeEventPlugin:null}),r({SelectEventPlugin:null}),r({BeforeInputEventPlugin:null}),r({AnalyticsEventPlugin:null})];t.exports=o},{136:136}],14:[function(e,t,n){"use strict";var r=e(15),o=e(20),i=e(95),a=e(67),u=e(136),s=r.topLevelTypes,l=a.getFirstReactDOM,c={mouseEnter:{registrationName:u({onMouseEnter:null}),dependencies:[s.topMouseOut,s.topMouseOver]},mouseLeave:{registrationName:u({onMouseLeave:null}),dependencies:[s.topMouseOut,s.topMouseOver]}},p=[null,null],d={eventTypes:c,extractEvents:function(e,t,n,r){if(e===s.topMouseOver&&(r.relatedTarget||r.fromElement))return null;if(e!==s.topMouseOut&&e!==s.topMouseOver)return null;var u;if(t.window===t)u=t;else{var d=t.ownerDocument;u=d?d.defaultView||d.parentWindow:window}var f,h;if(e===s.topMouseOut?(f=t,h=l(r.relatedTarget||r.toElement)||u):(f=u,h=t),f===h)return null;var m=f?a.getID(f):"",v=h?a.getID(h):"",g=i.getPooled(c.mouseLeave,m,r);g.type="mouseleave",g.target=f,g.relatedTarget=h;var y=i.getPooled(c.mouseEnter,v,r);return y.type="mouseenter",y.target=h,y.relatedTarget=f,o.accumulateEnterLeaveDispatches(g,y,m,v),p[0]=g,p[1]=y,p}};t.exports=d},{136:136,15:15,20:20,67:67,95:95}],15:[function(e,t,n){"use strict";var r=e(135),o=r({bubbled:null,captured:null}),i=r({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}),a={topLevelTypes:i,PropagationPhases:o};t.exports=a},{135:135}],16:[function(e,t,n){"use strict";var r=e(110),o={listen:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!1),{remove:function(){e.removeEventListener(t,n,!1)}}):e.attachEvent?(e.attachEvent("on"+t,n),{remove:function(){e.detachEvent("on"+t,n)}}):void 0},capture:function(e,t,n){return e.addEventListener?(e.addEventListener(t,n,!0),{remove:function(){e.removeEventListener(t,n,!0)}}):{remove:r}},registerDefault:function(){}};t.exports=o},{110:110}],17:[function(e,t,n){"use strict";var r=e(18),o=e(19),i=e(101),a=e(116),u=e(130),s=(e(148),{}),l=null,c=function(e){if(e){var t=o.executeDispatch,n=r.getPluginModuleForEvent(e);n&&n.executeDispatch&&(t=n.executeDispatch),o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},p=null,d={injection:{injectMount:o.injection.injectMount,injectInstanceHandle:function(e){p=e},getInstanceHandle:function(){return p},injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},eventNameDispatchConfigs:r.eventNameDispatchConfigs,registrationNameModules:r.registrationNameModules,putListener:function(e,t,n){u("function"==typeof n);var o=s[t]||(s[t]={});o[e]=n;var i=r.registrationNameModules[t];i&&i.didPutListener&&i.didPutListener(e,t,n)},getListener:function(e,t){var n=s[t];return n&&n[e]},deleteListener:function(e,t){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t);var o=s[t];o&&delete o[e]},deleteAllListeners:function(e){for(var t in s)if(s[t][e]){var n=r.registrationNameModules[t];n&&n.willDeleteListener&&n.willDeleteListener(e,t),delete s[t][e]}},extractEvents:function(e,t,n,o){for(var a,u=r.plugins,s=0;s<u.length;s++){var l=u[s];if(l){var c=l.extractEvents(e,t,n,o);c&&(a=i(a,c))}}return a},enqueueEvents:function(e){e&&(l=i(l,e))},processEventQueue:function(){var e=l;l=null,a(e,c),u(!l)},__purge:function(){s={}},__getListenerBank:function(){return s}};t.exports=d},{101:101,116:116,130:130,148:148,18:18,19:19}],18:[function(e,t,n){"use strict";function r(){if(u)for(var e in s){var t=s[e],n=u.indexOf(e);if(a(n>-1),!l.plugins[n]){a(t.extractEvents),l.plugins[n]=t;var r=t.eventTypes;for(var i in r)a(o(r[i],t,i))}}}function o(e,t,n){a(!l.eventNameDispatchConfigs.hasOwnProperty(n)),l.eventNameDispatchConfigs[n]=e;var r=e.phasedRegistrationNames;if(r){for(var o in r)if(r.hasOwnProperty(o)){var u=r[o];i(u,t,n)}return!0}return e.registrationName?(i(e.registrationName,t,n),!0):!1}function i(e,t,n){a(!l.registrationNameModules[e]),l.registrationNameModules[e]=t,l.registrationNameDependencies[e]=t.eventTypes[n].dependencies}var a=e(130),u=null,s={},l={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(e){a(!u),u=Array.prototype.slice.call(e),r()},injectEventPluginsByName:function(e){var t=!1;for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];s.hasOwnProperty(n)&&s[n]===o||(a(!s[n]),s[n]=o,t=!0)}t&&r()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return l.registrationNameModules[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=l.registrationNameModules[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){u=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];l.plugins.length=0;var t=l.eventNameDispatchConfigs;for(var n in t)t.hasOwnProperty(n)&&delete t[n];var r=l.registrationNameModules;for(var o in r)r.hasOwnProperty(o)&&delete r[o]}};t.exports=l},{130:130}],19:[function(e,t,n){"use strict";function r(e){return e===v.topMouseUp||e===v.topTouchEnd||e===v.topTouchCancel}function o(e){return e===v.topMouseMove||e===v.topTouchMove}function i(e){return e===v.topMouseDown||e===v.topTouchStart}function a(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function u(e,t,n){e.currentTarget=m.Mount.getNode(n);var r=t(e,n);return e.currentTarget=null,r}function s(e,t){a(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function c(e){var t=l(e);return e._dispatchIDs=null,e._dispatchListeners=null,t}function p(e){var t=e._dispatchListeners,n=e._dispatchIDs;h(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function d(e){return!!e._dispatchListeners}var f=e(15),h=e(130),m=(e(148),{Mount:null,injectMount:function(e){m.Mount=e}}),v=f.topLevelTypes,g={isEndish:r,isMoveish:o,isStartish:i,executeDirectDispatch:p,executeDispatch:u,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:c,hasDispatches:d,getNode:function(e){return m.Mount.getNode(e)},getID:function(e){return m.Mount.getID(e)},injection:m};t.exports=g},{130:130,148:148,15:15}],20:[function(e,t,n){"use strict";function r(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return y(e,r)}function o(e,t,n){var o=t?g.bubbled:g.captured,i=r(e,n,o);i&&(n._dispatchListeners=m(n._dispatchListeners,i),n._dispatchIDs=m(n._dispatchIDs,e))}function i(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhase(e.dispatchMarker,o,e)}function a(e){e&&e.dispatchConfig.phasedRegistrationNames&&h.injection.getInstanceHandle().traverseTwoPhaseSkipTarget(e.dispatchMarker,o,e)}function u(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=y(e,r);o&&(n._dispatchListeners=m(n._dispatchListeners,o),n._dispatchIDs=m(n._dispatchIDs,e))}}function s(e){e&&e.dispatchConfig.registrationName&&u(e.dispatchMarker,null,e)}function l(e){v(e,i)}function c(e){v(e,a)}function p(e,t,n,r){h.injection.getInstanceHandle().traverseEnterLeave(n,r,u,e,t)}function d(e){v(e,s)}var f=e(15),h=e(17),m=(e(148),e(101)),v=e(116),g=f.PropagationPhases,y=h.getListener,C={accumulateTwoPhaseDispatches:l,accumulateTwoPhaseDispatchesSkipTarget:c,accumulateDirectDispatches:d,accumulateEnterLeaveDispatches:p};t.exports=C},{101:101,116:116,148:148,15:15,17:17}],21:[function(e,t,n){"use strict";var r=!("undefined"==typeof window||!window.document||!window.document.createElement),o={canUseDOM:r,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:r&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:r&&!!window.screen,isInWorker:!r};t.exports=o},{}],22:[function(e,t,n){"use strict";function r(e){this._root=e,this._startText=this.getText(),this._fallbackText=null}var o=e(27),i=e(26),a=e(125);i(r.prototype,{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,r=n.length,o=this.getText(),i=o.length;for(e=0;r>e&&n[e]===o[e];e++);var a=r-e;for(t=1;a>=t&&n[r-t]===o[i-t];t++);var u=t>1?1-t:void 0;return this._fallbackText=o.slice(e,u),this._fallbackText}}),o.addPoolingTo(r),t.exports=r},{125:125,26:26,27:27}],23:[function(e,t,n){"use strict";var r,o=e(10),i=e(21),a=o.injection.MUST_USE_ATTRIBUTE,u=o.injection.MUST_USE_PROPERTY,s=o.injection.HAS_BOOLEAN_VALUE,l=o.injection.HAS_SIDE_EFFECTS,c=o.injection.HAS_NUMERIC_VALUE,p=o.injection.HAS_POSITIVE_NUMERIC_VALUE,d=o.injection.HAS_OVERLOADED_BOOLEAN_VALUE;if(i.canUseDOM){var f=document.implementation;r=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|s,allowTransparency:a,alt:null,async:s,autoComplete:null,autoPlay:s,cellPadding:null,cellSpacing:null,charSet:a,checked:u|s,classID:a,className:r?a:u,cols:a|p,colSpan:null,content:null,contentEditable:null,contextMenu:a,controls:u|s,coords:null,crossOrigin:null,data:null,dateTime:a,defer:s,dir:null,disabled:a|s,download:d,draggable:null,encType:null,form:a,formAction:a,formEncType:a,formMethod:a,formNoValidate:s,formTarget:a,frameBorder:a,headers:null,height:a,hidden:a|s,high:null,href:null,hrefLang:null,htmlFor:null,httpEquiv:null,icon:null,id:u,label:null,lang:null,list:a,loop:u|s,low:null,manifest:a,marginHeight:null,marginWidth:null,max:null,maxLength:a,media:a,mediaGroup:null,method:null,min:null,multiple:u|s,muted:u|s,name:null,noValidate:s,open:s,optimum:null,pattern:null,placeholder:null,poster:null,preload:null,radioGroup:null,readOnly:u|s,rel:null,required:s,role:a,rows:a|p,rowSpan:null,sandbox:null,scope:null,scoped:s,scrolling:null,seamless:a|s,selected:u|s,shape:null,size:a|p,sizes:a,span:p,spellCheck:null,src:null,srcDoc:u,srcSet:a,start:c,step:null,style:null,tabIndex:null,target:null,title:null,type:null,useMap:null,value:u|l,width:a,wmode:a,autoCapitalize:null,autoCorrect:null,itemProp:a,itemScope:a|s,itemType:a,itemID:a,itemRef:a,property:null,unselectable:a},DOMAttributeNames:{acceptCharset:"accept-charset",className:"class",htmlFor:"for",httpEquiv:"http-equiv"},DOMPropertyNames:{autoCapitalize:"autocapitalize",autoComplete:"autocomplete",autoCorrect:"autocorrect",autoFocus:"autofocus",autoPlay:"autoplay",encType:"encoding",hrefLang:"hreflang",radioGroup:"radiogroup",spellCheck:"spellcheck",srcDoc:"srcdoc",srcSet:"srcset"}};t.exports=h},{10:10,21:21}],24:[function(e,t,n){"use strict";function r(e){l(null==e.checkedLink||null==e.valueLink)}function o(e){r(e),l(null==e.value&&null==e.onChange)}function i(e){r(e),l(null==e.checked&&null==e.onChange)}function a(e){this.props.valueLink.requestChange(e.target.value)}function u(e){this.props.checkedLink.requestChange(e.target.checked)}var s=e(75),l=e(130),c={button:!0,checkbox:!0,image:!0,hidden:!0,radio:!0,reset:!0,submit:!0},p={Mixin:{propTypes:{value:function(e,t,n){return!e[t]||c[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}},getValue:function(e){return e.valueLink?(o(e),e.valueLink.value):e.value},getChecked:function(e){return e.checkedLink?(i(e),e.checkedLink.value):e.checked},getOnChange:function(e){return e.valueLink?(o(e),a):e.checkedLink?(i(e),u):e.onChange}};t.exports=p},{130:130,75:75}],25:[function(e,t,n){"use strict";function r(e){e.remove()}var o=e(29),i=e(101),a=e(113),u=e(116),s=e(130),l={trapBubbledEvent:function(e,t){s(this.isMounted());var n=a(this);s(n);var r=o.trapBubbledEvent(e,t,n);this._localEventListeners=i(this._localEventListeners,r)},componentWillUnmount:function(){this._localEventListeners&&u(this._localEventListeners,r)}};t.exports=l},{101:101,113:113,116:116,130:130,29:29}],26:[function(e,t,n){"use strict";function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var n=Object(e),r=Object.prototype.hasOwnProperty,o=1;o<arguments.length;o++){var i=arguments[o];if(null!=i){var a=Object(i);for(var u in a)r.call(a,u)&&(n[u]=a[u])}}return n}t.exports=r},{}],27:[function(e,t,n){"use strict";var r=e(130),o=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 r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},a=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},u=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},s=function(e){var t=this;r(e instanceof t),e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},l=10,c=o,p=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||c,n.poolSize||(n.poolSize=l),n.release=s,n},d={addPoolingTo:p,oneArgumentPooler:o,twoArgumentPooler:i,threeArgumentPooler:a,fiveArgumentPooler:u};t.exports=d},{130:130}],28:[function(e,t,n){"use strict";var r=(e(64),e(113)),o=(e(148),"_getDOMNodeDidWarn"),i={getDOMNode:function(){return this.constructor[o]=!0,r(this)}};t.exports=i},{113:113,148:148,64:64}],29:[function(e,t,n){"use strict";function r(e){return Object.prototype.hasOwnProperty.call(e,m)||(e[m]=f++,p[e[m]]={}),p[e[m]]}var o=e(15),i=e(17),a=e(18),u=e(58),s=e(100),l=e(26),c=e(131),p={},d=!1,f=0,h={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"},m="_reactListenersID"+String(Math.random()).slice(2),v=l({},u,{ReactEventListener:null,injection:{injectReactEventListener:function(e){e.setHandleTopLevel(v.handleTopLevel),v.ReactEventListener=e}},setEnabled:function(e){v.ReactEventListener&&v.ReactEventListener.setEnabled(e)},isEnabled:function(){return!(!v.ReactEventListener||!v.ReactEventListener.isEnabled())},listenTo:function(e,t){for(var n=t,i=r(n),u=a.registrationNameDependencies[e],s=o.topLevelTypes,l=0;l<u.length;l++){var p=u[l];i.hasOwnProperty(p)&&i[p]||(p===s.topWheel?c("wheel")?v.ReactEventListener.trapBubbledEvent(s.topWheel,"wheel",n):c("mousewheel")?v.ReactEventListener.trapBubbledEvent(s.topWheel,"mousewheel",n):v.ReactEventListener.trapBubbledEvent(s.topWheel,"DOMMouseScroll",n):p===s.topScroll?c("scroll",!0)?v.ReactEventListener.trapCapturedEvent(s.topScroll,"scroll",n):v.ReactEventListener.trapBubbledEvent(s.topScroll,"scroll",v.ReactEventListener.WINDOW_HANDLE):p===s.topFocus||p===s.topBlur?(c("focus",!0)?(v.ReactEventListener.trapCapturedEvent(s.topFocus,"focus",n), v.ReactEventListener.trapCapturedEvent(s.topBlur,"blur",n)):c("focusin")&&(v.ReactEventListener.trapBubbledEvent(s.topFocus,"focusin",n),v.ReactEventListener.trapBubbledEvent(s.topBlur,"focusout",n)),i[s.topBlur]=!0,i[s.topFocus]=!0):h.hasOwnProperty(p)&&v.ReactEventListener.trapBubbledEvent(p,h[p],n),i[p]=!0)}},trapBubbledEvent:function(e,t,n){return v.ReactEventListener.trapBubbledEvent(e,t,n)},trapCapturedEvent:function(e,t,n){return v.ReactEventListener.trapCapturedEvent(e,t,n)},ensureScrollValueMonitoring:function(){if(!d){var e=s.refreshScrollValues;v.ReactEventListener.monitorScrollValue(e),d=!0}},eventNameDispatchConfigs:i.eventNameDispatchConfigs,registrationNameModules:i.registrationNameModules,putListener:i.putListener,getListener:i.getListener,deleteListener:i.deleteListener,deleteAllListeners:i.deleteAllListeners});t.exports=v},{100:100,131:131,15:15,17:17,18:18,26:26,58:58}],30:[function(e,t,n){"use strict";var r=e(77),o=e(114),i=e(129),a=e(144),u={instantiateChildren:function(e,t,n){var r=o(e);for(var a in r)if(r.hasOwnProperty(a)){var u=r[a],s=i(u,null);r[a]=s}return r},updateChildren:function(e,t,n,u){var s=o(t);if(!s&&!e)return null;var l;for(l in s)if(s.hasOwnProperty(l)){var c=e&&e[l],p=c&&c._currentElement,d=s[l];if(a(p,d))r.receiveComponent(c,d,n,u),s[l]=c;else{c&&r.unmountComponent(c,l);var f=i(d,null);s[l]=f}}for(l in e)!e.hasOwnProperty(l)||s&&s.hasOwnProperty(l)||r.unmountComponent(e[l]);return s},unmountChildren:function(e){for(var t in e)if(e.hasOwnProperty(t)){var n=e[t];r.unmountComponent(n)}}};t.exports=u},{114:114,129:129,144:144,77:77}],31:[function(e,t,n){"use strict";function r(e,t){this.forEachFunction=e,this.forEachContext=t}function o(e,t,n,r){var o=e;o.forEachFunction.call(o.forEachContext,t,r)}function i(e,t,n){if(null==e)return e;var i=r.getPooled(t,n);f(e,o,i),r.release(i)}function a(e,t,n){this.mapResult=e,this.mapFunction=t,this.mapContext=n}function u(e,t,n,r){var o=e,i=o.mapResult,a=void 0===i[n];if(a){var u=o.mapFunction.call(o.mapContext,t,r);i[n]=u}}function s(e,t,n){if(null==e)return e;var r={},o=a.getPooled(r,t,n);return f(e,u,o),a.release(o),d.create(r)}function l(e,t,n,r){return null}function c(e,t){return f(e,l,null)}var p=e(27),d=e(60),f=e(146),h=(e(148),p.twoArgumentPooler),m=p.threeArgumentPooler;p.addPoolingTo(r,h),p.addPoolingTo(a,m);var v={forEach:i,map:s,count:c};t.exports=v},{146:146,148:148,27:27,60:60}],32:[function(e,t,n){"use strict";function r(e,t){var n=D.hasOwnProperty(t)?D[t]:null;I.hasOwnProperty(t)&&y(n===_.OVERRIDE_BASE),e.hasOwnProperty(t)&&y(n===_.DEFINE_MANY||n===_.DEFINE_MANY_MERGED)}function o(e,t){if(t){y("function"!=typeof t),y(!d.isValidElement(t));var n=e.prototype;t.hasOwnProperty(b)&&M.mixins(e,t.mixins);for(var o in t)if(t.hasOwnProperty(o)&&o!==b){var i=t[o];if(r(n,o),M.hasOwnProperty(o))M[o](e,i);else{var a=D.hasOwnProperty(o),l=n.hasOwnProperty(o),c="function"==typeof i,p=c&&!a&&!l;if(p)n.__reactAutoBindMap||(n.__reactAutoBindMap={}),n.__reactAutoBindMap[o]=i,n[o]=i;else if(l){var f=D[o];y(a&&(f===_.DEFINE_MANY_MERGED||f===_.DEFINE_MANY)),f===_.DEFINE_MANY_MERGED?n[o]=u(n[o],i):f===_.DEFINE_MANY&&(n[o]=s(n[o],i))}else n[o]=i}}}}function i(e,t){if(t)for(var n in t){var r=t[n];if(t.hasOwnProperty(n)){var o=n in M;y(!o);var i=n in e;y(!i),e[n]=r}}}function a(e,t){y(e&&t&&"object"==typeof e&&"object"==typeof t);for(var n in t)t.hasOwnProperty(n)&&(y(void 0===e[n]),e[n]=t[n]);return e}function u(e,t){return function(){var n=e.apply(this,arguments),r=t.apply(this,arguments);if(null==n)return r;if(null==r)return n;var o={};return a(o,n),a(o,r),o}}function s(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}function l(e,t){var n=t.bind(e);return n}function c(e){for(var t in e.__reactAutoBindMap)if(e.__reactAutoBindMap.hasOwnProperty(t)){var n=e.__reactAutoBindMap[t];e[t]=l(e,f.guard(n,e.constructor.displayName+"."+t))}}var p=e(33),d=(e(38),e(54)),f=e(57),h=e(64),m=e(65),v=(e(74),e(73),e(82)),g=e(26),y=e(130),C=e(135),E=e(136),b=(e(148),E({mixins:null})),_=C({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null,DEFINE_MANY_MERGED:null}),x=[],D={mixins:_.DEFINE_MANY,statics:_.DEFINE_MANY,propTypes:_.DEFINE_MANY,contextTypes:_.DEFINE_MANY,childContextTypes:_.DEFINE_MANY,getDefaultProps:_.DEFINE_MANY_MERGED,getInitialState:_.DEFINE_MANY_MERGED,getChildContext:_.DEFINE_MANY_MERGED,render:_.DEFINE_ONCE,componentWillMount:_.DEFINE_MANY,componentDidMount:_.DEFINE_MANY,componentWillReceiveProps:_.DEFINE_MANY,shouldComponentUpdate:_.DEFINE_ONCE,componentWillUpdate:_.DEFINE_MANY,componentDidUpdate:_.DEFINE_MANY,componentWillUnmount:_.DEFINE_MANY,updateComponent:_.OVERRIDE_BASE},M={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},childContextTypes:function(e,t){e.childContextTypes=g({},e.childContextTypes,t)},contextTypes:function(e,t){e.contextTypes=g({},e.contextTypes,t)},getDefaultProps:function(e,t){e.getDefaultProps?e.getDefaultProps=u(e.getDefaultProps,t):e.getDefaultProps=t},propTypes:function(e,t){e.propTypes=g({},e.propTypes,t)},statics:function(e,t){i(e,t)}},I={replaceState:function(e,t){v.enqueueReplaceState(this,e),t&&v.enqueueCallback(this,t)},isMounted:function(){var e=h.get(this);return e?e!==m.currentlyMountingInstance:!1},setProps:function(e,t){v.enqueueSetProps(this,e),t&&v.enqueueCallback(this,t)},replaceProps:function(e,t){v.enqueueReplaceProps(this,e),t&&v.enqueueCallback(this,t)}},N=function(){};g(N.prototype,p.prototype,I);var T={createClass:function(e){var t=function(e,t){this.__reactAutoBindMap&&c(this),this.props=e,this.context=t,this.state=null;var n=this.getInitialState?this.getInitialState():null;y("object"==typeof n&&!Array.isArray(n)),this.state=n};t.prototype=new N,t.prototype.constructor=t,x.forEach(o.bind(null,t)),o(t,e),t.getDefaultProps&&(t.defaultProps=t.getDefaultProps()),y(t.prototype.render);for(var n in D)t.prototype[n]||(t.prototype[n]=null);return t.type=t,t},injection:{injectMixin:function(e){x.push(e)}}};t.exports=T},{130:130,135:135,136:136,148:148,26:26,33:33,38:38,54:54,57:57,64:64,65:65,73:73,74:74,82:82}],33:[function(e,t,n){"use strict";function r(e,t){this.props=e,this.context=t}var o=e(82),i=e(130);e(148);r.prototype.setState=function(e,t){i("object"==typeof e||"function"==typeof e||null==e),o.enqueueSetState(this,e),t&&o.enqueueCallback(this,t)},r.prototype.forceUpdate=function(e){o.enqueueForceUpdate(this),e&&o.enqueueCallback(this,e)};t.exports=r},{130:130,148:148,82:82}],34:[function(e,t,n){"use strict";var r=e(43),o=e(67),i={processChildrenUpdates:r.dangerouslyProcessChildrenUpdates,replaceNodeWithMarkupByID:r.dangerouslyReplaceNodeWithMarkupByID,unmountIDFromEnvironment:function(e){o.purgeID(e)}};t.exports=i},{43:43,67:67}],35:[function(e,t,n){"use strict";var r=e(130),o=!1,i={unmountIDFromEnvironment:null,replaceNodeWithMarkupByID:null,processChildrenUpdates:null,injection:{injectEnvironment:function(e){r(!o),i.unmountIDFromEnvironment=e.unmountIDFromEnvironment,i.replaceNodeWithMarkupByID=e.replaceNodeWithMarkupByID,i.processChildrenUpdates=e.processChildrenUpdates,o=!0}}};t.exports=i},{130:130}],36:[function(e,t,n){"use strict";function r(e){var t=e._currentElement._owner||null;if(t){var n=t.getName();if(n)return" Check the render method of `"+n+"`."}return""}var o=e(35),i=e(37),a=e(38),u=e(54),s=(e(55),e(64)),l=e(65),c=e(70),p=e(72),d=e(74),f=(e(73),e(77)),h=e(83),m=e(26),v=e(111),g=e(130),y=e(144),C=(e(148),1),E={construct:function(e){this._currentElement=e,this._rootNodeID=null,this._instance=null,this._pendingElement=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._renderedComponent=null,this._context=null,this._mountOrder=0,this._isTopLevel=!1,this._pendingCallbacks=null},mountComponent:function(e,t,n){this._context=n,this._mountOrder=C++,this._rootNodeID=e;var r=this._processProps(this._currentElement.props),o=this._processContext(n),i=c.getComponentClassForElement(this._currentElement),a=new i(r,o);a.props=r,a.context=o,a.refs=v,this._instance=a,s.set(a,this);var u=a.state;void 0===u&&(a.state=u=null),g("object"==typeof u&&!Array.isArray(u)),this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1;var p,d=l.currentlyMountingInstance;l.currentlyMountingInstance=this;try{a.componentWillMount&&(a.componentWillMount(),this._pendingStateQueue&&(a.state=this._processPendingState(a.props,a.context))),p=this._renderValidatedComponent()}finally{l.currentlyMountingInstance=d}this._renderedComponent=this._instantiateReactComponent(p,this._currentElement.type);var h=f.mountComponent(this._renderedComponent,e,t,this._processChildContext(n));return a.componentDidMount&&t.getReactMountReady().enqueue(a.componentDidMount,a),h},unmountComponent:function(){var e=this._instance;if(e.componentWillUnmount){var t=l.currentlyUnmountingInstance;l.currentlyUnmountingInstance=this;try{e.componentWillUnmount()}finally{l.currentlyUnmountingInstance=t}}f.unmountComponent(this._renderedComponent),this._renderedComponent=null,this._pendingStateQueue=null,this._pendingReplaceState=!1,this._pendingForceUpdate=!1,this._pendingCallbacks=null,this._pendingElement=null,this._context=null,this._rootNodeID=null,s.remove(e)},_setPropsInternal:function(e,t){var n=this._pendingElement||this._currentElement;this._pendingElement=u.cloneAndReplaceProps(n,m({},n.props,e)),h.enqueueUpdate(this,t)},_maskContext:function(e){var t=null;if("string"==typeof this._currentElement.type)return v;var n=this._currentElement.type.contextTypes;if(!n)return v;t={};for(var r in n)t[r]=e[r];return t},_processContext:function(e){var t=this._maskContext(e);return t},_processChildContext:function(e){var t=this._instance,n=t.getChildContext&&t.getChildContext();if(n){g("object"==typeof t.constructor.childContextTypes);for(var r in n)g(r in t.constructor.childContextTypes);return m({},e,n)}return e},_processProps:function(e){return e},_checkPropTypes:function(e,t,n){var o=this.getName();for(var i in e)if(e.hasOwnProperty(i)){var a;try{g("function"==typeof e[i]),a=e[i](t,i,o,n)}catch(u){a=u}a instanceof Error&&(r(this),n===d.prop)}},receiveComponent:function(e,t,n){var r=this._currentElement,o=this._context;this._pendingElement=null,this.updateComponent(t,r,e,o,n)},performUpdateIfNecessary:function(e){null!=this._pendingElement&&f.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,t,n,r,o){var i=this._instance,a=i.context,u=i.props;t!==n&&(a=this._processContext(o),u=this._processProps(n.props),i.componentWillReceiveProps&&i.componentWillReceiveProps(u,a));var s=this._processPendingState(u,a),l=this._pendingForceUpdate||!i.shouldComponentUpdate||i.shouldComponentUpdate(u,s,a);l?(this._pendingForceUpdate=!1,this._performComponentUpdate(n,u,s,a,e,o)):(this._currentElement=n,this._context=o,i.props=u,i.state=s,i.context=a)},_processPendingState:function(e,t){var n=this._instance,r=this._pendingStateQueue,o=this._pendingReplaceState;if(this._pendingReplaceState=!1,this._pendingStateQueue=null,!r)return n.state;if(o&&1===r.length)return r[0];for(var i=m({},o?r[0]:n.state),a=o?1:0;a<r.length;a++){var u=r[a];m(i,"function"==typeof u?u.call(n,i,e,t):u)}return i},_performComponentUpdate:function(e,t,n,r,o,i){var a=this._instance,u=a.props,s=a.state,l=a.context;a.componentWillUpdate&&a.componentWillUpdate(t,n,r),this._currentElement=e,this._context=i,a.props=t,a.state=n,a.context=r,this._updateRenderedComponent(o,i),a.componentDidUpdate&&o.getReactMountReady().enqueue(a.componentDidUpdate.bind(a,u,s,l),a)},_updateRenderedComponent:function(e,t){var n=this._renderedComponent,r=n._currentElement,o=this._renderValidatedComponent();if(y(r,o))f.receiveComponent(n,o,e,this._processChildContext(t));else{var i=this._rootNodeID,a=n._rootNodeID;f.unmountComponent(n),this._renderedComponent=this._instantiateReactComponent(o,this._currentElement.type);var u=f.mountComponent(this._renderedComponent,i,e,this._processChildContext(t));this._replaceNodeWithMarkupByID(a,u)}},_replaceNodeWithMarkupByID:function(e,t){o.replaceNodeWithMarkupByID(e,t)},_renderValidatedComponentWithoutOwnerOrContext:function(){var e=this._instance,t=e.render();return t},_renderValidatedComponent:function(){var e,t=i.current;i.current=this._processChildContext(this._currentElement._context),a.current=this;try{e=this._renderValidatedComponentWithoutOwnerOrContext()}finally{i.current=t,a.current=null}return g(null===e||e===!1||u.isValidElement(e)),e},attachRef:function(e,t){var n=this.getPublicInstance(),r=n.refs===v?n.refs={}:n.refs;r[e]=t.getPublicInstance()},detachRef:function(e){var t=this.getPublicInstance().refs;delete t[e]},getName:function(){var e=this._currentElement.type,t=this._instance&&this._instance.constructor;return e.displayName||t&&t.displayName||e.name||t&&t.name||null},getPublicInstance:function(){return this._instance},_instantiateReactComponent:null};p.measureMethods(E,"ReactCompositeComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent",_renderValidatedComponent:"_renderValidatedComponent"});var b={Mixin:E};t.exports=b},{111:111,130:130,144:144,148:148,26:26,35:35,37:37,38:38,54:54,55:55,64:64,65:65,70:70,72:72,73:73,74:74,77:77,83:83}],37:[function(e,t,n){"use strict";var r=e(111),o={current:r};t.exports=o},{111:111}],38:[function(e,t,n){"use strict";var r={current:null};t.exports=r},{}],39:[function(e,t,n){"use strict";function r(e){return o.createFactory(e)}var o=e(54),i=(e(55),e(137)),a=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",hgroup:"hgroup",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",clipPath:"clipPath",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"},r);t.exports=a},{137:137,54:54,55:55}],40:[function(e,t,n){"use strict";var r=e(2),o=e(28),i=e(32),a=e(54),u=e(135),s=a.createFactory("button"),l=u({onClick:!0,onDoubleClick:!0,onMouseDown:!0,onMouseMove:!0,onMouseUp:!0,onClickCapture:!0,onDoubleClickCapture:!0,onMouseDownCapture:!0,onMouseMoveCapture:!0,onMouseUpCapture:!0}),c=i.createClass({displayName:"ReactDOMButton",tagName:"BUTTON",mixins:[r,o],render:function(){var e={};for(var t in this.props)!this.props.hasOwnProperty(t)||this.props.disabled&&l[t]||(e[t]=this.props[t]);return s(e,this.props.children)}});t.exports=c},{135:135,2:2,28:28,32:32,54:54}],41:[function(e,t,n){"use strict";function r(e,t){t&&(null!=t.dangerouslySetInnerHTML&&(C(null==t.children),C("object"==typeof t.dangerouslySetInnerHTML&&"__html"in t.dangerouslySetInnerHTML)),C(null==t.style||"object"==typeof t.style))}function o(e,t,n,r){var o=h.findReactContainerForID(e);if(o){var a=o.nodeType===I?o.ownerDocument:o;_(t,a)}r.getReactMountReady().enqueue(i,{id:e,registrationName:t,listener:n})}function i(){var e=this;d.putListener(e.id,e.registrationName,e.listener)}function a(e){O.call(w,e)||(C(P.test(e)),w[e]=!0)}function u(e,t){return e}function s(e){a(e),this._tag=e,this._renderedChildren=null,this._previousStyle=null,this._previousStyleCopy=null,this._rootNodeID=null}var l=e(5),c=e(10),p=e(11),d=e(29),f=e(34),h=e(67),m=e(68),v=e(72),g=e(26),y=e(112),C=e(130),E=(e(131),e(136)),b=(e(143),e(147),e(148),d.deleteListener),_=d.listenTo,x=d.registrationNameModules,D={string:!0,number:!0},M=E({style:null}),I=1,N=null,T={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},R={listing:!0,pre:!0,textarea:!0},P=(g({menuitem:!0},T),/^[a-zA-Z][a-zA-Z:_\.\-\d]*$/),w={},O={}.hasOwnProperty;s.displayName="ReactDOMComponent",s.Mixin={construct:function(e){this._currentElement=e},mountComponent:function(e,t,n){this._rootNodeID=e,r(this,this._currentElement.props);var o=this._createOpenTagMarkupAndPutListeners(t),i=this._createContentMarkup(t,n);return!i&&T[this._tag]?o+"/>":o+">"+i+"</"+this._tag+">"},_createOpenTagMarkupAndPutListeners:function(e){var t=this._currentElement.props,n="<"+this._tag;for(var r in t)if(t.hasOwnProperty(r)){var i=t[r];if(null!=i)if(x.hasOwnProperty(r))o(this._rootNodeID,r,i,e);else{r===M&&(i&&(i=this._previousStyleCopy=g({},t.style)),i=l.createMarkupForStyles(i));var a=p.createMarkupForProperty(r,i);a&&(n+=" "+a)}}if(e.renderToStaticMarkup)return n;var u=p.createMarkupForID(this._rootNodeID);return n+" "+u},_createContentMarkup:function(e,t){var n="",r=this._currentElement.props,o=r.dangerouslySetInnerHTML;if(null!=o)null!=o.__html&&(n=o.__html);else{var i=D[typeof r.children]?r.children:null,a=null!=i?null:r.children;if(null!=i)n=y(i);else if(null!=a){var s=this.mountChildren(a,e,u(t,this._tag));n=s.join("")}}return R[this._tag]&&"\n"===n.charAt(0)?"\n"+n:n},receiveComponent:function(e,t,n){var r=this._currentElement;this._currentElement=e,this.updateComponent(t,r,e,n)},updateComponent:function(e,t,n,o){r(this,this._currentElement.props),this._updateDOMProperties(t.props,e),this._updateDOMChildren(t.props,e,u(o,this._tag))},_updateDOMProperties:function(e,t){var n,r,i,a=this._currentElement.props;for(n in e)if(!a.hasOwnProperty(n)&&e.hasOwnProperty(n))if(n===M){var u=this._previousStyleCopy;for(r in u)u.hasOwnProperty(r)&&(i=i||{},i[r]="");this._previousStyleCopy=null}else x.hasOwnProperty(n)?e[n]&&b(this._rootNodeID,n):(c.isStandardName[n]||c.isCustomAttribute(n))&&N.deletePropertyByID(this._rootNodeID,n);for(n in a){var s=a[n],l=n===M?this._previousStyleCopy:e[n];if(a.hasOwnProperty(n)&&s!==l)if(n===M)if(s?s=this._previousStyleCopy=g({},s):this._previousStyleCopy=null,l){for(r in l)!l.hasOwnProperty(r)||s&&s.hasOwnProperty(r)||(i=i||{},i[r]="");for(r in s)s.hasOwnProperty(r)&&l[r]!==s[r]&&(i=i||{},i[r]=s[r])}else i=s;else x.hasOwnProperty(n)?s?o(this._rootNodeID,n,s,t):l&&b(this._rootNodeID,n):(c.isStandardName[n]||c.isCustomAttribute(n))&&N.updatePropertyByID(this._rootNodeID,n,s)}i&&N.updateStylesByID(this._rootNodeID,i)},_updateDOMChildren:function(e,t,n){var r=this._currentElement.props,o=D[typeof e.children]?e.children:null,i=D[typeof r.children]?r.children:null,a=e.dangerouslySetInnerHTML&&e.dangerouslySetInnerHTML.__html,u=r.dangerouslySetInnerHTML&&r.dangerouslySetInnerHTML.__html,s=null!=o?null:e.children,l=null!=i?null:r.children,c=null!=o||null!=a,p=null!=i||null!=u;null!=s&&null==l?this.updateChildren(null,t,n):c&&!p&&this.updateTextContent(""),null!=i?o!==i&&this.updateTextContent(""+i):null!=u?a!==u&&N.updateInnerHTMLByID(this._rootNodeID,u):null!=l&&this.updateChildren(l,t,n)},unmountComponent:function(){this.unmountChildren(),d.deleteAllListeners(this._rootNodeID),f.unmountIDFromEnvironment(this._rootNodeID),this._rootNodeID=null}},v.measureMethods(s,"ReactDOMComponent",{mountComponent:"mountComponent",updateComponent:"updateComponent"}),g(s.prototype,s.Mixin,m.Mixin),s.injection={injectIDOperations:function(e){s.BackendIDOperations=N=e}},t.exports=s},{10:10,11:11,112:112,130:130,131:131,136:136,143:143,147:147,148:148,26:26,29:29,34:34,5:5,67:67,68:68,72:72}],42:[function(e,t,n){"use strict";var r=e(15),o=e(25),i=e(28),a=e(32),u=e(54),s=u.createFactory("form"),l=a.createClass({displayName:"ReactDOMForm",tagName:"FORM",mixins:[i,o],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topReset,"reset"),this.trapBubbledEvent(r.topLevelTypes.topSubmit,"submit")}});t.exports=l},{15:15,25:25,28:28,32:32,54:54}],43:[function(e,t,n){"use strict";var r=e(5),o=e(9),i=e(11),a=e(67),u=e(72),s=e(130),l=e(141),c={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},p={updatePropertyByID:function(e,t,n){var r=a.getNode(e);s(!c.hasOwnProperty(t)),null!=n?i.setValueForProperty(r,t,n):i.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=a.getNode(e);s(!c.hasOwnProperty(t)),i.deleteValueForProperty(r,t,n)},updateStylesByID:function(e,t){var n=a.getNode(e);r.setValueForStyles(n,t)},updateInnerHTMLByID:function(e,t){var n=a.getNode(e);l(n,t)},updateTextContentByID:function(e,t){var n=a.getNode(e);o.updateTextContent(n,t)},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=a.getNode(e);o.dangerouslyReplaceNodeWithMarkup(n,t)},dangerouslyProcessChildrenUpdates:function(e,t){for(var n=0;n<e.length;n++)e[n].parentNode=a.getNode(e[n].parentID);o.processUpdates(e,t)}};u.measureMethods(p,"ReactDOMIDOperations",{updatePropertyByID:"updatePropertyByID",deletePropertyByID:"deletePropertyByID",updateStylesByID:"updateStylesByID",updateInnerHTMLByID:"updateInnerHTMLByID",updateTextContentByID:"updateTextContentByID",dangerouslyReplaceNodeWithMarkupByID:"dangerouslyReplaceNodeWithMarkupByID",dangerouslyProcessChildrenUpdates:"dangerouslyProcessChildrenUpdates"}),t.exports=p},{11:11,130:130,141:141,5:5,67:67,72:72,9:9}],44:[function(e,t,n){"use strict";var r=e(15),o=e(25),i=e(28),a=e(32),u=e(54),s=u.createFactory("iframe"),l=a.createClass({displayName:"ReactDOMIframe",tagName:"IFRAME",mixins:[i,o],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load")}});t.exports=l},{15:15,25:25,28:28,32:32,54:54}],45:[function(e,t,n){"use strict";var r=e(15),o=e(25),i=e(28),a=e(32),u=e(54),s=u.createFactory("img"),l=a.createClass({displayName:"ReactDOMImg",tagName:"IMG",mixins:[i,o],render:function(){return s(this.props)},componentDidMount:function(){this.trapBubbledEvent(r.topLevelTypes.topLoad,"load"),this.trapBubbledEvent(r.topLevelTypes.topError,"error")}});t.exports=l},{15:15,25:25,28:28,32:32,54:54}],46:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var o=e(2),i=e(11),a=e(24),u=e(28),s=e(32),l=e(54),c=e(67),p=e(83),d=e(26),f=e(113),h=e(130),m=l.createFactory("input"),v={},g=s.createClass({displayName:"ReactDOMInput",tagName:"INPUT",mixins:[o,a.Mixin,u],getInitialState:function(){var e=this.props.defaultValue;return{initialChecked:this.props.defaultChecked||!1,initialValue:null!=e?e:null}},render:function(){var e=d({},this.props);e.defaultChecked=null,e.defaultValue=null;var t=a.getValue(this.props);e.value=null!=t?t:this.state.initialValue;var n=a.getChecked(this.props);return e.checked=null!=n?n:this.state.initialChecked,e.onChange=this._handleChange,m(e,this.props.children)},componentDidMount:function(){var e=c.getID(f(this));v[e]=this},componentWillUnmount:function(){var e=f(this),t=c.getID(e);delete v[t]},componentDidUpdate:function(e,t,n){var r=f(this);null!=this.props.checked&&i.setValueForProperty(r,"checked",this.props.checked||!1);var o=a.getValue(this.props);null!=o&&i.setValueForProperty(r,"value",""+o)},_handleChange:function(e){var t,n=a.getOnChange(this.props);n&&(t=n.call(this,e)),p.asap(r,this);var o=this.props.name;if("radio"===this.props.type&&null!=o){for(var i=f(this),u=i;u.parentNode;)u=u.parentNode;for(var s=u.querySelectorAll("input[name="+JSON.stringify(""+o)+'][type="radio"]'),l=0;l<s.length;l++){var d=s[l];if(d!==i&&d.form===i.form){var m=c.getID(d);h(m);var g=v[m];h(g),p.asap(r,g)}}}return t}});t.exports=g},{11:11,113:113,130:130,2:2,24:24,26:26,28:28,32:32,54:54,67:67,83:83}],47:[function(e,t,n){"use strict";var r=e(28),o=e(32),i=e(48),a=e(54),u=e(64),s=e(75),l=e(26),c=(e(148),a.createFactory("option")),p=i.valueContextKey,d=o.createClass({displayName:"ReactDOMOption",tagName:"OPTION",mixins:[r],getInitialState:function(){return{selected:null}},contextTypes:function(){var e={};return e[p]=s.any,e}(),componentWillMount:function(){var e=u.get(this)._context,t=e[p];if(null!=t){var n=!1;if(Array.isArray(t)){for(var r=0;r<t.length;r++)if(""+t[r]==""+this.props.value){n=!0;break}}else n=""+t==""+this.props.value;this.setState({selected:n})}},render:function(){var e=this.props;return null!=this.state.selected&&(e=l({},e,{selected:this.state.selected})),c(e,this.props.children)}});t.exports=d},{148:148,26:26,28:28,32:32,48:48,54:54,64:64,75:75}],48:[function(e,t,n){"use strict";function r(){if(this._pendingUpdate){this._pendingUpdate=!1;var e=u.getValue(this.props);null!=e&&this.isMounted()&&i(this,e)}}function o(e,t,n){if(null==e[t])return null;if(e.multiple){if(!Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be an array if `multiple` is true.")}else if(Array.isArray(e[t]))return new Error("The `"+t+"` prop supplied to <select> must be a scalar value if `multiple` is false.")}function i(e,t){var n,r,o=h(e).options;if(e.props.multiple){for(n={},r=0;r<t.length;r++)n[""+t[r]]=!0;for(r=0;r<o.length;r++){var i=n.hasOwnProperty(o[r].value);o[r].selected!==i&&(o[r].selected=i)}}else{for(n=""+t,r=0;r<o.length;r++)if(o[r].value===n)return void(o[r].selected=!0);o.length&&(o[0].selected=!0)}}var a=e(2),u=e(24),s=e(28),l=e(32),c=e(54),p=e(83),d=e(75),f=e(26),h=e(113),m=c.createFactory("select"),v="__ReactDOMSelect_value$"+Math.random().toString(36).slice(2),g=l.createClass({displayName:"ReactDOMSelect",tagName:"SELECT",mixins:[a,u.Mixin,s],statics:{valueContextKey:v},propTypes:{defaultValue:o,value:o},getInitialState:function(){var e=u.getValue(this.props);return null!=e?{initialValue:e}:{initialValue:this.props.defaultValue}},childContextTypes:function(){var e={};return e[v]=d.any,e}(),getChildContext:function(){var e={};return e[v]=this.state.initialValue,e},render:function(){var e=f({},this.props);return e.onChange=this._handleChange,e.value=null,m(e,this.props.children)},componentWillMount:function(){this._pendingUpdate=!1},componentWillReceiveProps:function(e){this.setState({initialValue:null})},componentDidUpdate:function(e){var t=u.getValue(this.props);null!=t?(this._pendingUpdate=!1,i(this,t)):!e.multiple!=!this.props.multiple&&(null!=this.props.defaultValue?i(this,this.props.defaultValue):i(this,this.props.multiple?[]:""))},_handleChange:function(e){var t,n=u.getOnChange(this.props);return n&&(t=n.call(this,e)),this._pendingUpdate=!0,p.asap(r,this),t}});t.exports=g},{113:113,2:2,24:24,26:26,28:28,32:32,54:54,75:75,83:83}],49:[function(e,t,n){"use strict";function r(e,t,n,r){return e===n&&t===r}function o(e){var t=document.selection,n=t.createRange(),r=n.text.length,o=n.duplicate();o.moveToElementText(e),o.setEndPoint("EndToStart",n);var i=o.text.length,a=i+r;return{start:i,end:a}}function i(e){var t=window.getSelection&&window.getSelection();if(!t||0===t.rangeCount)return null;var n=t.anchorNode,o=t.anchorOffset,i=t.focusNode,a=t.focusOffset,u=t.getRangeAt(0),s=r(t.anchorNode,t.anchorOffset,t.focusNode,t.focusOffset),l=s?0:u.toString().length,c=u.cloneRange();c.selectNodeContents(e),c.setEnd(u.startContainer,u.startOffset);var p=r(c.startContainer,c.startOffset,c.endContainer,c.endOffset),d=p?0:c.toString().length,f=d+l,h=document.createRange();h.setStart(n,o),h.setEnd(i,a);var m=h.collapsed;return{start:m?f:d,end:m?d:f}}function a(e,t){var n,r,o=document.selection.createRange().duplicate();"undefined"==typeof t.end?(n=t.start,r=n):t.start>t.end?(n=t.end,r=t.start):(n=t.start,r=t.end),o.moveToElementText(e),o.moveStart("character",n),o.setEndPoint("EndToStart",o),o.moveEnd("character",r-n),o.select()}function u(e,t){if(window.getSelection){var n=window.getSelection(),r=e[c()].length,o=Math.min(t.start,r),i="undefined"==typeof t.end?o:Math.min(t.end,r);if(!n.extend&&o>i){var a=i;i=o,o=a}var u=l(e,o),s=l(e,i);if(u&&s){var p=document.createRange();p.setStart(u.node,u.offset),n.removeAllRanges(),o>i?(n.addRange(p),n.extend(s.node,s.offset)):(p.setEnd(s.node,s.offset),n.addRange(p))}}}var s=e(21),l=e(124),c=e(125),p=s.canUseDOM&&"selection"in document&&!("getSelection"in window),d={getOffsets:p?o:i,setOffsets:p?a:u};t.exports=d},{124:124,125:125,21:21}],50:[function(e,t,n){"use strict";var r=e(11),o=e(34),i=e(41),a=e(26),u=e(112),s=(e(147),function(e){});a(s.prototype,{construct:function(e){this._currentElement=e,this._stringText=""+e,this._rootNodeID=null,this._mountIndex=0},mountComponent:function(e,t,n){this._rootNodeID=e;var o=u(this._stringText);return t.renderToStaticMarkup?o:"<span "+r.createMarkupForID(e)+">"+o+"</span>"},receiveComponent:function(e,t){if(e!==this._currentElement){this._currentElement=e;var n=""+e;n!==this._stringText&&(this._stringText=n,i.BackendIDOperations.updateTextContentByID(this._rootNodeID,n))}},unmountComponent:function(){o.unmountIDFromEnvironment(this._rootNodeID)}}),t.exports=s},{11:11,112:112,147:147,26:26,34:34,41:41}],51:[function(e,t,n){"use strict";function r(){this.isMounted()&&this.forceUpdate()}var o=e(2),i=e(11),a=e(24),u=e(28),s=e(32),l=e(54),c=e(83),p=e(26),d=e(113),f=e(130),h=(e(148),l.createFactory("textarea")),m=s.createClass({displayName:"ReactDOMTextarea",tagName:"TEXTAREA",mixins:[o,a.Mixin,u],getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;null!=t&&(f(null==e),Array.isArray(t)&&(f(t.length<=1),t=t[0]),e=""+t),null==e&&(e="");var n=a.getValue(this.props);return{initialValue:""+(null!=n?n:e)}},render:function(){var e=p({},this.props);return f(null==e.dangerouslySetInnerHTML),e.defaultValue=null,e.value=null,e.onChange=this._handleChange,h(e,this.state.initialValue)},componentDidUpdate:function(e,t,n){var r=a.getValue(this.props);if(null!=r){var o=d(this);i.setValueForProperty(o,"value",""+r)}},_handleChange:function(e){var t,n=a.getOnChange(this.props);return n&&(t=n.call(this,e)),c.asap(r,this),t}});t.exports=m},{11:11,113:113,130:130,148:148,2:2,24:24,26:26,28:28,32:32,54:54,83:83}],52:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction()}var o=e(83),i=e(99),a=e(26),u=e(110),s={initialize:u,close:function(){d.isBatchingUpdates=!1}},l={initialize:u,close:o.flushBatchedUpdates.bind(o)},c=[l,s];a(r.prototype,i.Mixin,{getTransactionWrappers:function(){return c}});var p=new r,d={isBatchingUpdates:!1,batchedUpdates:function(e,t,n,r,o,i){var a=d.isBatchingUpdates;d.isBatchingUpdates=!0,a?e(t,n,r,o,i):p.perform(e,null,t,n,r,o,i)}};t.exports=d},{110:110,26:26,83:83,99:99}],53:[function(e,t,n){"use strict";function r(e){return f.createClass({tagName:e.toUpperCase(),render:function(){var t=w.get(this);return new N(e,null,null,t._currentElement._owner,null,this.props)}})}function o(){R.EventEmitter.injectReactEventListener(T),R.EventPluginHub.injectEventPluginOrder(s),R.EventPluginHub.injectInstanceHandle(P),R.EventPluginHub.injectMount(O),R.EventPluginHub.injectEventPluginsByName({SimpleEventPlugin:U,EnterLeaveEventPlugin:l,ChangeEventPlugin:a,SelectEventPlugin:k,BeforeInputEventPlugin:i }),R.NativeComponent.injectGenericComponentClass(v),R.NativeComponent.injectTextComponentClass(I),R.NativeComponent.injectAutoWrapper(r),R.Class.injectMixin(d),R.NativeComponent.injectComponentClasses({button:g,form:y,iframe:b,img:C,input:_,option:x,select:D,textarea:M,html:F("html"),head:F("head"),body:F("body")}),R.DOMProperty.injectDOMPropertyConfig(p),R.DOMProperty.injectDOMPropertyConfig(L),R.EmptyComponent.injectEmptyComponent("noscript"),R.Updates.injectReconcileTransaction(S),R.Updates.injectBatchingStrategy(m),R.RootIndex.injectCreateReactRootIndex(c.canUseDOM?u.createReactRootIndex:A.createReactRootIndex),R.Component.injectEnvironment(h),R.DOMComponent.injectIDOperations(E)}var i=e(3),a=e(7),u=e(8),s=e(13),l=e(14),c=e(21),p=e(23),d=e(28),f=e(32),h=e(34),m=e(52),v=e(41),g=e(40),y=e(42),C=e(45),E=e(43),b=e(44),_=e(46),x=e(47),D=e(48),M=e(51),I=e(50),N=e(54),T=e(59),R=e(61),P=e(63),w=e(64),O=e(67),S=e(76),k=e(85),A=e(86),U=e(87),L=e(84),F=e(107);t.exports={inject:o}},{107:107,13:13,14:14,21:21,23:23,28:28,3:3,32:32,34:34,40:40,41:41,42:42,43:43,44:44,45:45,46:46,47:47,48:48,50:50,51:51,52:52,54:54,59:59,61:61,63:63,64:64,67:67,7:7,76:76,8:8,84:84,85:85,86:86,87:87}],54:[function(e,t,n){"use strict";var r=e(37),o=e(38),i=e(26),a=(e(148),{key:!0,ref:!0}),u=function(e,t,n,r,o,i){this.type=e,this.key=t,this.ref=n,this._owner=r,this.props=i};u.prototype={_isReactElement:!0},u.createElement=function(e,t,n){var i,s={},l=null,c=null;if(null!=t){c=void 0===t.ref?null:t.ref,l=void 0===t.key?null:""+t.key;for(i in t)t.hasOwnProperty(i)&&!a.hasOwnProperty(i)&&(s[i]=t[i])}var p=arguments.length-2;if(1===p)s.children=n;else if(p>1){var d=Array(p);try{Object.defineProperty(d,"_reactChildKeysValidated",{configurable:!1,enumerable:!1,writable:!0})}catch(f){}d._reactChildKeysValidated=!0;for(var h=0;p>h;h++)d[h]=arguments[h+2];s.children=d}if(e&&e.defaultProps){var m=e.defaultProps;for(i in m)"undefined"==typeof s[i]&&(s[i]=m[i])}return new u(e,l,c,o.current,r.current,s)},u.createFactory=function(e){var t=u.createElement.bind(null,e);return t.type=e,t},u.cloneAndReplaceProps=function(e,t){var n=new u(e.type,e.key,e.ref,e._owner,e._context,t);return n},u.cloneElement=function(e,t,n){var r,s=i({},e.props),l=e.key,c=e.ref,p=e._owner;if(null!=t){void 0!==t.ref&&(c=t.ref,p=o.current),void 0!==t.key&&(l=""+t.key);for(r in t)t.hasOwnProperty(r)&&!a.hasOwnProperty(r)&&(s[r]=t[r])}var d=arguments.length-2;if(1===d)s.children=n;else if(d>1){for(var f=Array(d),h=0;d>h;h++)f[h]=arguments[h+2];s.children=f}return new u(e.type,l,c,p,e._context,s)},u.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},t.exports=u},{148:148,26:26,37:37,38:38}],55:[function(e,t,n){"use strict";function r(){if(y.current){var e=y.current.getName();if(e)return" Check the render method of `"+e+"`."}return""}function o(e){var t=e&&e.getPublicInstance();if(!t)return void 0;var n=t.constructor;return n?n.displayName||n.name||void 0:void 0}function i(){var e=y.current;return e&&o(e)||void 0}function a(e,t){null==e.key&&s('Each child in an array or iterator should have a unique "key" prop.',e,t)}function u(e,t,n){D.test(e)&&s("Child objects should have non-numeric keys so ordering is preserved.",t,n)}function s(e,t,n){var r=i(),a="string"==typeof n?n:n.displayName||n.name,u=r||a,s=_[e]||(_[e]={});if(!s.hasOwnProperty(u)){s[u]=!0;var l="";if(t&&t._owner&&t._owner!==y.current){var c=o(t._owner);l=" It was passed a child from "+c+"."}}}function l(e,t){if(Array.isArray(e)){if(e._reactChildKeysValidated)return;for(var n=0;n<e.length;n++){var r=e[n];m.isValidElement(r)?a(r,t):l(r,t)}}else{if("string"==typeof e||"number"==typeof e||m.isValidElement(e))return;if(e){var o=E(e);if(o){if(o!==e.entries)for(var i,s=o.call(e);!(i=s.next()).done;)m.isValidElement(i.value)?a(i.value,t):l(i.value,t)}else if("object"==typeof e){var c=v.extractIfFragment(e);for(var p in c)c.hasOwnProperty(p)&&(u(p,c[p],t),l(c[p],t))}}}}function c(e,t,n,o){for(var i in t)if(t.hasOwnProperty(i)){var a;try{b("function"==typeof t[i]),a=t[i](n,i,e,o)}catch(u){a=u}a instanceof Error&&!(a.message in x)&&(x[a.message]=!0,r())}}function p(e,t){var n=t.type,r="string"==typeof n?n:n.displayName,o=t._owner?t._owner.getPublicInstance().constructor.displayName:null,i=e+"|"+r+"|"+o;if(!M.hasOwnProperty(i)){M[i]=!0;var a="";r&&(a=" <"+r+" />");var u="";o&&(u=" The element was created by "+o+".")}}function d(e,t){return e!==e?t!==t:0===e&&0===t?1/e===1/t:e===t}function f(e){if(e._store){var t=e._store.originalProps,n=e.props;for(var r in n)n.hasOwnProperty(r)&&(t.hasOwnProperty(r)&&d(t[r],n[r])||(p(r,e),t[r]=n[r]))}}function h(e){if("string"==typeof e.type||"function"==typeof e.type){var t=C.getComponentClassForElement(e),n=t.displayName||t.name;t.propTypes&&c(n,t.propTypes,e.props,g.prop),"function"==typeof t.getDefaultProps}}var m=e(54),v=e(60),g=e(74),y=(e(73),e(38)),C=e(70),E=e(122),b=e(130),_=(e(148),{}),x={},D=/^\d+$/,M={},I={checkAndWarnForMutatedProps:f,createElement:function(e,t,n){var r=m.createElement.apply(this,arguments);if(null==r)return r;for(var o=2;o<arguments.length;o++)l(arguments[o],e);return h(r),r},createFactory:function(e){var t=I.createElement.bind(null,e);return t.type=e,t},cloneElement:function(e,t,n){for(var r=m.cloneElement.apply(this,arguments),o=2;o<arguments.length;o++)l(arguments[o],r.type);return h(r),r}};t.exports=I},{122:122,130:130,148:148,38:38,54:54,60:60,70:70,73:73,74:74}],56:[function(e,t,n){"use strict";function r(e){c[e]=!0}function o(e){delete c[e]}function i(e){return!!c[e]}var a,u=e(54),s=e(64),l=e(130),c={},p={injectEmptyComponent:function(e){a=u.createFactory(e)}},d=function(){};d.prototype.componentDidMount=function(){var e=s.get(this);e&&r(e._rootNodeID)},d.prototype.componentWillUnmount=function(){var e=s.get(this);e&&o(e._rootNodeID)},d.prototype.render=function(){return l(a),a()};var f=u.createElement(d),h={emptyElement:f,injection:p,isNullComponentID:i};t.exports=h},{130:130,54:54,64:64}],57:[function(e,t,n){"use strict";var r={guard:function(e,t){return e}};t.exports=r},{}],58:[function(e,t,n){"use strict";function r(e){o.enqueueEvents(e),o.processEventQueue()}var o=e(17),i={handleTopLevel:function(e,t,n,i){var a=o.extractEvents(e,t,n,i);r(a)}};t.exports=i},{17:17}],59:[function(e,t,n){"use strict";function r(e){var t=p.getID(e),n=c.getReactRootIDFromNodeID(t),r=p.findReactContainerForID(n),o=p.getFirstReactDOM(r);return o}function o(e,t){this.topLevelType=e,this.nativeEvent=t,this.ancestors=[]}function i(e){for(var t=p.getFirstReactDOM(h(e.nativeEvent))||window,n=t;n;)e.ancestors.push(n),n=r(n);for(var o=0;o<e.ancestors.length;o++){t=e.ancestors[o];var i=p.getID(t)||"";v._handleTopLevel(e.topLevelType,t,i,e.nativeEvent)}}function a(e){var t=m(window);e(t)}var u=e(16),s=e(21),l=e(27),c=e(63),p=e(67),d=e(83),f=e(26),h=e(121),m=e(126);f(o.prototype,{destructor:function(){this.topLevelType=null,this.nativeEvent=null,this.ancestors.length=0}}),l.addPoolingTo(o,l.twoArgumentPooler);var v={_enabled:!0,_handleTopLevel:null,WINDOW_HANDLE:s.canUseDOM?window:null,setHandleTopLevel:function(e){v._handleTopLevel=e},setEnabled:function(e){v._enabled=!!e},isEnabled:function(){return v._enabled},trapBubbledEvent:function(e,t,n){var r=n;return r?u.listen(r,t,v.dispatchEvent.bind(null,e)):null},trapCapturedEvent:function(e,t,n){var r=n;return r?u.capture(r,t,v.dispatchEvent.bind(null,e)):null},monitorScrollValue:function(e){var t=a.bind(null,e);u.listen(window,"scroll",t)},dispatchEvent:function(e,t){if(v._enabled){var n=o.getPooled(e,t);try{d.batchedUpdates(i,n)}finally{o.release(n)}}}};t.exports=v},{121:121,126:126,16:16,21:21,26:26,27:27,63:63,67:67,83:83}],60:[function(e,t,n){"use strict";var r=(e(54),e(148),{create:function(e){return e},extract:function(e){return e},extractIfFragment:function(e){return e}});t.exports=r},{148:148,54:54}],61:[function(e,t,n){"use strict";var r=e(10),o=e(17),i=e(35),a=e(32),u=e(56),s=e(29),l=e(70),c=e(41),p=e(72),d=e(79),f=e(83),h={Component:i.injection,Class:a.injection,DOMComponent:c.injection,DOMProperty:r.injection,EmptyComponent:u.injection,EventPluginHub:o.injection,EventEmitter:s.injection,NativeComponent:l.injection,Perf:p.injection,RootIndex:d.injection,Updates:f.injection};t.exports=h},{10:10,17:17,29:29,32:32,35:35,41:41,56:56,70:70,72:72,79:79,83:83}],62:[function(e,t,n){"use strict";function r(e){return i(document.documentElement,e)}var o=e(49),i=e(105),a=e(115),u=e(117),s={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=u();return{focusedElem:e,selectionRange:s.hasSelectionCapabilities(e)?s.getSelection(e):null}},restoreSelection:function(e){var t=u(),n=e.focusedElem,o=e.selectionRange;t!==n&&r(n)&&(s.hasSelectionCapabilities(n)&&s.setSelection(n,o),a(n))},getSelection:function(e){var t;if("selectionStart"in e)t={start:e.selectionStart,end:e.selectionEnd};else if(document.selection&&"INPUT"===e.nodeName){var n=document.selection.createRange();n.parentElement()===e&&(t={start:-n.moveStart("character",-e.value.length),end:-n.moveEnd("character",-e.value.length)})}else t=o.getOffsets(e);return t||{start:0,end:0}},setSelection:function(e,t){var n=t.start,r=t.end;if("undefined"==typeof r&&(r=n),"selectionStart"in e)e.selectionStart=n,e.selectionEnd=Math.min(r,e.value.length);else if(document.selection&&"INPUT"===e.nodeName){var i=e.createTextRange();i.collapse(!0),i.moveStart("character",n),i.moveEnd("character",r-n),i.select()}else o.setOffsets(e,t)}};t.exports=s},{105:105,115:115,117:117,49:49}],63:[function(e,t,n){"use strict";function r(e){return f+e.toString(36)}function o(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)&&o(t,e.length)}function u(e){return e?e.substr(0,e.lastIndexOf(f)):""}function s(e,t){if(d(i(e)&&i(t)),d(a(e,t)),e===t)return e;var n,r=e.length+h;for(n=r;n<t.length&&!o(t,n);n++);return t.substr(0,n)}function l(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var r=0,a=0;n>=a;a++)if(o(e,a)&&o(t,a))r=a;else if(e.charAt(a)!==t.charAt(a))break;var u=e.substr(0,r);return d(i(u)),u}function c(e,t,n,r,o,i){e=e||"",t=t||"",d(e!==t);var l=a(t,e);d(l||a(e,t));for(var c=0,p=l?u:s,f=e;;f=p(f,t)){var h;if(o&&f===e||i&&f===t||(h=n(f,l,r)),h===!1||f===t)break;d(c++<m)}}var p=e(79),d=e(130),f=".",h=f.length,m=100,v={createReactRootID:function(){return r(p.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,r,o){var i=l(e,t);i!==e&&c(e,i,n,r,!1,!0),i!==t&&c(i,t,n,o,!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:l,_getNextDescendantID:s,isAncestorIDOf:a,SEPARATOR:f};t.exports=v},{130:130,79:79}],64:[function(e,t,n){"use strict";var r={remove:function(e){e._reactInternalInstance=void 0},get:function(e){return e._reactInternalInstance},has:function(e){return void 0!==e._reactInternalInstance},set:function(e,t){e._reactInternalInstance=t}};t.exports=r},{}],65:[function(e,t,n){"use strict";var r={currentlyMountingInstance:null,currentlyUnmountingInstance:null};t.exports=r},{}],66:[function(e,t,n){"use strict";var r=e(102),o={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=r(e);return e.replace(">"," "+o.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var n=t.getAttribute(o.CHECKSUM_ATTR_NAME);n=n&&parseInt(n,10);var i=r(e);return i===n}};t.exports=o},{102:102}],67:[function(e,t,n){"use strict";function r(e,t){for(var n=Math.min(e.length,t.length),r=0;n>r;r++)if(e.charAt(r)!==t.charAt(r))return r;return e.length===t.length?-1:n}function o(e){return e?e.nodeType===B?e.documentElement:e.firstChild:null}function i(e){var t=o(e);return t&&q.getID(t)}function a(e){var t=u(e);if(t)if(L.hasOwnProperty(t)){var n=L[t];n!==e&&(O(!p(n,t)),L[t]=e)}else L[t]=e;return t}function u(e){return e&&e.getAttribute&&e.getAttribute(U)||""}function s(e,t){var n=u(e);n!==t&&delete L[n],e.setAttribute(U,t),L[t]=e}function l(e){return L.hasOwnProperty(e)&&p(L[e],e)||(L[e]=q.findReactNodeByID(e)),L[e]}function c(e){var t=x.get(e)._rootNodeID;return b.isNullComponentID(t)?null:(L.hasOwnProperty(t)&&p(L[t],t)||(L[t]=q.findReactNodeByID(t)),L[t])}function p(e,t){if(e){O(u(e)===t);var n=q.findReactContainerForID(t);if(n&&P(n,e))return!0}return!1}function d(e){delete L[e]}function f(e){var t=L[e];return t&&p(t,e)?void(H=t):!1}function h(e){H=null,_.traverseAncestors(e,f);var t=H;return H=null,t}function m(e,t,n,r,o,i){var a=I.mountComponent(e,t,r,i);e._isTopLevel=!0,q._mountImageIntoNode(a,n,o)}function v(e,t,n,r,o){var i=T.ReactReconcileTransaction.getPooled();i.perform(m,null,e,t,n,i,r,o),T.ReactReconcileTransaction.release(i)}function g(e,t){for(I.unmountComponent(e),t.nodeType===B&&(t=t.documentElement);t.lastChild;)t.removeChild(t.lastChild)}var y=e(10),C=e(29),E=(e(38),e(54)),b=(e(55),e(56)),_=e(63),x=e(64),D=e(66),M=e(72),I=e(77),N=e(82),T=e(83),R=e(111),P=e(105),w=e(129),O=e(130),S=e(141),k=e(144),A=(e(147),e(148),_.SEPARATOR),U=y.ID_ATTRIBUTE_NAME,L={},F=1,B=9,V=11,j={},K={},W=[],H=null,q={_instancesByReactRootID:j,scrollMonitor:function(e,t){t()},_updateRootComponent:function(e,t,n,r){return q.scrollMonitor(n,function(){N.enqueueElementInternal(e,t),r&&N.enqueueCallbackInternal(e,r)}),e},_registerComponent:function(e,t){O(t&&(t.nodeType===F||t.nodeType===B||t.nodeType===V)),C.ensureScrollValueMonitoring();var n=q.registerContainer(t);return j[n]=e,n},_renderNewRootComponent:function(e,t,n,r){var o=w(e,null),i=q._registerComponent(o,t);return T.batchedUpdates(v,o,i,t,n,r),o},renderSubtreeIntoContainer:function(e,t,n,r){return O(null!=e&&null!=e._reactInternalInstance),q._renderSubtreeIntoContainer(e,t,n,r)},_renderSubtreeIntoContainer:function(e,t,n,r){O(E.isValidElement(t));var a=j[i(n)];if(a){var u=a._currentElement;if(k(u,t))return q._updateRootComponent(a,t,n,r).getPublicInstance();q.unmountComponentAtNode(n)}var s=o(n),l=s&&q.isRenderedByReact(s),c=l&&!a,p=q._renderNewRootComponent(t,n,c,null!=e?e._reactInternalInstance._processChildContext(e._reactInternalInstance._context):R).getPublicInstance();return r&&r.call(p),p},render:function(e,t,n){return q._renderSubtreeIntoContainer(null,e,t,n)},constructAndRenderComponent:function(e,t,n){var r=E.createElement(e,t);return q.render(r,n)},constructAndRenderComponentByID:function(e,t,n){var r=document.getElementById(n);return O(r),q.constructAndRenderComponent(e,t,r)},registerContainer:function(e){var t=i(e);return t&&(t=_.getReactRootIDFromNodeID(t)),t||(t=_.createReactRootID()),K[t]=e,t},unmountComponentAtNode:function(e){O(e&&(e.nodeType===F||e.nodeType===B||e.nodeType===V));var t=i(e),n=j[t];return n?(T.batchedUpdates(g,n,e),delete j[t],delete K[t],!0):!1},findReactContainerForID:function(e){var t=_.getReactRootIDFromNodeID(e),n=K[t];return n},findReactNodeByID:function(e){var t=q.findReactContainerForID(e);return q.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=q.getID(e);return t?t.charAt(0)===A:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(q.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){var n=W,r=0,o=h(t)||e;for(n[0]=o.firstChild,n.length=1;r<n.length;){for(var i,a=n[r++];a;){var u=q.getID(a);u?t===u?i=a:_.isAncestorIDOf(u,t)&&(n.length=r=0,n.push(a.firstChild)):n.push(a.firstChild),a=a.nextSibling}if(i)return n.length=0,i}n.length=0,O(!1)},_mountImageIntoNode:function(e,t,n){if(O(t&&(t.nodeType===F||t.nodeType===B||t.nodeType===V)),n){var i=o(t);if(D.canReuseMarkup(e,i))return;var a=i.getAttribute(D.CHECKSUM_ATTR_NAME);i.removeAttribute(D.CHECKSUM_ATTR_NAME);var u=i.outerHTML;i.setAttribute(D.CHECKSUM_ATTR_NAME,a);var s=r(e,u);" (client) "+e.substring(s-20,s+20)+"\n (server) "+u.substring(s-20,s+20),O(t.nodeType!==B)}O(t.nodeType!==B),S(t,e)},getReactRootID:i,getID:a,setID:s,getNode:l,getNodeFromInstance:c,purgeID:d};M.measureMethods(q,"ReactMount",{_renderNewRootComponent:"_renderNewRootComponent",_mountImageIntoNode:"_mountImageIntoNode"}),t.exports=q},{10:10,105:105,111:111,129:129,130:130,141:141,144:144,147:147,148:148,29:29,38:38,54:54,55:55,56:56,63:63,64:64,66:66,72:72,77:77,82:82,83:83}],68:[function(e,t,n){"use strict";function r(e,t,n){h.push({parentID:e,parentNode:null,type:c.INSERT_MARKUP,markupIndex:m.push(t)-1,textContent:null,fromIndex:null,toIndex:n})}function o(e,t,n){h.push({parentID:e,parentNode:null,type:c.MOVE_EXISTING,markupIndex:null,textContent:null,fromIndex:t,toIndex:n})}function i(e,t){h.push({parentID:e,parentNode:null,type:c.REMOVE_NODE,markupIndex:null,textContent:null,fromIndex:t,toIndex:null})}function a(e,t){h.push({parentID:e,parentNode:null,type:c.TEXT_CONTENT,markupIndex:null,textContent:t,fromIndex:null,toIndex:null})}function u(){h.length&&(l.processChildrenUpdates(h,m),s())}function s(){h.length=0,m.length=0}var l=e(35),c=e(69),p=e(77),d=e(30),f=0,h=[],m=[],v={Mixin:{mountChildren:function(e,t,n){var r=d.instantiateChildren(e,t,n);this._renderedChildren=r;var o=[],i=0;for(var a in r)if(r.hasOwnProperty(a)){var u=r[a],s=this._rootNodeID+a,l=p.mountComponent(u,s,t,n);u._mountIndex=i,o.push(l),i++}return o},updateTextContent:function(e){f++;var t=!0;try{var n=this._renderedChildren;d.unmountChildren(n);for(var r in n)n.hasOwnProperty(r)&&this._unmountChildByName(n[r],r);this.setTextContent(e),t=!1}finally{f--,f||(t?s():u())}},updateChildren:function(e,t,n){f++;var r=!0;try{this._updateChildren(e,t,n),r=!1}finally{f--,f||(r?s():u())}},_updateChildren:function(e,t,n){var r=this._renderedChildren,o=d.updateChildren(r,e,t,n);if(this._renderedChildren=o,o||r){var i,a=0,u=0;for(i in o)if(o.hasOwnProperty(i)){var s=r&&r[i],l=o[i];s===l?(this.moveChild(s,u,a),a=Math.max(s._mountIndex,a),s._mountIndex=u):(s&&(a=Math.max(s._mountIndex,a),this._unmountChildByName(s,i)),this._mountChildByNameAtIndex(l,i,u,t,n)),u++}for(i in r)!r.hasOwnProperty(i)||o&&o.hasOwnProperty(i)||this._unmountChildByName(r[i],i)}},unmountChildren:function(){var e=this._renderedChildren;d.unmountChildren(e),this._renderedChildren=null},moveChild:function(e,t,n){e._mountIndex<n&&o(this._rootNodeID,e._mountIndex,t)},createChild:function(e,t){r(this._rootNodeID,t,e._mountIndex)},removeChild:function(e){i(this._rootNodeID,e._mountIndex)},setTextContent:function(e){a(this._rootNodeID,e)},_mountChildByNameAtIndex:function(e,t,n,r,o){var i=this._rootNodeID+t,a=p.mountComponent(e,i,r,o);e._mountIndex=n,this.createChild(e,a)},_unmountChildByName:function(e,t){this.removeChild(e),e._mountIndex=null}}};t.exports=v},{30:30,35:35,69:69,77:77}],69:[function(e,t,n){"use strict";var r=e(135),o=r({INSERT_MARKUP:null,MOVE_EXISTING:null,REMOVE_NODE:null,TEXT_CONTENT:null});t.exports=o},{135:135}],70:[function(e,t,n){"use strict";function r(e){if("function"==typeof e.type)return e.type;var t=e.type,n=p[t];return null==n&&(p[t]=n=l(t)),n}function o(e){return s(c),new c(e.type,e.props)}function i(e){return new d(e)}function a(e){return e instanceof d}var u=e(26),s=e(130),l=null,c=null,p={},d=null,f={injectGenericComponentClass:function(e){c=e},injectTextComponentClass:function(e){d=e},injectComponentClasses:function(e){u(p,e)},injectAutoWrapper:function(e){l=e}},h={getComponentClassForElement:r,createInternalComponent:o,createInstanceForText:i,isTextComponent:a,injection:f};t.exports=h},{130:130,26:26}],71:[function(e,t,n){"use strict";var r=e(130),o={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,n){r(o.isValidOwner(n)),n.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,n){r(o.isValidOwner(n)),n.getPublicInstance().refs[t]===e.getPublicInstance()&&n.detachRef(t)}};t.exports=o},{130:130}],72:[function(e,t,n){"use strict";function r(e,t,n){return n}var o={enableMeasure:!1,storedMeasure:r,measureMethods:function(e,t,n){},measure:function(e,t,n){return n},injection:{injectMeasure:function(e){o.storedMeasure=e}}};t.exports=o},{}],73:[function(e,t,n){"use strict";var r={};t.exports=r},{}],74:[function(e,t,n){"use strict";var r=e(135),o=r({prop:null,context:null,childContext:null});t.exports=o},{135:135}],75:[function(e,t,n){"use strict";function r(e){function t(t,n,r,o,i){if(o=o||b,null==n[r]){var a=C[i];return t?new Error("Required "+a+" `"+r+"` was not specified in "+("`"+o+"`.")):null}return e(n,r,o,i)}var n=t.bind(null,!1);return n.isRequired=t.bind(null,!0),n}function o(e){function t(t,n,r,o){var i=t[n],a=m(i);if(a!==e){var u=C[o],s=v(i);return new Error("Invalid "+u+" `"+n+"` of type `"+s+"` "+("supplied to `"+r+"`, expected `"+e+"`."))}return null}return r(t)}function i(){return r(E.thatReturns(null))}function a(e){function t(t,n,r,o){var i=t[n];if(!Array.isArray(i)){var a=C[o],u=m(i);return new Error("Invalid "+a+" `"+n+"` of type "+("`"+u+"` supplied to `"+r+"`, expected an array."))}for(var s=0;s<i.length;s++){var l=e(i,s,r,o);if(l instanceof Error)return l}return null}return r(t)}function u(){function e(e,t,n,r){if(!g.isValidElement(e[t])){var o=C[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactElement."))}return null}return r(e)}function s(e){function t(t,n,r,o){if(!(t[n]instanceof e)){var i=C[o],a=e.name||b;return new Error("Invalid "+i+" `"+n+"` supplied to "+("`"+r+"`, expected instance of `"+a+"`."))}return null}return r(t)}function l(e){function t(t,n,r,o){for(var i=t[n],a=0;a<e.length;a++)if(i===e[a])return null;var u=C[o],s=JSON.stringify(e);return new Error("Invalid "+u+" `"+n+"` of value `"+i+"` "+("supplied to `"+r+"`, expected one of "+s+"."))}return r(t)}function c(e){function t(t,n,r,o){var i=t[n],a=m(i);if("object"!==a){var u=C[o];return new Error("Invalid "+u+" `"+n+"` of type "+("`"+a+"` supplied to `"+r+"`, expected an object."))}for(var s in i)if(i.hasOwnProperty(s)){var l=e(i,s,r,o);if(l instanceof Error)return l}return null}return r(t)}function p(e){function t(t,n,r,o){for(var i=0;i<e.length;i++){var a=e[i];if(null==a(t,n,r,o))return null}var u=C[o];return new Error("Invalid "+u+" `"+n+"` supplied to "+("`"+r+"`."))}return r(t)}function d(){function e(e,t,n,r){if(!h(e[t])){var o=C[r];return new Error("Invalid "+o+" `"+t+"` supplied to "+("`"+n+"`, expected a ReactNode."))}return null}return r(e)}function f(e){function t(t,n,r,o){var i=t[n],a=m(i);if("object"!==a){var u=C[o];return new Error("Invalid "+u+" `"+n+"` of type `"+a+"` "+("supplied to `"+r+"`, expected `object`."))}for(var s in e){var l=e[s];if(l){var c=l(i,s,r,o);if(c)return c}}return null}return r(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;e=y.extractIfFragment(e);for(var t in e)if(!h(e[t]))return!1;return!0;default:return!1}}function m(e){var t=typeof e;return Array.isArray(e)?"array":e instanceof RegExp?"object":t}function v(e){var t=m(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}var g=e(54),y=e(60),C=e(73),E=e(110),b="<<anonymous>>",_={array:o("array"),bool:o("boolean"),func:o("function"),number:o("number"),object:o("object"),string:o("string"),any:i(),arrayOf:a,element:u(),instanceOf:s,node:d(),objectOf:c,oneOf:l,oneOfType:p,shape:f};t.exports=_},{110:110,54:54,60:60,73:73}],76:[function(e,t,n){"use strict";function r(){this.reinitializeTransaction(),this.renderToStaticMarkup=!1,this.reactMountReady=o.getPooled(null)}var o=e(6),i=e(27),a=e(29),u=e(62),s=e(99),l=e(26),c={initialize:u.getSelectionInformation,close:u.restoreSelection},p={initialize:function(){var e=a.isEnabled();return a.setEnabled(!1),e},close:function(e){a.setEnabled(e)}},d={initialize:function(){this.reactMountReady.reset()},close:function(){this.reactMountReady.notifyAll()}},f=[c,p,d],h={getTransactionWrappers:function(){return f},getReactMountReady:function(){return this.reactMountReady},destructor:function(){o.release(this.reactMountReady),this.reactMountReady=null}};l(r.prototype,s.Mixin,h),i.addPoolingTo(r),t.exports=r},{26:26,27:27,29:29,6:6,62:62,99:99}],77:[function(e,t,n){"use strict";function r(){o.attachRefs(this,this._currentElement)}var o=e(78),i=(e(55),{mountComponent:function(e,t,n,o){var i=e.mountComponent(t,n,o);return n.getReactMountReady().enqueue(r,e),i},unmountComponent:function(e){o.detachRefs(e,e._currentElement),e.unmountComponent()},receiveComponent:function(e,t,n,i){var a=e._currentElement;if(t!==a||null==t._owner){var u=o.shouldUpdateRefs(a,t);u&&o.detachRefs(e,a),e.receiveComponent(t,n,i),u&&n.getReactMountReady().enqueue(r,e)}},performUpdateIfNecessary:function(e,t){e.performUpdateIfNecessary(t)}});t.exports=i},{55:55,78:78}],78:[function(e,t,n){"use strict";function r(e,t,n){"function"==typeof e?e(t.getPublicInstance()):i.addComponentAsRefTo(t,e,n)}function o(e,t,n){"function"==typeof e?e(null):i.removeComponentAsRefFrom(t,e,n)}var i=e(71),a={};a.attachRefs=function(e,t){var n=t.ref;null!=n&&r(n,e,t._owner)},a.shouldUpdateRefs=function(e,t){return t._owner!==e._owner||t.ref!==e.ref},a.detachRefs=function(e,t){var n=t.ref;null!=n&&o(n,e,t._owner)},t.exports=a},{71:71}],79:[function(e,t,n){"use strict";var r={injectCreateReactRootIndex:function(e){o.createReactRootIndex=e}},o={createReactRootIndex:null,injection:r};t.exports=o},{}],80:[function(e,t,n){"use strict";function r(e){p(i.isValidElement(e));var t;try{var n=a.createReactRootID();return t=s.getPooled(!1),t.perform(function(){var r=c(e,null),o=r.mountComponent(n,t,l);return u.addChecksumToMarkup(o)},null)}finally{s.release(t)}}function o(e){p(i.isValidElement(e));var t;try{var n=a.createReactRootID();return t=s.getPooled(!0),t.perform(function(){var r=c(e,null);return r.mountComponent(n,t,l)},null)}finally{s.release(t)}}var i=e(54),a=e(63),u=e(66),s=e(81),l=e(111),c=e(129),p=e(130);t.exports={renderToString:r,renderToStaticMarkup:o}},{111:111,129:129,130:130,54:54,63:63,66:66,81:81}],81:[function(e,t,n){"use strict";function r(e){this.reinitializeTransaction(),this.renderToStaticMarkup=e,this.reactMountReady=i.getPooled(null)}var o=e(27),i=e(6),a=e(99),u=e(26),s=e(110),l={initialize:function(){this.reactMountReady.reset()},close:s},c=[l],p={getTransactionWrappers:function(){return c},getReactMountReady:function(){return this.reactMountReady},destructor:function(){i.release(this.reactMountReady),this.reactMountReady=null}};u(r.prototype,a.Mixin,p),o.addPoolingTo(r),t.exports=r},{110:110,26:26,27:27,6:6,99:99}],82:[function(e,t,n){"use strict";function r(e){e!==i.currentlyMountingInstance&&l.enqueueUpdate(e)}function o(e,t){p(null==a.current);var n=s.get(e);return n?n===i.currentlyUnmountingInstance?null:n:null}var i=e(65),a=e(38),u=e(54),s=e(64),l=e(83),c=e(26),p=e(130),d=(e(148),{enqueueCallback:function(e,t){p("function"==typeof t);var n=o(e);return n&&n!==i.currentlyMountingInstance?(n._pendingCallbacks?n._pendingCallbacks.push(t):n._pendingCallbacks=[t],void r(n)):null},enqueueCallbackInternal:function(e,t){p("function"==typeof t),e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t],r(e)},enqueueForceUpdate:function(e){var t=o(e,"forceUpdate");t&&(t._pendingForceUpdate=!0,r(t))},enqueueReplaceState:function(e,t){var n=o(e,"replaceState");n&&(n._pendingStateQueue=[t],n._pendingReplaceState=!0,r(n))},enqueueSetState:function(e,t){var n=o(e,"setState");if(n){var i=n._pendingStateQueue||(n._pendingStateQueue=[]);i.push(t),r(n)}},enqueueSetProps:function(e,t){var n=o(e,"setProps");if(n){p(n._isTopLevel);var i=n._pendingElement||n._currentElement,a=c({},i.props,t);n._pendingElement=u.cloneAndReplaceProps(i,a),r(n)}},enqueueReplaceProps:function(e,t){var n=o(e,"replaceProps");if(n){p(n._isTopLevel);var i=n._pendingElement||n._currentElement;n._pendingElement=u.cloneAndReplaceProps(i,t),r(n)}},enqueueElementInternal:function(e,t){e._pendingElement=t,r(e)}});t.exports=d},{130:130,148:148,26:26,38:38,54:54,64:64,65:65,83:83}],83:[function(e,t,n){"use strict";function r(){v(I.ReactReconcileTransaction&&E)}function o(){this.reinitializeTransaction(),this.dirtyComponentsLength=null,this.callbackQueue=c.getPooled(),this.reconcileTransaction=I.ReactReconcileTransaction.getPooled()}function i(e,t,n,o,i,a){r(),E.batchedUpdates(e,t,n,o,i,a)}function a(e,t){return e._mountOrder-t._mountOrder}function u(e){var t=e.dirtyComponentsLength;v(t===g.length),g.sort(a);for(var n=0;t>n;n++){var r=g[n],o=r._pendingCallbacks;if(r._pendingCallbacks=null,f.performUpdateIfNecessary(r,e.reconcileTransaction),o)for(var i=0;i<o.length;i++)e.callbackQueue.enqueue(o[i],r.getPublicInstance())}}function s(e){return r(),E.isBatchingUpdates?void g.push(e):void E.batchedUpdates(s,e)}function l(e,t){v(E.isBatchingUpdates),y.enqueue(e,t),C=!0}var c=e(6),p=e(27),d=(e(38),e(72)),f=e(77),h=e(99),m=e(26),v=e(130),g=(e(148),[]),y=c.getPooled(),C=!1,E=null,b={initialize:function(){this.dirtyComponentsLength=g.length},close:function(){this.dirtyComponentsLength!==g.length?(g.splice(0,this.dirtyComponentsLength),D()):g.length=0}},_={initialize:function(){this.callbackQueue.reset()},close:function(){this.callbackQueue.notifyAll()}},x=[b,_];m(o.prototype,h.Mixin,{getTransactionWrappers:function(){return x},destructor:function(){this.dirtyComponentsLength=null,c.release(this.callbackQueue),this.callbackQueue=null,I.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)}}),p.addPoolingTo(o);var D=function(){for(;g.length||C;){if(g.length){var e=o.getPooled();e.perform(u,null,e),o.release(e)}if(C){C=!1;var t=y;y=c.getPooled(),t.notifyAll(),c.release(t)}}};D=d.measure("ReactUpdates","flushBatchedUpdates",D);var M={injectReconcileTransaction:function(e){v(e),I.ReactReconcileTransaction=e},injectBatchingStrategy:function(e){v(e),v("function"==typeof e.batchedUpdates),v("boolean"==typeof e.isBatchingUpdates),E=e}},I={ReactReconcileTransaction:null,batchedUpdates:i,enqueueUpdate:s,flushBatchedUpdates:D,injection:M,asap:l};t.exports=I},{130:130,148:148,26:26,27:27,38:38,6:6,72:72,77:77,99:99}],84:[function(e,t,n){"use strict";var r=e(10),o=r.injection.MUST_USE_ATTRIBUTE,i={xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"},a={Properties:{clipPath:o,cx:o,cy:o,d:o,dx:o,dy:o,fill:o,fillOpacity:o,fontFamily:o,fontSize:o,fx:o,fy:o,gradientTransform:o,gradientUnits:o,markerEnd:o,markerMid:o,markerStart:o,offset:o,opacity:o,patternContentUnits:o,patternUnits:o,points:o,preserveAspectRatio:o,r:o,rx:o,ry:o,spreadMethod:o,stopColor:o,stopOpacity:o,stroke:o,strokeDasharray:o,strokeLinecap:o,strokeOpacity:o,strokeWidth:o,textAnchor:o,transform:o,version:o,viewBox:o,x1:o,x2:o,x:o,xlinkActuate:o,xlinkArcrole:o,xlinkHref:o,xlinkRole:o,xlinkShow:o,xlinkTitle:o,xlinkType:o,xmlBase:o,xmlLang:o,xmlSpace:o,y1:o,y2:o,y:o},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"}};t.exports=a},{10:10}],85:[function(e,t,n){"use strict";function r(e){if("selectionStart"in e&&u.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 o(e){if(y||null==m||m!==l())return null;var t=r(m);if(!g||!d(g,t)){g=t;var n=s.getPooled(h.select,v,e);return n.type="select",n.target=m,a.accumulateTwoPhaseDispatches(n),n}return null}var i=e(15),a=e(20),u=e(62),s=e(91),l=e(117),c=e(133),p=e(136),d=e(143),f=i.topLevelTypes,h={select:{phasedRegistrationNames:{bubbled:p({onSelect:null}),captured:p({onSelectCapture:null})},dependencies:[f.topBlur,f.topContextMenu,f.topFocus,f.topKeyDown,f.topMouseDown,f.topMouseUp,f.topSelectionChange]}},m=null,v=null,g=null,y=!1,C=!1,E=p({onSelect:null}),b={eventTypes:h,extractEvents:function(e,t,n,r){if(!C)return null;switch(e){case f.topFocus:(c(t)||"true"===t.contentEditable)&&(m=t,v=n,g=null);break;case f.topBlur:m=null,v=null,g=null;break;case f.topMouseDown:y=!0;break;case f.topContextMenu:case f.topMouseUp:return y=!1,o(r);case f.topSelectionChange:case f.topKeyDown:case f.topKeyUp:return o(r)}return null},didPutListener:function(e,t,n){t===E&&(C=!0)}};t.exports=b},{117:117,133:133,136:136,143:143,15:15,20:20,62:62,91:91}],86:[function(e,t,n){"use strict";var r=Math.pow(2,53),o={createReactRootIndex:function(){return Math.ceil(Math.random()*r)}};t.exports=o},{}],87:[function(e,t,n){"use strict";var r=e(15),o=e(16),i=e(19),a=e(20),u=e(67),s=e(88),l=e(91),c=e(92),p=e(94),d=e(95),f=e(90),h=e(96),m=e(97),v=e(98),g=e(110),y=e(118),C=e(130),E=e(136),b=(e(148),r.topLevelTypes),_={blur:{phasedRegistrationNames:{bubbled:E({onBlur:!0}),captured:E({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:E({onClick:!0}),captured:E({onClickCapture:!0})}},contextMenu:{phasedRegistrationNames:{bubbled:E({onContextMenu:!0}),captured:E({onContextMenuCapture:!0})}},copy:{phasedRegistrationNames:{bubbled:E({onCopy:!0}),captured:E({onCopyCapture:!0})}},cut:{phasedRegistrationNames:{bubbled:E({onCut:!0}),captured:E({onCutCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:E({onDoubleClick:!0}),captured:E({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:E({onDrag:!0}),captured:E({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:E({onDragEnd:!0}),captured:E({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:E({onDragEnter:!0}),captured:E({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:E({onDragExit:!0}),captured:E({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:E({onDragLeave:!0}),captured:E({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:E({onDragOver:!0}),captured:E({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:E({onDragStart:!0}),captured:E({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:E({onDrop:!0}),captured:E({onDropCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:E({onFocus:!0}),captured:E({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:E({onInput:!0}),captured:E({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:E({onKeyDown:!0}),captured:E({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:E({onKeyPress:!0}),captured:E({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:E({onKeyUp:!0}),captured:E({onKeyUpCapture:!0})}},load:{phasedRegistrationNames:{bubbled:E({onLoad:!0}),captured:E({onLoadCapture:!0})}},error:{phasedRegistrationNames:{bubbled:E({onError:!0}),captured:E({onErrorCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:E({onMouseDown:!0}),captured:E({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:E({onMouseMove:!0}),captured:E({onMouseMoveCapture:!0})}},mouseOut:{phasedRegistrationNames:{bubbled:E({onMouseOut:!0}),captured:E({onMouseOutCapture:!0})}},mouseOver:{phasedRegistrationNames:{bubbled:E({onMouseOver:!0}),captured:E({onMouseOverCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:E({onMouseUp:!0}),captured:E({onMouseUpCapture:!0})}},paste:{phasedRegistrationNames:{bubbled:E({onPaste:!0}),captured:E({onPasteCapture:!0})}},reset:{phasedRegistrationNames:{bubbled:E({onReset:!0}),captured:E({onResetCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:E({onScroll:!0}),captured:E({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:E({onSubmit:!0}),captured:E({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:E({onTouchCancel:!0}),captured:E({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:E({onTouchEnd:!0}),captured:E({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:E({onTouchMove:!0}),captured:E({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:E({onTouchStart:!0}),captured:E({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:E({onWheel:!0}),captured:E({onWheelCapture:!0})}}},x={topBlur:_.blur,topClick:_.click,topContextMenu:_.contextMenu,topCopy:_.copy,topCut:_.cut,topDoubleClick:_.doubleClick,topDrag:_.drag,topDragEnd:_.dragEnd,topDragEnter:_.dragEnter,topDragExit:_.dragExit,topDragLeave:_.dragLeave,topDragOver:_.dragOver,topDragStart:_.dragStart,topDrop:_.drop,topError:_.error,topFocus:_.focus,topInput:_.input,topKeyDown:_.keyDown,topKeyPress:_.keyPress,topKeyUp:_.keyUp,topLoad:_.load,topMouseDown:_.mouseDown,topMouseMove:_.mouseMove,topMouseOut:_.mouseOut,topMouseOver:_.mouseOver,topMouseUp:_.mouseUp,topPaste:_.paste,topReset:_.reset,topScroll:_.scroll,topSubmit:_.submit,topTouchCancel:_.touchCancel,topTouchEnd:_.touchEnd,topTouchMove:_.touchMove,topTouchStart:_.touchStart,topWheel:_.wheel};for(var D in x)x[D].dependencies=[D];var M=E({onClick:null}),I={},N={eventTypes:_,executeDispatch:function(e,t,n){var r=i.executeDispatch(e,t,n);r===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,r){var o=x[e];if(!o)return null;var i;switch(e){case b.topInput:case b.topLoad:case b.topError:case b.topReset:case b.topSubmit:i=l;break;case b.topKeyPress:if(0===y(r))return null;case b.topKeyDown:case b.topKeyUp:i=p;break;case b.topBlur:case b.topFocus:i=c;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:i=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:i=f;break;case b.topTouchCancel:case b.topTouchEnd:case b.topTouchMove:case b.topTouchStart:i=h;break;case b.topScroll:i=m;break;case b.topWheel:i=v;break;case b.topCopy:case b.topCut:case b.topPaste:i=s}C(i);var u=i.getPooled(o,n,r);return a.accumulateTwoPhaseDispatches(u),u},didPutListener:function(e,t,n){if(t===M){var r=u.getNode(e);I[e]||(I[e]=o.listen(r,"click",g))}},willDeleteListener:function(e,t){t===M&&(I[e].remove(),delete I[e])}};t.exports=N},{110:110,118:118,130:130,136:136,148:148,15:15,16:16,19:19,20:20,67:67,88:88,90:90,91:91,92:92,94:94,95:95,96:96,97:97,98:98}],88:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(91),i={clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}};o.augmentClass(r,i),t.exports=r},{91:91}],89:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(91),i={data:null};o.augmentClass(r,i),t.exports=r},{91:91}],90:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(95),i={dataTransfer:null};o.augmentClass(r,i),t.exports=r},{95:95}],91:[function(e,t,n){"use strict";function r(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var o in r)if(r.hasOwnProperty(o)){var i=r[o];i?this[o]=i(n):this[o]=n[o]}var u=null!=n.defaultPrevented?n.defaultPrevented:n.returnValue===!1;u?this.isDefaultPrevented=a.thatReturnsTrue:this.isDefaultPrevented=a.thatReturnsFalse,this.isPropagationStopped=a.thatReturnsFalse}var o=e(27),i=e(26),a=e(110),u=e(121),s={type:null,target:u,currentTarget:a.thatReturnsNull,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};i(r.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=a.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;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}}),r.Interface=s,r.augmentClass=function(e,t){var n=this,r=Object.create(n.prototype);i(r,e.prototype),e.prototype=r,e.prototype.constructor=e,e.Interface=i({},n.Interface,t),e.augmentClass=n.augmentClass,o.addPoolingTo(e,o.threeArgumentPooler)},o.addPoolingTo(r,o.threeArgumentPooler),t.exports=r},{110:110,121:121,26:26,27:27}],92:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(97),i={relatedTarget:null};o.augmentClass(r,i),t.exports=r},{97:97}],93:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(91),i={data:null};o.augmentClass(r,i),t.exports=r},{91:91}],94:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(97),i=e(118),a=e(119),u=e(120),s={key:a,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:u,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}};o.augmentClass(r,s),t.exports=r},{118:118,119:119,120:120,97:97}],95:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(97),i=e(100),a=e(120),u={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}};o.augmentClass(r,u),t.exports=r},{100:100,120:120,97:97}],96:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(97),i=e(120),a={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:i};o.augmentClass(r,a),t.exports=r},{120:120,97:97}],97:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(91),i=e(121),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}};o.augmentClass(r,a),t.exports=r},{121:121,91:91}],98:[function(e,t,n){"use strict";function r(e,t,n){o.call(this,e,t,n)}var o=e(95),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};o.augmentClass(r,i),t.exports=r},{95:95}],99:[function(e,t,n){"use strict";var r=e(130),o={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,n,o,i,a,u,s){r(!this.isInTransaction());var l,c;try{this._isInTransaction=!0,l=!0,this.initializeAll(0),c=e.call(t,n,o,i,a,u,s),l=!1}finally{try{if(l)try{this.closeAll(0)}catch(p){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return c},initializeAll:function(e){for(var t=this.transactionWrappers,n=e;n<t.length;n++){var r=t[n];try{this.wrapperInitData[n]=i.OBSERVED_ERROR,this.wrapperInitData[n]=r.initialize?r.initialize.call(this):null}finally{if(this.wrapperInitData[n]===i.OBSERVED_ERROR)try{this.initializeAll(n+1)}catch(o){}}}},closeAll:function(e){r(this.isInTransaction());for(var t=this.transactionWrappers,n=e;n<t.length;n++){var o,a=t[n],u=this.wrapperInitData[n];try{o=!0,u!==i.OBSERVED_ERROR&&a.close&&a.close.call(this,u),o=!1}finally{if(o)try{this.closeAll(n+1)}catch(s){}}}this.wrapperInitData.length=0}},i={Mixin:o,OBSERVED_ERROR:{}};t.exports=i},{130:130}],100:[function(e,t,n){"use strict";var r={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(e){r.currentScrollLeft=e.x,r.currentScrollTop=e.y}};t.exports=r},{}],101:[function(e,t,n){"use strict";function r(e,t){if(o(null!=t),null==e)return t;var n=Array.isArray(e),r=Array.isArray(t);return n&&r?(e.push.apply(e,t),e):n?(e.push(t),e):r?[e].concat(t):[e,t]}var o=e(130);t.exports=r},{130:130}],102:[function(e,t,n){"use strict";function r(e){for(var t=1,n=0,r=0;r<e.length;r++)t=(t+e.charCodeAt(r))%o,n=(n+t)%o;return t|n<<16}var o=65521;t.exports=r},{}],103:[function(e,t,n){"use strict";function r(e){return e.replace(o,function(e,t){return t.toUpperCase()})}var o=/-(.)/g;t.exports=r},{}],104:[function(e,t,n){"use strict";function r(e){return o(e.replace(i,"ms-"))}var o=e(103),i=/^-ms-/;t.exports=r},{103:103}],105:[function(e,t,n){"use strict";function r(e,t){var n=!0;e:for(;n;){n=!1;var r=e,i=t;if(r&&i){if(r===i)return!0;if(o(r))return!1;if(o(i)){e=r,t=i.parentNode,n=!0;continue e}return r.contains?r.contains(i):r.compareDocumentPosition?!!(16&r.compareDocumentPosition(i)):!1}return!1}}var o=e(134);t.exports=r},{134:134}],106:[function(e,t,n){"use strict";function r(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 o(e){return r(e)?Array.isArray(e)?e.slice():i(e):[e]}var i=e(145);t.exports=o},{145:145}],107:[function(e,t,n){"use strict";function r(e){var t=i.createFactory(e),n=o.createClass({tagName:e.toUpperCase(),displayName:"ReactFullPageComponent"+e,componentWillUnmount:function(){a(!1)},render:function(){return t(this.props)}});return n}var o=e(32),i=e(54),a=e(130);t.exports=r},{130:130,32:32,54:54}],108:[function(e,t,n){"use strict";function r(e){var t=e.match(c);return t&&t[1].toLowerCase()}function o(e,t){var n=l;s(!!l);var o=r(e),i=o&&u(o);if(i){n.innerHTML=i[1]+e+i[2];for(var c=i[0];c--;)n=n.lastChild}else n.innerHTML=e;var p=n.getElementsByTagName("script");p.length&&(s(t),a(p).forEach(t));for(var d=a(n.childNodes);n.lastChild;)n.removeChild(n.lastChild);return d}var i=e(21),a=e(106),u=e(123),s=e(130),l=i.canUseDOM?document.createElement("div"):null,c=/^\s*<(\w+)/;t.exports=o},{106:106,123:123,130:130,21:21}],109:[function(e,t,n){"use strict";function r(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var r=isNaN(t);return r||0===t||i.hasOwnProperty(e)&&i[e]?""+t:("string"==typeof t&&(t=t.trim()),t+"px")}var o=e(4),i=o.isUnitlessNumber;t.exports=r},{4:4}],110:[function(e,t,n){"use strict";function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},t.exports=o},{}],111:[function(e,t,n){"use strict";var r={};t.exports=r},{}],112:[function(e,t,n){"use strict";function r(e){return i[e]}function o(e){return(""+e).replace(a,r)}var i={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;"},a=/[&><"']/g;t.exports=o},{}],113:[function(e,t,n){"use strict";function r(e){return null==e?null:u(e)?e:o.has(e)?i.getNodeFromInstance(e):(a(null==e.render||"function"!=typeof e.render),void a(!1))}var o=(e(38),e(64)),i=e(67),a=e(130),u=e(132);e(148);t.exports=r},{130:130,132:132,148:148,38:38,64:64,67:67}],114:[function(e,t,n){"use strict";function r(e,t,n){var r=e,o=void 0===r[n];o&&null!=t&&(r[n]=t)}function o(e){if(null==e)return e;var t={};return i(e,r,t),t}var i=e(146);e(148);t.exports=o},{146:146,148:148}],115:[function(e,t,n){"use strict";function r(e){try{e.focus()}catch(t){}}t.exports=r},{}],116:[function(e,t,n){"use strict";var r=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=r},{}],117:[function(e,t,n){"use strict";function r(){try{return document.activeElement||document.body}catch(e){return document.body}}t.exports=r},{}],118:[function(e,t,n){"use strict";function r(e){var t,n=e.keyCode;return"charCode"in e?(t=e.charCode,0===t&&13===n&&(t=13)):t=n,t>=32||13===t?t:0}t.exports=r},{}],119:[function(e,t,n){"use strict";function r(e){if(e.key){var t=i[e.key]||e.key;if("Unidentified"!==t)return t}if("keypress"===e.type){var n=o(e);return 13===n?"Enter":String.fromCharCode(n)}return"keydown"===e.type||"keyup"===e.type?a[e.keyCode]||"Unidentified":""}var o=e(118),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"};t.exports=r},{118:118}],120:[function(e,t,n){"use strict";function r(e){var t=this,n=t.nativeEvent;if(n.getModifierState)return n.getModifierState(e);var r=i[e];return r?!!n[r]:!1}function o(e){return r}var i={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};t.exports=o},{}],121:[function(e,t,n){"use strict";function r(e){var t=e.target||e.srcElement||window;return 3===t.nodeType?t.parentNode:t}t.exports=r},{}],122:[function(e,t,n){"use strict";function r(e){var t=e&&(o&&e[o]||e[i]);return"function"==typeof t?t:void 0}var o="function"==typeof Symbol&&Symbol.iterator,i="@@iterator";t.exports=r},{}],123:[function(e,t,n){"use strict";function r(e){return i(!!a),d.hasOwnProperty(e)||(e="*"),u.hasOwnProperty(e)||("*"===e?a.innerHTML="<link />":a.innerHTML="<"+e+"></"+e+">",u[e]=!a.firstChild),u[e]?d[e]:null}var o=e(21),i=e(130),a=o.canUseDOM?document.createElement("div"):null,u={circle:!0,clipPath:!0,defs:!0,ellipse:!0,g:!0,line:!0,linearGradient:!0,path:!0,polygon:!0,polyline:!0,radialGradient:!0,rect:!0,stop:!0,text:!0},s=[1,'<select multiple="true">',"</select>"],l=[1,"<table>","</table>"],c=[3,"<table><tbody><tr>","</tr></tbody></table>"],p=[1,"<svg>","</svg>"],d={"*":[1,"?<div>","</div>"],area:[1,"<map>","</map>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],legend:[1,"<fieldset>","</fieldset>"],param:[1,"<object>","</object>"],tr:[2,"<table><tbody>","</tbody></table>"],optgroup:s,option:s,caption:l,colgroup:l,tbody:l,tfoot:l,thead:l,td:c,th:c,circle:p,clipPath:p,defs:p,ellipse:p,g:p,line:p,linearGradient:p,path:p,polygon:p,polyline:p,radialGradient:p,rect:p,stop:p,text:p};t.exports=r},{130:130,21:21}],124:[function(e,t,n){"use strict";function r(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 i(e,t){for(var n=r(e),i=0,a=0;n;){if(3===n.nodeType){if(a=i+n.textContent.length,t>=i&&a>=t)return{node:n,offset:t-i};i=a}n=r(o(n))}}t.exports=i},{}],125:[function(e,t,n){"use strict";function r(){return!i&&o.canUseDOM&&(i="textContent"in document.documentElement?"textContent":"innerText"),i}var o=e(21),i=null;t.exports=r},{21:21}],126:[function(e,t,n){"use strict";function r(e){return e===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:e.scrollLeft,y:e.scrollTop}}t.exports=r},{}],127:[function(e,t,n){"use strict";function r(e){return e.replace(o,"-$1").toLowerCase()}var o=/([A-Z])/g;t.exports=r},{}],128:[function(e,t,n){"use strict";function r(e){return o(e).replace(i,"-ms-")}var o=e(127),i=/^ms-/;t.exports=r},{127:127}],129:[function(e,t,n){"use strict";function r(e){return"function"==typeof e&&"undefined"!=typeof e.prototype&&"function"==typeof e.prototype.mountComponent&&"function"==typeof e.prototype.receiveComponent}function o(e,t){var n;if((null===e||e===!1)&&(e=a.emptyElement),"object"==typeof e){var o=e;n=t===o.type&&"string"==typeof o.type?u.createInternalComponent(o):r(o.type)?new o.type(o):new c}else"string"==typeof e||"number"==typeof e?n=u.createInstanceForText(e):l(!1);return n.construct(e),n._mountIndex=0,n._mountImage=null,n}var i=e(36),a=e(56),u=e(70),s=e(26),l=e(130),c=(e(148),function(){});s(c.prototype,i.Mixin,{_instantiateReactComponent:o}),t.exports=o},{130:130,148:148,26:26,36:36,56:56,70:70}],130:[function(e,t,n){"use strict";var r=function(e,t,n,r,o,i,a,u){if(!e){var s;if(void 0===t)s=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,u],c=0;s=new Error("Invariant Violation: "+t.replace(/%s/g,function(){return l[c++]}))}throw s.framesToPop=1,s}};t.exports=r},{}],131:[function(e,t,n){"use strict";function r(e,t){if(!i.canUseDOM||t&&!("addEventListener"in document))return!1;var n="on"+e,r=n in document;if(!r){var a=document.createElement("div");a.setAttribute(n,"return;"),r="function"==typeof a[n]}return!r&&o&&"wheel"===e&&(r=document.implementation.hasFeature("Events.wheel","3.0")),r}var o,i=e(21);i.canUseDOM&&(o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=r},{21:21}],132:[function(e,t,n){"use strict";function r(e){return!(!e||!("function"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName))}t.exports=r},{}],133:[function(e,t,n){"use strict";function r(e){return e&&("INPUT"===e.nodeName&&o[e.type]||"TEXTAREA"===e.nodeName)}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};t.exports=r},{}],134:[function(e,t,n){"use strict";function r(e){return o(e)&&3==e.nodeType}var o=e(132);t.exports=r},{132:132}],135:[function(e,t,n){"use strict";var r=e(130),o=function(e){var t,n={};r(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(n[t]=t);return n};t.exports=o},{130:130}],136:[function(e,t,n){"use strict";var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=r},{}],137:[function(e,t,n){"use strict";function r(e,t,n){if(!e)return null;var r={};for(var i in e)o.call(e,i)&&(r[i]=t.call(n,e[i],i,e));return r}var o=Object.prototype.hasOwnProperty;t.exports=r},{}],138:[function(e,t,n){"use strict";function r(e){var t={};return function(n){return t.hasOwnProperty(n)||(t[n]=e.call(this,n)),t[n]}}t.exports=r},{}],139:[function(e,t,n){"use strict";function r(e){return i(o.isValidElement(e)),e}var o=e(54),i=e(130);t.exports=r},{130:130,54:54}],140:[function(e,t,n){"use strict";function r(e){return'"'+o(e)+'"'}var o=e(112);t.exports=r},{112:112}],141:[function(e,t,n){"use strict";var r=e(21),o=/^[ \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})}),r.canUseDOM){var u=document.createElement("div");u.innerHTML=" ",""===u.innerHTML&&(a=function(e,t){if(e.parentNode&&e.parentNode.replaceChild(e,e),o.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})}t.exports=a},{21:21}],142:[function(e,t,n){"use strict";var r=e(21),o=e(112),i=e(141),a=function(e,t){e.textContent=t};r.canUseDOM&&("textContent"in document.documentElement||(a=function(e,t){i(e,o(t))})),t.exports=a},{112:112,141:141,21:21}],143:[function(e,t,n){"use strict";function r(e,t){if(e===t)return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=Object.prototype.hasOwnProperty.bind(t),i=0;i<n.length;i++)if(!o(n[i])||e[n[i]]!==t[n[i]])return!1;return!0}t.exports=r},{}],144:[function(e,t,n){"use strict";function r(e,t){if(null!=e&&null!=t){var n=typeof e,r=typeof t;return"string"===n||"number"===n?"string"===r||"number"===r:"object"===r&&e.type===t.type&&e.key===t.key}return!1}t.exports=r},{}],145:[function(e,t,n){"use strict";function r(e){var t=e.length;if(o(!Array.isArray(e)&&("object"==typeof e||"function"==typeof e)),o("number"==typeof t),o(0===t||t-1 in e),e.hasOwnProperty)try{return Array.prototype.slice.call(e)}catch(n){}for(var r=Array(t),i=0;t>i;i++)r[i]=e[i];return r}var o=e(130);t.exports=r},{130:130}],146:[function(e,t,n){"use strict";function r(e){return v[e]}function o(e,t){return e&&null!=e.key?a(e.key):t.toString(36)}function i(e){return(""+e).replace(g,r)}function a(e){return"$"+i(e)}function u(e,t,n,r,i){var s=typeof e;if(("undefined"===s||"boolean"===s)&&(e=null),null===e||"string"===s||"number"===s||l.isValidElement(e))return r(i,e,""===t?h+o(e,0):t,n),1;var p,v,g,y=0;if(Array.isArray(e))for(var C=0;C<e.length;C++)p=e[C],v=(""!==t?t+m:h)+o(p,C),g=n+y,y+=u(p,v,g,r,i);else{var E=d(e);if(E){var b,_=E.call(e);if(E!==e.entries)for(var x=0;!(b=_.next()).done;)p=b.value,v=(""!==t?t+m:h)+o(p,x++),g=n+y,y+=u(p,v,g,r,i);else for(;!(b=_.next()).done;){var D=b.value;D&&(p=D[1],v=(""!==t?t+m:h)+a(D[0])+m+o(p,0),g=n+y,y+=u(p,v,g,r,i))}}else if("object"===s){f(1!==e.nodeType);var M=c.extract(e);for(var I in M)M.hasOwnProperty(I)&&(p=M[I],v=(""!==t?t+m:h)+a(I)+m+o(p,0),g=n+y,y+=u(p,v,g,r,i))}}return y}function s(e,t,n){return null==e?0:u(e,"",0,t,n)}var l=e(54),c=e(60),p=e(63),d=e(122),f=e(130),h=(e(148),p.SEPARATOR),m=":",v={"=":"=0",".":"=1",":":"=2"},g=/[=.:]/g;t.exports=s},{122:122,130:130,148:148,54:54,60:60,63:63}],147:[function(e,t,n){"use strict";var r=e(110),o=(e(148),r);t.exports=o},{110:110,148:148}],148:[function(e,t,n){"use strict";var r=e(110),o=r;t.exports=o},{110:110}]},{},[1])(1)});
examples/create-react-app-with-jss/src/withRoot.js
cherniavskii/material-ui
import React from 'react'; import { create } from 'jss'; import JssProvider from 'react-jss/lib/JssProvider'; import { MuiThemeProvider, createMuiTheme, createGenerateClassName, jssPreset, } from 'material-ui/styles'; import purple from 'material-ui/colors/purple'; import green from 'material-ui/colors/green'; import CssBaseline from 'material-ui/CssBaseline'; // A theme with custom primary and secondary color. // It's optional. const theme = createMuiTheme({ primary: { light: purple[300], main: purple[500], dark: purple[700], }, secondary: { light: green[300], main: green[500], dark: green[700], }, }); // Create a JSS instance with the default preset of plugins. // It's optional. const jss = create(jssPreset()); // The standard class name generator. // It's optional. const generateClassName = createGenerateClassName(); function withRoot(Component) { function WithRoot(props) { // JssProvider allows customizing the JSS styling solution. return ( <JssProvider jss={jss} generateClassName={generateClassName}> {/* MuiThemeProvider makes the theme available down the React tree thanks to React context. */} <MuiThemeProvider theme={theme}> {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */} <CssBaseline /> <Component {...props} /> </MuiThemeProvider> </JssProvider> ); } return WithRoot; } export default withRoot;
senic_hub/setup_app/components/Settings.js
grunskis/nuimo-hub-backend
import React from 'react'; import { FlatList, StyleSheet, View, } from 'react-native'; import { List, ListItem } from 'react-native-elements' import Screen from './Screen'; import Settings from '../Settings' export default class SettingsScreen extends Screen { constructor(props) { super(props) this.items = [ { title: 'Feedback', onPress: () => this.pushScreen('feedback') }, { title: 'Restart Setup', onPress: () => Settings.resetHubApiUrl().then(() => this.resetTo('setup.welcome')) }, ] this.setTitle('Settings') this.setNavigationButtons([], [ { title: "Close", id: 'close', onPress: () => this.dismissModal() } ]) } render() { return ( <View style={styles.container}> <List> <FlatList data={this.items} renderItem={({item}) => ( <ListItem title={item.title} onPress={item.onPress} /> )} keyExtractor={(item) => item.title} /> </List> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, }, title: { fontSize: 18, textAlign: 'center', margin: 10, }, })
ajax/libs/rxjs/2.5.0/rx.all.compat.js
fredericksilva/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 = (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; }, 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; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } 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])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // 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 hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; 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) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; 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; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // 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; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // 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]; this.items[this.length] = undefined; 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 () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.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 len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @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 }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; 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; if (!shouldDispose) { var 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 () { if (!this.isDisposed) { this.isDisposed = true; var 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 && !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 && !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; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; 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[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(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[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](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([state, 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([state, 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([state, 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 NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.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); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; 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 (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); 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) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (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); })(); var CatchScheduler = (function (__super__) { 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__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; 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; } }; }; 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; }; 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, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * 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 self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { 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) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * 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) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * 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 () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); 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 (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.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( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.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( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); 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) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(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. * @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. * @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, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, 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.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * 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); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * 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 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(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; 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 (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)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } 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(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); 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(typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? 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, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(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)); }, source); }; /** * 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; }, source); }; /** * 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 NotSupportedError('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); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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 () { return new ToArrayObservable(this); }; /** * 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.scheduleWithState(null, function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); 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 () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : 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 () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : 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); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * 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) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * 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 (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * 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 () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * 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) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(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; }); }; /** * 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 keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @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 RangeObservable(start, count, scheduler); }; /** * 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' or 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 = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (o) { return scheduler.scheduleWithState(value, function(_,v) { o.onNext(v); o.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 '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); }; /** * 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 = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } 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 (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); 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 = 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. * @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'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.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) { o.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 () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * 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 () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).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 = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * 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) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * 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 = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * 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 = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.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) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); 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 = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } 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); }); }; /** * 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(); } })); }, function (e) { observer.onError(e); }, 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 len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; 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) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * 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 args. * * @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 args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); 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 = args[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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var 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; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } 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); }; /** * 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 (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; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var 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 = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * 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) { if (count < 0) { throw new ArgumentOutOfRangeError(); } 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; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, 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) { if (count < 0) { throw new ArgumentOutOfRangeError(); } 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); }; /** * 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 (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * 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 ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } 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; }, 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 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, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).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; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // 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 (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * 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; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * 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.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; 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 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(); }); }, source).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 ArgumentOutOfRangeError(); } 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 ArgumentOutOfRangeError(); } 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); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @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.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } 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. * @deprecated Use #reduce instead * @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 hasSeed = false, accumulator, seed, 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) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * 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. * @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 hasSeed = false, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } 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) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @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 = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * 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. * @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 = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * 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.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * 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. * @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 && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * 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).map(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).map(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. * @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 && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * 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); return new AnonymousObservable(function (o) { 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) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * 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 (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * 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. * @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 && isFunction(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 && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * 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. * @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 (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @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. * @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) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * 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); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * 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. * @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 len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } 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 len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } 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 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; /** * 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, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.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) { return observer.onError(err); } } 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) { return observer.onError(err); } } 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.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; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) this.subject.onCompleted(); else this.queue.push(Rx.Notification.createOnCompleted()); }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) this.subject.onError(error); else this.queue.push(Rx.Notification.createOnError(error)); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Rx.Notification.createOnNext(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.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') numberOfItems--; else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } //TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function //if (this.hasFailed) { // this.subject.onError(this.error); //} else if (this.hasCompleted) { // this.subject.onCompleted(); //} 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); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(String(x)) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; /** * 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 windowSize [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, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, 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, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; 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 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(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, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * 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(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), 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(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), 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(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), 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__) { var maxSafeInteger = Math.pow(2, 53) - 1; 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(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 ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : 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(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[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(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * 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, 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)); 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 valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = 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 ArgumentOutOfRangeError(); } 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) { 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; }, left); }; /** * 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; }, left); }; /** * 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 observableWindowWithBoundaries.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, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * 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)); }, source); }; /** * 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) { return [ this.filter(predicate, thisArg), this.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, thisArg) { return enumerableOf(sources, resultSelector, thisArg).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; }, this); }; /** * 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 = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } 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); }, first); }; /** * 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); }, source); }; 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.mergeAll().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.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; 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} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} 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} 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 (e) { observer.onError(e); 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; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); 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; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; 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 {Function} 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 len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var 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); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { 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 d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, 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); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @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 (isScheduler(timeShiftOrScheduler)) { 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 () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * 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. * @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 timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); 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; }, source); }; /** * 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) ); }, 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); }; /** * 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(start, observer.onError.bind(observer), start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @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; 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; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { 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(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, 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); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * 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 (o) { 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) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * 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. * @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 (o) { 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(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * 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. * @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 (o) { 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(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * 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 (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * 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))); }, source); }; /** * 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(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} 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] 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 (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @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 (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, 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); }; /* * 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; }, this); }; /* * 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, selectorFunc = bindCallback(selector, thisArg, 3); 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 = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** * 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); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * 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 ArgumentOutOfRangeError(); } 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 ArgumentOutOfRangeError(); } 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 ArgumentOutOfRangeError(); } 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) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __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 result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; 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 GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } 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(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(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), 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(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), 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(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), 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(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(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(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), 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(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), 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(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) { return 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)); /** * 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));
src/svg-icons/image/crop-5-4.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCrop54 = (props) => ( <SvgIcon {...props}> <path d="M19 5H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 12H5V7h14v10z"/> </SvgIcon> ); ImageCrop54 = pure(ImageCrop54); ImageCrop54.displayName = 'ImageCrop54'; ImageCrop54.muiName = 'SvgIcon'; export default ImageCrop54;
src/components/LoginForm.js
Leobuaa/online-disk
import React, { Component } from 'react'; import Helper from '../helper.js'; import 'whatwg-fetch'; class LoginForm extends Component { constructor(props) { super(props); this.state = { validity: true, checkInfos: { username: null, password: null, }, }; } handleLoginSubmit(event) { event.preventDefault(); this.checkLoginInfo(); // console.log('Username: ' + localStorage.getItem('username')); } submitLoginInfo() { if (this.state.validity === false) { console.log('The login info is invalid!'); } else { console.log('The login info is valid!'); fetch(Helper.fetchLinkHeader + 'login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(this.props.loginInfo), credentials: 'include' }) .then(function(response) { return response.json(); }).then((json) => { console.log(json); let isLogin = false; if (json.success === 1 || json.success === '1') { let avatarURL = 'https://ss0.bdstatic.com/7Ls0a8Sm1A5BphGlnYG/sys/portrait/item/0945792c.jpg'; if (json.data.avatarURL) { avatarURL = Helper.fetchLinkHeader + json.data.avatarURL } const userInfo = { username: json.data.username, avatarURL: avatarURL, }; this.props.onUpdateUserInfo(userInfo); localStorage.setItem('avatarURL', avatarURL); isLogin = true; localStorage.setItem('sessionId', json.data.sessionId); localStorage.setItem('rootDir', JSON.stringify(json.data.rootDir)); localStorage.setItem('username', json.data.username); console.log('localStorage: ', localStorage); this.props.onLoginStateChange(isLogin); Helper.notifyBox('登录成功', 'success'); } else { if (json.code === '1') { Helper.notifyBox('该用户名尚未注册.', 'danger'); } else { Helper.notifyBox('用户名或密码错误.', 'danger'); } } }).catch((ex) =>{ console.log(ex); Helper.notifyBox('服务器未响应, 请稍后重试或向开发者反馈', 'danger') }); } // console.log(JSON.stringify(this.props.loginInfo, null, 4)); } handleInputChange(event) { this.props.onChange(event); // console.log(this.props.loginInfo); } handleInputFocus(event) { const checkInfos = this.state.checkInfos; checkInfos[event.target.name] = ''; this.setState({checkInfos: checkInfos}); } checkLoginInfo() { const checkInfos = this.state.checkInfos; let validity = true; validity = this.checkInfoIsNull(checkInfos) & this.checkInfoWhiteSpace(checkInfos); validity = validity == 1 ? true : false; this.setState({ validity: validity, checkInfos: checkInfos, }, this.submitLoginInfo); } checkInfoIsNull(checkInfos) { const loginInfo = this.props.loginInfo; let validity = true; if (!loginInfo.username || loginInfo.username === '') { checkInfos.username = '请输入用户名'; validity = false; } if (!loginInfo.password || loginInfo.password === '') { checkInfos.password = '请输入密码'; validity = false; } return validity; } checkInfoWhiteSpace(checkInfos) { const loginInfo = this.props.loginInfo; let validity = true; if (loginInfo.username && loginInfo.username.search(' ') != -1) { checkInfos.username = '用户名中不能包含空格'; validity = false; } return validity; } render() { return ( <div className="login-form-wrapper"> <form> <div className="group-inputs"> <div className="username input-wrapper"> <input name="username" type="text" placeholder="邮箱或用户名" value={this.props.loginInfo.username || ''} onChange={(e) => this.handleInputChange(e)} onFocus={(e) => this.handleInputFocus(e)} /> <label className="error">{this.state.checkInfos.username}</label> </div> <div className="password input-wrapper"> <input name="password" type="password" placeholder="密码" value={this.props.loginInfo.password || ''} onChange={(e) => this.handleInputChange(e)} onFocus={(e) => this.handleInputFocus(e)} /> <label className="error">{this.state.checkInfos.password}</label> </div> </div> <div className="login-button-wrapper"> <button className="button login-button" onClick={(e) => this.handleLoginSubmit(e)}>登录</button> </div> </form> </div> ) } } export default LoginForm;
node_modules/react-icons/md/trending-down.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdTrendingDown = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m26.6 30l3.9-3.8-8.2-8.2-6.6 6.7-12.3-12.4 2.3-2.3 10 10 6.6-6.6 10.5 10.4 3.8-3.8v10h-10z"/></g> </Icon> ) export default MdTrendingDown
components/require-auth.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import {flowRight} from 'lodash' import {withRouter} from 'next/router' import getConfig from 'next/config' import {translate} from 'react-i18next' import withSession from './hoc/with-session' import Info from './info' import Button from './button' const {publicRuntimeConfig: { PUBLIC_URL, PUBLICATION_BASE_URL }} = getConfig() class RequireAuth extends React.Component { static propTypes = { message: PropTypes.string, session: PropTypes.shape({ clear: PropTypes.func.isRequired }), router: PropTypes.shape({ asPath: PropTypes.string.isRequired }).isRequired, render: PropTypes.func.isRequired, t: PropTypes.func.isRequired } static defaultProps = { message: null, session: null } render() { const {session, router, message, render, t} = this.props const currentUrl = `${PUBLIC_URL}${router.asPath}` const loginUrl = `${PUBLICATION_BASE_URL}/login?redirect=${encodeURIComponent(currentUrl)}` if (!session) { return t('loading') } if (!session.user) { return ( <div className='container'> {message && ( <div className='message'> <Info>{message}</Info> </div> )} <div className='buttons'> <Button href={loginUrl}> {t('auth.login')} </Button> <Button href='https://www.data.gouv.fr/register'> {t('auth.register')} </Button> </div> <style jsx>{` .container { text-align: left; } .message { margin-bottom: 1em; } .buttons { :global(a) { margin-right: 5px; } } `}</style> </div> ) } return render(session.user) } } export default flowRight( translate(), withRouter, withSession )(RequireAuth)
src/routes/Home/components/HomeView.js
harijoe/redux-dollar
import React from 'react' import DuckImage from '../assets/Duck.jpg' import './HomeView.scss' export const HomeView = () => ( <div> <h4>Welcome!</h4> <img alt='This is a duck, because Redux!' className='duck' src={DuckImage} /> </div> ) export default HomeView
src/components/ExampleComponent.js
ambershen/ambershen.github.io
import React from 'react'; import Interactive from 'react-interactive'; import { Switch, Route, Link } from 'react-router-dom'; import ExampleTwoDeepComponent from './ExampleTwoDeepComponent'; import PageNotFound from './PageNotFound'; import s from '../styles/exampleComponent.style'; const ExamplePageText = () => ( <p style={s.p}> This is an example page. Refresh the page or copy/paste the url to test out the redirect functionality (this same page should load after the redirect). </p> ); export default function ExampleComponent() { return ( <Switch> <Route exact path="/example/two-deep" render={({ location }) => ( <div> <ExamplePageText /> <ExampleTwoDeepComponent location={location} /> </div> )} /> <Route exact path="/example" render={() => ( <div> <ExamplePageText /> <div style={s.pageLinkContainer}> <Interactive as={Link} {...s.link} to="/example/two-deep?field1=foo&field2=bar#boom!" >Example two deep with query and hash</Interactive> </div> </div> )} /> <Route component={PageNotFound} /> </Switch> ); }
src/routes.js
alexnsl/ipmaps
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import ipmap_list from './containers/ipmap-list'; import ipmap_new from './containers/ipmap-new'; export default ( <Route path="/" component={App}> <IndexRoute component={ipmap_list} /> <Route path="/add" mode="add" component={ipmap_new} /> <Route path="/edit" mode="edit" component={ipmap_new} /> </Route> )
assets/js/components/activities/checkin/Skeleton.js
tdfischer/organizer
import React from 'react' import { withStyles } from '@material-ui/styles' import Grid from '@material-ui/core/Grid' const carouselStyles = { card: { backgroundColor: '#eee', animationName: '$fade', animationDuration: '1s', animationIterationCount: 'infinite', animationDirection: 'alternate', animationTimingFunction: 'ease-out', height: '14rem', margin: '1rem' }, '@keyframes fade': { from: { backgroundColor: '#fafafa' }, to: { backgroundColor: '#ddd' } } } export const Skeleton = props => ( <Grid item container spacing={8} alignItems="stretch" direction="column"> <Grid item className={props.classes.card} /> <Grid item className={props.classes.card} /> </Grid> ) export default withStyles(carouselStyles)(Skeleton)
src/components/Footer/index.js
cslint/stylelint.cn
import React from "react" import Svg from "react-svg-inline" import github from './github.svg' import twitter from './twitter.svg' import styles from "./index.css" const Footer = () => ( <footer className={ styles.footer } role="contentinfo"> <ul className={ styles.items }> <li className={ styles.item }> <a className={ styles.itemInner } href="https://github.com/stylelint/stylelint" > <Svg className={ styles.svg } svg={ github } /> </a> </li> <li className={ styles.item }> <a className={ styles.itemInner } href="https://twitter.com/stylelint" > <Svg className={ styles.svg } svg={ twitter} /> </a> </li> </ul> </footer> ) export default Footer
ajax/libs/yui/3.1.0pr1/event-custom/event-custom-debug.js
gokuale/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var BEFORE = 0, AFTER = 1; Y.Do = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ Y.Do.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ Y.Do.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case Y.Do.Halt: return ret.retVal; case Y.Do.AlterArgs: args = ret.newArgs; break; case Y.Do.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == Y.Do.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == Y.Do.AlterReturn) { ret = newRet.newRetVal; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ Y.Do.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ Y.Do.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ Y.Do.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ Y.Do.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ Y.Do.Error = Y.Do.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); })(); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param evt {CustomEvent} the custom event * @param sub {Subscriber} the subscriber */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { /** * Detaches this subscriber * @method detach */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i=0; i<evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish') * return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param o configuration object * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber{} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber{} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish') * return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @return {Array} first item is the on subscribers, second the after */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log("Invalid callback for CE: " + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { // Y.later(0, this, Y.bind(this._notify, this, s, this.firedWith)); setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute * @return {EventHandle} handle Unsubscribe handle * @deprecated use on */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute * @return {EventHandle} handle Unsubscribe handle */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; this.host._monitor('attach', this.type, { args: arguments }); return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute * @return {EventHandle} handle Unsubscribe handle */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var found = 0, subs = this.subscribers, i, s; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param s {Subscriber} the subscriber * @param args {Array} the arguments array to apply to the listener * @private */ _notify: function(s, args, ef) { this.log(this.type + "->" + "sub: " + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + " cancelled by subscriber"); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param msg {string} message to log * @param cat {string} log category */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || "info", "event"); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object * @private */ _delete: function(s) { if (s) { delete s.fn; delete s.context; delete this.subscribers[s.id]; delete this.afters[s.id]; } this.host._monitor('detach', this.type, { ce: this, sub: s }); } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute * @param {Object} context The value of the keyword 'this' in the listener * @param {Array} args* 0..n additional arguments to supply the listener * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber * @param ce {CustomEvent} The custom event that sent the notification */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch(e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} context optional 'this' keyword for the listener * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaulTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.sub.once = true; return handle; }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context, x) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = Y.Array(arguments, 0, true); ret = {}; if (L.isArray(type)) { isArr = true; } else { after = type._after; delete type._after; } Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } args[0] = (isArr) ? v : ((after) ? AFTER_PREFIX + k : k); args[1] = f; args[2] = c; ret[k] = this.on.apply(this, args); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) { args = Y.Array(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (this instanceof YUI) { adapt = Y.Env.evt.plugins[type]; args = Y.Array(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (n instanceof Y.NodeList) { n = Y.NodeList.getDOMNodes(n); } else if (n instanceof Node) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? Y.Array(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (this instanceof Node); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, handle, adapt, store = Y.Env.evt.handles, cat, args, ce, keyDetacher = function(lcat, ltype) { var handles = lcat[ltype]; if (handles) { while (handles.length) { handle = handles.pop(); handle.detach(); } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; if (cat) { if (type) { keyDetacher(cat, type); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = Y.Array(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (this instanceof YUI) { args = Y.Array(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } ce = evts[type]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = this._yuievt.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.mix(opts, this._yuievt.defaults) : this._yuievt.defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', and 'publish. When * configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? Y.Array(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = Y.Array(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? })(); /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('domready', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type** event type (this parameter does not apply for function events) * @param fn the callback * @param target** a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra** 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param target a descriptor for the target (applies to custom events only). * For function events, this is the object that contains the function to * execute. * @param extra 0..n Extra information a particular event may need. These * will be documented with the event. In the case of function events, this * is the name of the function to execute on the host. In the case of * delegate listeners, this is the event delegation specification. * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']}); YUI.add('event-custom-complex', function(Y) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ (function() { var FACADE, FACADE_KEYS, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { e = e || {}; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property type * @type string */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @propery target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @propery currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @propery relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; /** * Stops the propagation to the next bubble target * @method stopPropagation */ this.stopPropagation = function() { e.stopPropagation(); }; /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ this.stopImmediatePropagation = function() { e.stopImmediatePropagation(); }; /** * Prevents the event's default behavior * @method preventDefault */ this.preventDefault = function() { e.preventDefault(); }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ this.halt = function(immediate) { e.halt(immediate); }; }; CEProto.fireComplex = function(args) { var es = Y.Env._eventstack, ef, q, queue, ce, ret, events, subs, self = this, host = self.host || self, next, oldbubble; if (es) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type != es.next.type) { self.log('queue ' + self.type); es.queue.push([self, args]); return true; } } else { Y.Env._eventstack = { // id of the first event in the stack id: self.id, next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), afterQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly, queue: [] }; es = Y.Env._eventstack; } subs = self.getSubs(); self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; self.target = self.target || host; events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; if (self.preventedFn) { events.on('prevented', self.preventedFn); } if (self.stoppedFn) { events.on('stopped', self.stoppedFn); } self.currentTarget = host; self.details = args.slice(); // original arguments in the details // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (Y.Lang.isObject(args[0])) { args[0] = ef; } else { args.unshift(ef); } // if (subCount) { if (subs[0]) { // self._procSubs(Y.merge(self.subscribers), args, ef); self._procSubs(subs[0], args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; // self.bubbling = true; es.bubbling = self.type; // if (host !== ef.target || es.type != self.type) { if (es.type != self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); // self.bubbling = false; es.bubbling = oldbubble; } // execute the default behavior if not prevented // console.log('defaultTargetOnly: ' + self.defaultTargetOnly); // console.log('host === target: ' + (host === ef.target)); // if (self.defaultFn && !self.prevented && ((!self.defaultTargetOnly) || host === es.id === self.id)) { if (self.defaultFn && !self.prevented && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { // if (es.id === self.id) { // self.defaultFn.apply(host, args); // while ((next = es.defaultFnQueue.last())) { // next(); // } // } else { // es.defaultFnQueue.add(function() { // self.defaultFn.apply(host, args); // }); // } self.defaultFn.apply(host, args); } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. self._broadcast(args); // process after listeners. If the default behavior was // prevented, the after events don't fire. // if (self.afterCount && !self.prevented && self.stopped < 2) { // if (subs[1] && !self.prevented && self.stopped < 2) { // // self._procSubs(Y.merge(self.afters), args, ef); // self._procSubs(subs[1], args, ef); // } // Queue the after if (subs[1] && !self.prevented && self.stopped < 2) { if (es.id === self.id || self.type != host._yuievt.bubbling) { self._procSubs(subs[1], args, ef); while ((next = es.afterQueue.last())) { next(); } } else { es.afterQueue.add(function() { self._procSubs(subs[1], args, ef); }); } } self.target = null; // es.stopped = 0; // es.prevented = 0; if (es.id === self.id) { queue = es.queue; while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce.fire.apply(ce, q[1]); // es.stopped = 0; // es.prevented = 0; } Y.Env._eventstack = null; } ret = !(self.stopped); if (self.type != host._yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } return ret; }; CEProto._getFacade = function() { var ef = this._facade, o, o2, args = this.details; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } // if the first argument is an object literal, apply the // properties to the event facade o = args && args[0]; if (Y.Lang.isObject(o, true)) { o2 = {}; // protect the event facade properties Y.mix(o2, ef, true, FACADE_KEYS); // mix the data Y.mix(ef, o, true); // restore ef Y.mix(ef, o2, true, FACADE_KEYS); // Allow the event type to be faked // http://yuilibrary.com/projects/yui3/ticket/2528376 ef.type = o.type || ef.type; } // update the details field with the arguments // ef.type = this.type; ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; Y.Env._eventstack.stopped = 1; this.events.fire('stopped', this); }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; Y.Env._eventstack.stopped = 2; this.events.fire('stopped', this); }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; Y.Env._eventstack.prevented = 1; this.events.fire('prevented', this); } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { this._yuievt.targets[Y.stamp(o)] = o; this._yuievt.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { return Y.Object.values(this._yuievt.targets); }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { delete this._yuievt.targets[Y.stamp(o)]; }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {Event.Custom} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target) { var targs = this._yuievt.targets, ret = true, t, type = evt && evt.type, ce, i, bc, ce2, originalTarget = target || (evt && evt.target) || this, es = Y.Env._eventstack, oldbubble; if (!evt || ((!evt.stopped) && targs)) { // Y.log('Bubbling ' + evt.type); for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t.getEvent(type, true); ce2 = t.getSibling(type, ce); if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget); } } else { ce.sibling = ce2; // set the original target to that the target payload on the // facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = Y.Object.keys(FACADE); })(); }, '@VERSION@' ,{requires:['event-custom-base']}); YUI.add('event-custom', function(Y){}, '@VERSION@' ,{use:['event-custom-base', 'event-custom-complex']});
src/modules/editor/components/popovers/addTooltip/AddTooltipMenuItemButton/AddTooltipMenuItemButton.js
CtrHellenicStudies/Commentary
import React from 'react'; import './AddTooltipMenuItemButton.css'; const AddTooltipMenuItemButton = props => ( <button className={`addTooltipMenuItemButton ${props.className}`} onClick={props.onClick} > {props.children} </button> ); export default AddTooltipMenuItemButton;
src/svg-icons/image/compare.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageCompare = (props) => ( <SvgIcon {...props}> <path d="M10 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h5v2h2V1h-2v2zm0 15H5l5-6v6zm9-15h-5v2h5v13l-5-6v9h5c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ImageCompare = pure(ImageCompare); ImageCompare.displayName = 'ImageCompare'; ImageCompare.muiName = 'SvgIcon'; export default ImageCompare;
packages/material-ui/src/CardActionArea/CardActionArea.js
Kagami/material-ui
// @inheritedComponent ButtonBase import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import ButtonBase from '../ButtonBase'; export const styles = theme => ({ /* Styles applied to the root element. */ root: { display: 'block', textAlign: 'inherit', width: '100%', '&:hover $focusHighlight': { opacity: theme.palette.action.hoverOpacity, }, '&$focusVisible $focusHighlight': { opacity: 0.12, }, }, /* Styles applied to the ButtonBase root element if the action area is keyboard focused. */ focusVisible: {}, /* Styles applied to the overlay that covers the action area when it is keyboard focused. */ focusHighlight: { pointerEvents: 'none', position: 'absolute', backgroundColor: 'currentcolor', top: 0, right: 0, bottom: 0, left: 0, opacity: 0, transition: theme.transitions.create('opacity', { duration: theme.transitions.duration.short, }), }, }); function CardActionArea(props) { const { children, classes, className, focusVisibleClassName, ...other } = props; return ( <ButtonBase className={classNames(classes.root, className)} focusVisibleClassName={classNames(focusVisibleClassName, classes.focusVisible)} {...other} > {children} <span className={classes.focusHighlight} /> </ButtonBase> ); } CardActionArea.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css-api) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * @ignore */ focusVisibleClassName: PropTypes.string, }; export default withStyles(styles, { name: 'MuiCardActionArea' })(CardActionArea);
src/common/components/TimelineNodeEditor/TimelineForm/TimelineVariableTable.js
jspsych/jsPsych-Redux-GUI
import React from 'react'; import { findDOMNode } from 'react-dom' import Divider from 'material-ui/Divider'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import IconButton from 'material-ui/IconButton'; import Subheader from 'material-ui/Subheader'; import TextField from 'material-ui/TextField'; import { List, ListItem } from 'material-ui/List'; import { Toolbar, ToolbarGroup, ToolbarSeparator } from 'material-ui/Toolbar'; import SvgIcon from 'material-ui/SvgIcon'; import CheckBoxIcon from 'material-ui/svg-icons/toggle/radio-button-checked'; import UnCheckBoxIcon from 'material-ui/svg-icons/toggle/radio-button-unchecked'; import Launch from 'material-ui/svg-icons/action/launch'; import UndoIcon from 'material-ui/svg-icons/content/undo'; import NumberIcon from 'material-ui/svg-icons/image/looks-one'; import ArrayIcon from 'material-ui/svg-icons/action/view-array'; import StringIcon from 'material-ui/svg-icons/editor/text-fields'; import LongStringIcon from 'material-ui/svg-icons/editor/insert-comment'; import ObjectIcon from 'material-ui/svg-icons/editor/mode-edit'; import FunctionIcon from 'material-ui/svg-icons/action/code'; import MediaIcon from 'material-ui/svg-icons/image/photo-library'; import { renderDialogTitle } from '../../gadgets'; import CodeEditor, { CodeLanguage } from '../../CodeEditor'; import ArrayEditor from '../../../containers/ArrayEditor'; import ObjectEditor from '../../../containers/ObjectEditor'; import MediaManager from '../../../containers/MediaManager'; import { CommonComponents, CommonComponentsStyle } from '../CommonComponents'; import flow from 'lodash/flow'; import { DropTarget, DragSource } from 'react-dnd'; /*************** Constants and Helper ***************/ const constants = { GhostCellWidth: 50, CellHeight: 60, CellWidth: 175, DND: { contentRow: 'Timeline-Variable-Table-Content-Row-Item' } } const colors = { ...theme.colors, labelColor: '#B1B1B1', functionColor: '#708', arrayColor: theme.colors.secondaryDeep, objectColor: '#00BCD4', mediaColor: '#2196F3' }; const cssStyle = { MySheet: { root: utils.prefixer({ width: 720, maxWidth: 720, minWidth: 720, height: 300, maxHeight: 300, minHeight: 300, overflow: 'auto' }) }, HeaderRow: { root: utils.prefixer({ display: 'flex' }) }, Cell: { root: utils.prefixer({ width: constants.CellWidth, maxWidth: constants.CellWidth, minWidth: constants.CellWidth, justifyContent: 'center', alignItems: 'center', display: 'flex', height: constants.CellHeight, minHeight: constants.CellHeight, maxHeight: constants.CellHeight }) }, GhostCell: { root: utils.prefixer({ width: constants.GhostCellWidth, minWidth: constants.GhostCellWidth, maxWidth: constants.GhostCellWidth, justifyContent: 'center', alignItems: 'center', display: 'flex', height: constants.CellHeight, minHeight: constants.CellHeight, maxHeight: constants.CellHeight }) }, HeaderCell: { Container: utils.prefixer({ width: '90%', height: '90%', }), Label: utils.prefixer({ textOverflow: 'ellipsis', overflow: 'hidden', fontWeight: 'bold', whiteSpace: 'nowrap', color: colors.primary, maxHeight: 48, }) }, ContentCell: { row: utils.prefixer({ display: 'flex', flexBasis: 'auto' }), Container: utils.prefixer({ width: '90%', height: '90%', }), Label: utils.prefixer({ textOverflow: 'ellipsis', overflow: 'hidden', fontWeight: 'bold', textAlign: 'center', whiteSpace: 'nowrap', color: colors.primary, maxHeight: 48, }) } } // material-ui style const style = { Icon: { color: colors.primaryDeep, // hoverColor: colors.secondary }, TextFieldFocusStyle: { ...theme.TextFieldFocusStyle() }, triggerIconStyle: { hoverColor: colors.secondary }, deleteIconStyle: { color: colors.secondaryDeep, hoverColor: colors.secondary }, addIconStyle: { ...theme.Icon }, iconSize: { width: 36, height: 36 }, undoIconStyle: { hoverColor: colors.secondary }, codeIconStyle: { color: colors.primaryDeep, hoverColor: colors.secondary }, TriggerStyle: { ...CommonComponentsStyle.TriggerStyle, fullWidth: true }, TriggerIconStyle: { ...CommonComponentsStyle.TriggerIconStyle }, ContentCellTextFieldFocus: { underlineFocusStyle: { borderColor: colors.primaryDeep } } }; // Custom SVG Icon const mySvgIcons = { AddRowIcon: (props) => ( <SvgIcon {...props}> <path d="M14.651 5.521V3.23H1.42v5.238h5.072c-.108.42-.172.858-.172 1.312 0 .037.005.073.005.11H0V1.809h16.072v5.254a5.284 5.284 0 0 0-1.421-1.542z"/> <path d="M11.7 14.263a4.378 4.378 0 0 0 4.372-4.373A4.377 4.377 0 0 0 11.7 5.517 4.377 4.377 0 0 0 7.327 9.89a4.379 4.379 0 0 0 4.373 4.373zm0-1.188a3.19 3.19 0 0 1-3.185-3.186A3.19 3.19 0 0 1 11.7 6.703a3.19 3.19 0 0 1 3.186 3.186 3.189 3.189 0 0 1-3.186 3.186z"/> <path d="M9.806 10.44V9.299h1.332V7.995h1.142v1.304h1.315v1.141H12.28v1.344h-1.142V10.44z"/> </SvgIcon> ), DeleteRowIcon: (props) => ( <SvgIcon {...props}> <path d="M0 1.732v7.732h6.053c0-.035-.004-.07-.004-.104 0-.434.061-.854.165-1.255H1.36V3.092h12.662v2.192c.546.396 1.01.897 1.359 1.477V1.732H0z"/> <path d="M11.196 5.28c-2.307 0-4.183 1.877-4.183 4.184 0 2.308 1.876 4.185 4.183 4.185 2.309 0 4.185-1.877 4.185-4.185 0-2.307-1.876-4.184-4.185-4.184zm0 7.233c-1.679 0-3.047-1.367-3.047-3.049 0-1.68 1.368-3.049 3.047-3.049 1.684 0 3.05 1.369 3.05 3.049 0 1.682-1.366 3.049-3.05 3.049z"/> <path d="M9.312 8.759h3.844v1.104H9.312z"/> </SvgIcon> ), AddColumnIcon: (props) => ( <SvgIcon {...props}> <path d="M6.237 16.546H3.649V1.604h5.916v5.728a5.92 5.92 0 0 1 1.479-.194c.042 0 .083.006.125.006V0H2.044v18.15h5.934a5.98 5.98 0 0 1-1.741-1.604z"/> <path d="M11.169 8.275c-2.723 0-4.938 2.215-4.938 4.938s2.215 4.938 4.938 4.938 4.938-2.215 4.938-4.938-2.215-4.938-4.938-4.938zm0 8.535a3.601 3.601 0 0 1-3.598-3.598c0-1.983 1.614-3.597 3.598-3.597s3.597 1.613 3.597 3.597a3.6 3.6 0 0 1-3.597 3.598z"/> <path d="M11.792 11.073h-1.29v1.505H9.03v1.29h1.472v1.484h1.29v-1.484h1.517v-1.29h-1.517z"/> </SvgIcon> ), DeleteColumnIcon: (props) => ( <SvgIcon {...props}> <path d="M6.237 16.546H3.649V1.604h5.916v5.728c.474-.122.968-.194 1.479-.194.042 0 .083.006.125.006V0H2.044v18.15h5.934c-.683-.414-1.274-.96-1.741-1.604z"/> <path d="M11.169 8.275c-2.723 0-4.938 2.215-4.938 4.938s2.215 4.938 4.938 4.938 4.938-2.215 4.938-4.938-2.215-4.938-4.938-4.938zm0 8.535c-1.983 0-3.598-1.612-3.598-3.598 0-1.983 1.614-3.597 3.598-3.597s3.597 1.613 3.597 3.597c0 1.986-1.613 3.598-3.597 3.598z"/> <path d="M9.312 12.759h3.844v1.104H9.312z"/> </SvgIcon> ) } const matchInputTypeIcon = (type) => { switch (type) { case enums.TimelineVariableInputType.NUMBER: return <NumberIcon {...style.Icon} />; case enums.TimelineVariableInputType.MEDIA: return <MediaIcon {...style.Icon} />; case enums.TimelineVariableInputType.ARRAY: return <ArrayIcon {...style.Icon} />; case enums.TimelineVariableInputType.OBJECT: return <ObjectIcon {...style.Icon} />; case enums.TimelineVariableInputType.TEXT: return <StringIcon {...style.Icon} />; case enums.TimelineVariableInputType.LONG_TEXT: return <LongStringIcon {...style.Icon} />; case enums.TimelineVariableInputType.FUNCTION: return <FunctionIcon {...style.Icon} />; default: return null; } } const ContentCellLabelItem = ({onClick=()=>{}, value='', label='', rightIcon=null, labelStyle={}}) => ( <ListItem containerElement="div" onClick={onClick} primaryText={ <div style={{ ...cssStyle.ContentCell.Label, ...labelStyle }} title={`${value}`} > {label} </div> } rightIcon={rightIcon} /> ) /*************** Constants and Helper functions and components ***************/ /*************** Header Cell ***************/ class HeaderCell extends React.Component { constructor(props) { super(props); this.state = { // dialog open open: false, // header name variableName: this.props.variableName, // this header column input type type: this.props.type } this.handleOpen = () => { this.setState({ open: true, variableName: this.props.variableName, }) } this.handleClose = () => { this.setState({ open: false }) } this.setVariableName = (name) => { let c = name === this.props.variableName ? 0 : 1; for (let n of this.props.headers) { if (n === name) { c++; } } let error = name === '' || c > 1; this.setState({ variableName: name, error: error, errorText: error ? (c > 1 ? 'Variable name duplicated!' : 'Invalid variable name!') : '' }) } this.setType = (type) => { this.setState({ type: type }) } this.onCommit = () => { if (this.state.error) { this.props.notifyError(this.state.errorText); return; } let recordHistory = false; if (this.state.variableName !== this.props.variableName) { this.props.updateTimelineVariableName(this.props.variableName, this.state.variableName); this.props.recordHistory(); } if (this.state.type !== this.props.type) { let isBothString = utils.isString(this.state.type) && utils.isString(this.props.type); let isTargetFunction = utils.isFunction(this.state.type); if (isBothString || isTargetFunction) { this.props.updateenums.TimelineVariableInputType(this.state.variableName, this.state.type, false); this.props.recordHistory(); } else { this.props.notifyConfirm( 'Value will be cleared for type coercion. Do you want to continue?', () => { this.props.updateenums.TimelineVariableInputType(this.state.variableName, this.state.type, true); this.props.recordHistory(); } ); } } this.handleClose(); } this.onCancel = () => { this.setVariableName(this.props.variableName); this.setType(this.props.type); this.handleClose(); } } static defaultProps = { type: enums.TimelineVariableInputType.TEXT, variableName: "" } render() { let actions = [ <FlatButton label="Cancel" labelStyle={{ color: colors.secondaryDeep }} onClick={this.onCancel} />, <FlatButton label="Save" labelStyle={{ color: colors.primaryDeep }} onClick={this.onCommit} />, ] return ( <div style={{ border: `1px solid ${colors.primaryDeep}`, ...cssStyle.Cell.root, }}> <div style={{ ...cssStyle.HeaderCell.Container }} > <ListItem containerElement="div" onClick={this.handleOpen} primaryText={ <div style={{ ...cssStyle.HeaderCell.Label }} title={`${this.props.variableName}`} > {this.state.variableName} </div> } rightIconButton={ <IconButton disableTouchRipple onClick={this.handleOpen} tooltip={this.props.type} > {matchInputTypeIcon(this.props.type)} </IconButton> } /> </div> <Dialog modal open={this.state.open} titleStyle={{padding: 0}} actions={actions} > <TextField autoFocus id="TV-Table-Variable-Name_Field" {...theme.TextFieldFocusStyle(this.state.error)} errorText={this.state.errorText} floatingLabelText="Variable Name" floatingLabelFixed value={this.state.variableName} onChange={(event, newVal) => this.setVariableName(newVal)} /> <Divider /> <List> { Object.values(enums.TimelineVariableInputType).map((v, i) => ( <ListItem key={`Input-Type-Choice-${v}-${i}`} primaryText={v} onClick={()=>{this.setType(v);}} rightIcon={ v === this.state.type ? <CheckBoxIcon color={colors.primary}/>: <UnCheckBoxIcon color={colors.primary}/> } /> )) } </List> </Dialog> </div> ) } } /*************** Header Cell ***************/ /*************** Content Cell ***************/ class ContentCell extends React.Component { constructor(props) { super(props); this.state = { edit: false, valueObject: utils.deepCopy(this.props.valueObject) } this.handleEdit = () => { this.setState({ edit: true, // init valueObject: utils.deepCopy(this.props.valueObject) }); } this.handleCloseEdit = () => { this.setState({ edit: false, }); this.onCommit(); } this.setValue = (newVal, callback=()=>{}, isNormalValue=true) => { let clone = utils.deepCopy(this.state.valueObject); if (isNormalValue) { clone.value = newVal; } else { clone.func.code = newVal; } this.setState({ valueObject: clone }, callback ) } this.setCode = (code, callback=()=>{}) => { let clone = utils.deepCopy(this.state.valueObject); clone.func.code = code; this.setState({ valueObject: clone }, callback ) } this.onCommit = () => { if (!utils.deepEqual(this.state.valueObject, this.props.valueObject)) { this.props.updateCell(this.props.columnName, this.props.rowNum, this.state.valueObject); this.props.recordHistory(); } } this.isSelected = () => { return this.props.selectedRow === this.props.rowNum && this.props.selectedCol === this.props.colNum; } this.onCellSelect = () => { this.props.onCellSelect({row: this.props.rowNum, col: this.props.colNum}) } this.renderTextFieldDialog = () => { let actions = [ <FlatButton label="Cancel" labelStyle={{ color: colors.secondaryDeep }} onClick={this.handleClose} />, <FlatButton label="Save" labelStyle={{ color: colors.primaryDeep }} onClick={this.onCommit} />, ] let isNumber = this.props.type === enums.TimelineVariableInputType.NUMBER, value = isNumber ? this.props.valueObject.value : utils.toEmptyString(this.props.valueObject.value), label = isNumber ? value : `"${value}"`, stateValue = utils.toEmptyString(this.state.valueObject.value); return ( !this.state.edit ? <ContentCellLabelItem onClick={this.handleEdit} value={value} label={label} /> : <div style={{width: '100%', height: '100%'}}> <TextField autoFocus fullWidth type={isNumber ? 'number' : 'text'} id="TV-Table-Variable-Cell" {...style.ContentCellTextFieldFocus} value={stateValue} onChange={(event, newVal) => this.setValue(newVal)} onBlur={this.handleCloseEdit} onKeyPress={(e) => { if (e.which === 13) { this.handleCloseEdit(); } }} /> </div> ) } this.renderEditor = () => { let value, label; switch(this.props.type) { case enums.TimelineVariableInputType.TEXT: case enums.TimelineVariableInputType.NUMBER: return this.renderTextFieldDialog(); case enums.TimelineVariableInputType.LONG_TEXT: case enums.TimelineVariableInputType.FUNCTION: let isValueString = utils.isString(this.props.type); value = utils.toEmptyString(isValueString ? this.props.valueObject.value : this.props.valueObject.func.code), label = isValueString ? `"${value}"` : (value || 'void'); return ( <CodeEditor value={value} onCommit={(v) => { this.setValue(v, this.onCommit, isString); }} Trigger={ ({onClick}) => ( <ContentCellLabelItem onClick={onClick} value={value} label={label} labelStyle={isValueString ? {} : { color: colors.functionColor, textDecoration: 'underline' }} /> ) } language={isValueString ? CodeLanguage.html[0] : CodeLanguage.javascript[0]} onlyString={isValueString} onlyFunction={!isValueString} evalAsFunction={!isValueString} tooltip="Edit value" /> ) case enums.TimelineVariableInputType.ARRAY: // must be array value = this.props.valueObject.value; let len = value.length; label = len < 2 ? `[0 item]` : `[${len} items]`; return ( <ArrayEditor value={value} onCommit={(v) => { this.setValue(v, this.onCommit); }} Trigger={ ({onClick}) => ( <ContentCellLabelItem onClick={onClick} value={value} label={label} labelStyle={{color: colors.arrayColor, textDecoration: 'underline'}} /> ) } /> ); case enums.TimelineVariableInputType.OBJECT: value = this.props.valueObject.value; label = "[Data Object]"; return ( <ObjectEditor value={value} onCommit={(v) => { this.setValue(v, this.onCommit); }} Trigger={ ({onClick}) => ( <ContentCellLabelItem onClick={onClick} value={value} label={label} labelStyle={{color: colors.objectColor, textDecoration: 'underline'}} /> ) } /> ); case enums.TimelineVariableInputType.MEDIA: value = this.props.valueObject.value; if (value.length > 0) { label = value[0].replace('<path>', '').replace('</path>', ''); } else { label = "[No File]" } return ( <MediaManager selected={value} onCommit={(v) => { this.setValue(v, this.onCommit); }} mode={enums.MediaManagerMode.select} Trigger_insert={ ({onClick}) => ( <ContentCellLabelItem onClick={onClick} value={value} label={label} labelStyle={{color: colors.mediaColor, textDecoration: 'underline'}} /> ) } /> ) default: return null; } } } static defaultProps = { // JspsychValueObject valueObject: {}, // input type, enums.TimelineVariableInputType ENUM type: '', // column name columnName: '', // column number colNum: -1, // row number rowNum: -1, } render() { let { rowNum, colNum, onCellSelect, selectedRow, selectedCol, onCellDeselect } = this.props; let isSelected = selectedRow === rowNum && selectedCol === colNum, borderColor = isSelected ? colors.secondary : colors.primaryDeep, borderWeight = isSelected ? 2 : 1; return ( <div style={{ border: `${borderWeight}px solid ${borderColor}`, ...cssStyle.Cell.root, cursor: 'crosshair' }} onClick={() => { if (isSelected) { onCellDeselect(); } else { this.onCellSelect(); } } } > <div style={{ ...cssStyle.ContentCell.Container }} onBlur={onCellDeselect} > {this.renderEditor()} </div> </div> ) } } /*************** Content Cell ***************/ /*************** Placeholder Cell and Drag and Drop Handler ***************/ class GhostCell extends React.Component { constructor(props) { super(props); } static defaultProps = { // if is ghost (placeholder) cell of header row isHeaderRow: false, rowNum: 0, } render() { let { isHeaderRow, isDragging } = this.props; return ( <div style={{ ...cssStyle.GhostCell.root, border: `1px solid ${colors.primaryDeep}`, ...utils.prefixer({ cursor: isHeaderRow ? 'auto' : 'pointer' }) }} title={this.props.title} > { isHeaderRow ? null : `${this.props.rowNum+1}.` } </div> ) } } /*************** Placeholder Cell and Drag and Drop Handler ***************/ /*************** Header Row ***************/ class HeaderRow extends React.Component { constructor(props) { super(props); } static defaultProps = { // headers, safely map row content to corresponding header headers: [], // this.props.inputType mapping from redux inputType: {}, } render() { let { headers, inputType } = this.props; return ( <div style={{ ...cssStyle.HeaderRow.root }} > <GhostCell isHeaderRow={true}/> { headers && headers.map((header, i) => { let type = inputType[header]; return ( <HeaderCell key={`timeline-variable-header-${i}`} variableName={header} type={type} {...this.props} /> ) }) } </div> ) } } /*************** Header Row ***************/ /*************** Content Row ***************/ const contentRowItemDnD = { ITEM_TYPE: constants.DND.contentRow, itemSource: { beginDrag(props) { return { rowId: props.rowId, rowNum: props.rowNum }; }, isDragging(props, monitor) { return props.rowId === monitor.getItem().rowId; } }, itemTarget: { // better this way since we always want hover (for preview effects) canDrop() { return false; }, hover(props, monitor, component) { const {rowId: draggedId, rowNum: dragIndex } = monitor.getItem() const {rowId: overId, rowNum: hoverIndex } = props; if (dragIndex === hoverIndex) return; const hoverBoundingRect = findDOMNode(component).getBoundingClientRect(); // Get vertical middle const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; // Determine mouse position const clientOffset = monitor.getClientOffset(); // Get pixels to the top const hoverClientY = clientOffset.y - hoverBoundingRect.top; // Only perform the move when the mouse has crossed half of the items height // When dragging downwards, only move when the cursor is below 50% // When dragging upwards, only move when the cursor is above 50% // Dragging downwards if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) return; // Dragging upwards if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) return; props.moveTo(dragIndex, hoverIndex); monitor.getItem().rowNum = hoverIndex; } }, sourceCollector: (connect, monitor) => ({ connectDragSource: connect.dragSource(), connectDragPreview: connect.dragPreview(), isDragging: monitor.isDragging(), }), targetCollector: (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), isOverCurrent: monitor.isOver({ shallow: true }), }) } class ContentRow extends React.Component { constructor(props) { super(props); } static defaultProps = { // {} of [{},...,{}] row: {}, // headers, safely map row content to corresponding header headers: [], // this.props.inputType mapping from redux inputType: {}, rowNum: 0, } render() { let { row, headers, rowNum, inputType, connectDropTarget, connectDragPreview, connectDragSource, isDragging } = this.props; let isSelected; return connectDragPreview(connectDropTarget( <div style={{ ...cssStyle.ContentCell.row, border: isDragging ? `2px dotted ${colors.secondary}` : 'none', width: headers.length * constants.CellWidth + constants.GhostCellWidth }} > {connectDragSource(<div><GhostCell rowNum={rowNum} isDragging={isDragging}/></div>)} { headers && headers.map((cell, i) => { let columnName = headers[i], valueObject = row[columnName]; return ( <ContentCell key={`timeline-variable-cell-${rowNum}-${i}`} columnName={columnName} valueObject={valueObject} type={inputType[columnName]} colNum={i} {...this.props} /> ) }) } </div> )) } } ContentRow = flow( DragSource( contentRowItemDnD.ITEM_TYPE, contentRowItemDnD.itemSource, contentRowItemDnD.sourceCollector ), DropTarget( contentRowItemDnD.ITEM_TYPE, contentRowItemDnD.itemTarget, contentRowItemDnD.targetCollector ) )(ContentRow); /*************** Content Row ***************/ /*************** Main part: Table Sheet ***************/ class MySheet extends React.Component { constructor(props) { super(props); } static defaultProps = { // using jsPsych timeline variable structure [{}...] table: [], // this.props.inputType mapping from redux inputType: {} } render() { let { table, headers, rowIds } = this.props; return ( <div style={{ ...cssStyle.MySheet.root }} > <HeaderRow headers={headers} {...this.props}/> { table && table.map((row, i) => ( <ContentRow key={`timeline-variable-row-${i}`} rowId={rowIds[i]} {...this.props} headers={headers} row={table[i]} rowNum={i} /> )) } </div> ) } } MySheet = utils.withDnDContext(MySheet); /*************** Main part: Table Sheet ***************/ /*************** Table Dialog and Trigger ***************/ class TimelineVariableTableOpener extends React.Component { constructor(props) { super(props); this.onRowDelete = () => { if (this.props.selectedRow === null) { this.props.notifyWarningBySnackbar('Select a row first !') return; } else { this.props.deleteRow(this.props.selectedRow); this.props.recordHistory(); } } this.onColDelete = () => { if (this.props.selectedCol === null) { this.props.notifyWarningBySnackbar('Select a column first !') return; } else { this.props.deleteColumn(this.props.selectedCol); this.props.recordHistory(); } } this.onRowAdd = () => { this.props.addRow(); this.props.recordHistory(); } this.onColumnAdd = () => { this.props.addColumn(); this.props.recordHistory(); } this.renderToolbar = () => ( <Toolbar className="Appbar-tools" style={{backgroundColor: 'white', flexGrow: '1'}}> <ToolbarGroup firstChild={true}> <IconButton tooltip="Insert Row" onClick={this.onRowAdd} iconStyle={{...style.iconSize}} > <mySvgIcons.AddRowIcon {...style.addIconStyle}/> </IconButton> <IconButton tooltip="Delete Row" onClick={this.onRowDelete} iconStyle={{...style.iconSize}} > <mySvgIcons.DeleteRowIcon {...style.deleteIconStyle}/> </IconButton> <ToolbarSeparator /> <IconButton tooltip="Insert Column" onClick={this.onColumnAdd} iconStyle={{...style.iconSize}} > <mySvgIcons.AddColumnIcon {...style.addIconStyle}/> </IconButton> <IconButton tooltip="Delete Column" onClick={this.onColDelete} iconStyle={{...style.iconSize}} > <mySvgIcons.DeleteColumnIcon {...style.deleteIconStyle}/> </IconButton> <ToolbarSeparator /> <IconButton tooltip="Undo" disabled={this.props.history.length === 0} onClick={this.props.handleUndo} > <UndoIcon {...style.undoIconStyle}/> </IconButton> </ToolbarGroup> </Toolbar> ) } static defaultProps = { // using jsPsych timeline variable structure [{}...] table: [], // this.props.inputType mapping from redux inputType: {} } render() { return ( <div> <FlatButton {...style.TriggerStyle} label={"Open Timeline Table"} onClick={this.props.handleOpen} icon={<Launch {...style.TriggerIconStyle}/>} /> <Dialog open={this.props.open} contentStyle={{minHeight: 700}} titleStyle={{padding: 0}} style={{zIndex: 1000}} title={renderDialogTitle( <Subheader style={{maxHeight: 58}}>{this.renderToolbar()}</Subheader>, this.props.handleClose, null, {borderTop: `10px solid ${colors.primaryDeep}`} )} modal={true} bodyStyle={{ paddingTop: '25px', paddingBottom: '50px', borderTop: '1px solid #aaa' }} > <MySheet {...this.props} /> </Dialog> </div> ) } } /*************** Table Dialog and Trigger ***************/ /*************** Table Wrapper ***************/ export default class TimelineVariableTable extends React.Component { constructor(props) { super(props); this.state = { open: false, history: [], selectedRow: null, selectedCol: null, } this.handleOpen = () => { this.setState({ open: true, history: [] }) } this.handleClose = () => { this.setState({ open: false, history: [] }) } this.recordHistory = () => { let history = this.state.history.slice(); history.push(utils.deepCopy(this.props.parameters)); this.setState({ history: history }) } this.handleUndo = () => { if (this.state.history.length > 0) { this.props.setTable(this.state.history.pop()); } } this.onCellSelect = ({row, col}) => { this.setState({ selectedRow: row, selectedCol: col, }) } this.onCellDeselect = () => { this.setState({ selectedRow: null, selectedCol: null, }) } this.moveTo = (sourceIndex, targetIndex) => { this.props.moveTo(sourceIndex, targetIndex); this.onCellDeselect(); } } render() { return ( <div className="Trial-Form-Item-Container"> <CommonComponents.CustomFloatingLabelField label="Timeline Variables" node={ <TimelineVariableTableOpener open={this.state.open} handleOpen={this.handleOpen} handleClose={this.handleClose} handleUndo={this.handleUndo} recordHistory={this.recordHistory} history={this.state.history} onCellSelect={this.onCellSelect} onCellDeselect={this.onCellDeselect} selectedRow={this.state.selectedRow} selectedCol={this.state.selectedCol} {...this.props} moveTo={this.moveTo} /> } /> </div> ) } } /*************** Table Wrapper ***************/
src/components/AddTodo.js
gsans/todo-react
import React from 'react' export default class AddTodo extends React.Component { _onSubmit () { this.props.addTodo(this.input.value) this.input.value = '' } render () { return ( <div> <input ref={node => (this.input = node)} /> <button onClick={e => this._onSubmit()}> Add Todo </button> </div> ) } }
qmarkit/config/webpackDevServer.config.js
lcgong/alchemy
"use strict"; const errorOverlayMiddleware = require("react-dev-utils/errorOverlayMiddleware"); const noopServiceWorkerMiddleware = require("react-dev-utils/noopServiceWorkerMiddleware"); const ignoredFiles = require("react-dev-utils/ignoredFiles"); const config = require("./webpack.config.dev"); const paths = require("./paths"); const protocol = process.env.HTTPS === "true" ? "https" : "http"; const host = process.env.HOST || "0.0.0.0"; module.exports = function(proxy, allowedHost) { return { // WebpackDevServer 2.4.3 introduced a security fix that prevents remote // websites from potentially accessing local content through DNS rebinding: // https://github.com/webpack/webpack-dev-server/issues/887 // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a // However, it made several existing use cases such as development in cloud // environment or subdomains in development significantly more complicated: // https://github.com/facebookincubator/create-react-app/issues/2271 // https://github.com/facebookincubator/create-react-app/issues/2233 // While we're investigating better solutions, for now we will take a // compromise. Since our WDS configuration only serves files in the `public` // folder we won't consider accessing them a vulnerability. However, if you // use the `proxy` feature, it gets more dangerous because it can expose // remote code execution vulnerabilities in backends like Django and Rails. // So we will disable the host check normally, but enable it if you have // specified the `proxy` setting. Finally, we let you override it if you // really know what you're doing with a special environment variable. disableHostCheck: !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === "true", // Enable gzip compression of generated files. compress: true, // Silence WebpackDevServer's own logs since they're generally not useful. // It will still show compile warnings and errors with this setting. clientLogLevel: "none", // By default WebpackDevServer serves physical files from current directory // in addition to all the virtual build products that it serves from memory. // This is confusing because those files won’t automatically be available in // production build folder unless we copy them. However, copying the whole // project directory is dangerous because we may expose sensitive files. // Instead, we establish a convention that only files in `public` directory // get served. Our build script will copy `public` into the `build` folder. // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. // Note that we only recommend to use `public` folder as an escape hatch // for files like `favicon.ico`, `manifest.json`, and libraries that are // for some reason broken when imported through Webpack. If you just want to // use an image, put it in `src` and `import` it from JavaScript instead. contentBase: paths.appPublic, // By default files from `contentBase` will not trigger a page reload. watchContentBase: true, // Enable hot reloading server. It will provide /sockjs-node/ endpoint // for the WebpackDevServer client so it can learn when the files were // updated. The WebpackDevServer client is included as an entry point // in the Webpack development configuration. Note that only changes // to CSS are currently hot reloaded. JS changes will refresh the browser. hot: true, // It is important to tell WebpackDevServer to use the same "root" path // as we specified in the config. In development, we always serve from /. publicPath: config.output.publicPath, // WebpackDevServer is noisy by default so we emit custom message instead // by listening to the compiler events with `compiler.plugin` calls above. quiet: true, // Reportedly, this avoids CPU overload on some systems. // https://github.com/facebookincubator/create-react-app/issues/293 // src/node_modules is not ignored to support absolute imports // https://github.com/facebookincubator/create-react-app/issues/1065 watchOptions: { ignored: ignoredFiles(paths.appSrc) }, // Enable HTTPS if the HTTPS environment variable is set to 'true' https: protocol === "https", host: host, overlay: false, historyApiFallback: { // Paths with dots should still use the history fallback. // See https://github.com/facebookincubator/create-react-app/issues/387. disableDotRule: true }, public: allowedHost, proxy, before(app) { // This lets us open files from the runtime error overlay. app.use(errorOverlayMiddleware()); // This service worker file is effectively a 'no-op' that will reset any // previous service worker registered for the same host:port combination. // We do this in development to avoid hitting the production cache if // it used the same host and port. // https://github.com/facebookincubator/create-react-app/issues/2272#issuecomment-302832432 app.use(noopServiceWorkerMiddleware()); } }; };
examples/js/hacker-news/client/containers/Header.js
reimagined/resolve
import React from 'react' import { useStaticResolver } from '@resolve-js/react-hooks' import { Helmet } from 'react-helmet' const Header = ({ title, css, favicon }) => { const asset = useStaticResolver() const stylesheetLinks = css.map((sheet) => ({ rel: 'stylesheet', href: asset(sheet), })) const faviconLink = { rel: 'icon', type: 'image/png', href: asset(favicon) } const links = [...stylesheetLinks, faviconLink] const meta = { name: 'viewport', content: 'width=device-width, initial-scale=1', } return <Helmet title={title} link={links} meta={[meta]} /> } export { Header }
src/Button/index.js
reactivers/react-mcw
/** * Created by Utku on 24/03/2017. */ import React from 'react'; import PropTypes from 'prop-types'; import '@material/button/dist/mdc.button.css'; import classNames from 'classnames'; import generateId from '../utils/generateId'; export default class Button extends React.PureComponent{ static propTypes={ className : PropTypes.string, primary : PropTypes.bool, accent : PropTypes.bool, textColor : PropTypes.string, buttonColor : PropTypes.string, style : PropTypes.object, raised : PropTypes.bool, onClick : PropTypes.func, disabled :PropTypes.bool, dense :PropTypes.bool, compact : PropTypes.bool, }; static defaultProps={ dense : false, compact : false, disabled : false } componentWillMount(){ this.buttonId = generateId(); }; render(){ const{className,dense,compact,style,textColor,buttonColor,raised,primary,accent,...rest} = this.props; const classes = classNames("mdc-button",{ "mdc-button--accent" : accent, "mdc-button--primary" : primary, "mdc-button--raised" : raised, "mdc-button--dense" : dense, "mdc-button--compact" : compact, },className) let buttonStyle = Object.assign({},style,{backgroundColor : buttonColor,color:textColor,fontWeight : "bold"}); return( <button className={classes} key={this.props.key || this.buttonId} style={buttonStyle} {...rest}> {this.props.children} </button> ) } }
pootle/static/js/auth/components/SignInForm.js
mail-apps/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ 'use strict'; import assign from 'object-assign'; import React from 'react'; import { FormElement } from 'components/forms'; import { FormMixin } from 'mixins/forms'; let SignInForm = React.createClass({ mixins: [FormMixin], propTypes: { canRegister: React.PropTypes.bool.isRequired, formErrors: React.PropTypes.object.isRequired, isLoading: React.PropTypes.bool.isRequired, }, /* Lifecycle */ getInitialState() { // XXX: initialData required by `FormMixin`; this is really OBSCURE this.initialData = { login: '', password: '', }; return { formData: assign({}, this.initialData), }; }, componentWillReceiveProps(nextProps) { if (this.state.errors !== nextProps.formErrors) { this.setState({errors: nextProps.formErrors}); } }, /* Handlers */ handleRequestPasswordReset(e) { e.preventDefault(); this.props.flux.getActions('auth').gotoScreen('requestPasswordReset'); }, handleSignUp(e) { e.preventDefault(); this.props.flux.getActions('auth').gotoScreen('signUp'); }, handleFormSubmit(e) { e.preventDefault(); let nextURL = window.location.pathname + window.location.hash; this.props.flux.getActions('auth').signIn(this.state.formData, nextURL); }, /* Others */ hasData() { let { formData } = this.state; return formData.login !== '' && formData.password !== ''; }, /* Layout */ render() { let { errors } = this.state; let { formData } = this.state; let signUp = this.props.canRegister ? <a href="#" onClick={this.handleSignUp}> {gettext('Sign up as a new user')} </a> : <p>{gettext('Creating new user accounts is prohibited.')}</p>; return ( <form method="post" onSubmit={this.handleFormSubmit} > <div className="fields"> <FormElement attribute="login" label={gettext('Username')} autoFocus={true} handleChange={this.handleChange} formData={formData} errors={errors} /> <FormElement type="password" attribute="password" label={gettext('Password')} handleChange={this.handleChange} formData={formData} errors={errors} /> <div className="actions password-forgotten"> <a href="#" onClick={this.handleRequestPasswordReset}> {gettext('I forgot my password')} </a> </div> {this.renderAllFormErrors()} </div> <div className="actions"> <div> <input type="submit" className="btn btn-primary" disabled={!this.hasData() || this.props.isLoading} value={gettext('Sign In')} /> </div> <div> {signUp} </div> </div> </form> ); } }); export default SignInForm;
webApp/src/Components/BroadcastLive.js
s-law/silent-disco
import React from 'react'; // ROUTER import { History } from 'react-router'; import reactMixin from 'react-mixin'; // COMPONENTS import NavBar from './NavBar.js'; import BroadcastLiveView from './BroadcastLiveView.js'; import Loading from './Loading.js'; // VISUALIZER import visualizer from './visualizer.js'; // CLIENTID import SC_Client from '../../server/config/apiKeys'; // AJAX GET CALL import $ from '../../public/js/jquery-1.11.1.min'; // MATERIAL UI import Card from 'material-ui/lib/card/card'; var BASE_URL = window.protocol + document.location.host; class BroadcastLive extends React.Component { constructor(props) { var user = JSON.parse(localStorage.getItem("me")); super(props); this.state = { disabled: false, hasBroadcasted: false, heartCount: 0, listenerLiveCount: 0, listenerMaxCount: 0, listenerTotalCount: 0, name: "", description: "", artist: user.full_name || "", artistAlias: user.username || "", artistImage: user.avatar_url, streamImage: "", selectedSource: null, audioSources: [], isLoading: true, songQueue:[], search: "", searchResults:[], nextSearch:'', currentSong: { title:"", genre:"", artwork_url:"", user: { avatar_url:"" } }, endedSongQueue:[] }; } gotMediaDevices(devices) { var audioSources = []; devices.forEach(function(device) { if (device.kind === 'audio') { audioSources.push({ id: device.id, label: device.label || 'Input ' + audioSources.length + 1 }) } }); this.setState({ audioSources: audioSources }); } componentWillMount() { this.bc = new Broadcaster(this.props.params.streamId, this.gotMediaDevices.bind(this), visualizer); this.fetchData(); } componentDidMount(){ //add bclient on handler here window.bClient.on('stream', this.handleSocketEvent.bind(this)); } componentWillUnmount() { window.bClient.off('stream', this.handleSocketEvent.bind(this)); if(this.state.disabled){ var PUT_STREAM_STATUS = BASE_URL + '/api/stream/status/' + this.props.params.streamId; $.ajax({ url: PUT_STREAM_STATUS, method: 'PUT', contentType: "application/x-www-form-urlencoded", data: '' }) .done((responseData) => { this.bc.stop(); this.setState({ disabled: false }); }); } } fetchData() { $.ajax({ url: '/api/stream/' + this.props.params.streamId }) .done((stream) => { let fav = JSON.parse(localStorage.getItem("favorites")); this.setState({ name: stream.name, description: stream.description, heartCount: stream.heartCountNum, listenerLiveCount: stream.listenerLiveCount, listenerMaxCount: stream.listenerMaxCount, listenerTotalCount: stream.listenerTotalCount, isLoading: false, creator: stream.creator, broadcaster: stream.broadcaster, streamImage: stream.streamImage, playing: stream.playing, favorites: fav }); }); } handleSocketEvent(data, meta) { if (meta.type === 'event') { if (meta.action === 'enterStream' || meta.action === 'leaveStream' || meta.action === 'upHeart') { if (meta.streamId === this.props.params.streamId) { $.ajax({ url: '/api/stream/' + this.props.params.streamId }) .done((stream) => { this.setState({ heartCount: stream.heartCountNum, listenerLiveCount: stream.listenerLiveCount, listenerMaxCount: stream.listenerMaxCount, listenerTotalCount: stream.listenerTotalCount }); }); } } } } startHTMLBroadcast() { if (this.state.currentSong.title) { this.setState({ disabled: true }, () => { this.bc.startFromHTML("soundcloudPlayer"); }); } } startBroadcast() { if (this.state.selectedSource) { this.setState({ disabled: true }, () => { this.bc.start(this.state.selectedSource); }); } } stopBroadcast() { var PUT_STREAM_STATUS = BASE_URL + '/api/stream/status/' + this.props.params.streamId; $.ajax({ url: PUT_STREAM_STATUS, method: 'PUT', contentType: "application/x-www-form-urlencoded", data: '' }) .done((responseData) => { this.setState({ disabled: false, hasBroadcasted: true }, () => { this.bc.stop(); }); }); } handleMediaEnd() { let newQueue = this.state.songQueue; let endedQueue = this.state.endedSongQueue; if (newQueue.length === 1) { let playedSong = newQueue.shift(); endedQueue.push(playedSong); this.setState({ songQueue: newQueue, currentSong: { title:"", genre:"", artwork_url:"", user: { avatar_url:"" } }, endedSongQueue: endedQueue }); } else if (newQueue.length>1) { let playedSong = newQueue.shift(); endedQueue.push(playedSong); this.setState({ songQueue: newQueue, currentSong: newQueue[0], endedSongQueue: endedQueue }); } } sourceInput(event, index, value) { this.setState({ selectedSource: value }); } goToProfile() { this.props.history.push({ pathname: '/user/' + this.state.creator }); } addSongToQueue(selectedSong) { let newQueue = this.state.songQueue; newQueue.push(selectedSong); if (newQueue.length === 1) { this.setState({ songQueue: newQueue, currentSong: newQueue[0] }); } else { this.setState({ songQueue: newQueue }); } } submitSearch(query) { SC.initialize({ client_id: SC_Client.clientID }); var page_size = 10; SC.get('/tracks', { limit: page_size, linked_partitioning: 1, q: query }).then((tracks) => { // page through results, 100 at a time this.setState({ searchResults:tracks.collection, nextSearch:tracks.next_href }); }); } loadMoreSongs() { let query = this.state.nextSearch; $.get(query).then((tracks) => { // page through results, 100 at a time this.setState({ search: "", searchResults:tracks.collection, nextSearch:tracks.next_href || '' }); }); } removeSongFromQueue(song) { let newQueue = this.state.songQueue; newQueue.splice(song,1); this.setState({ songQueue: newQueue }); } render() { var partial = <Loading /> if (!this.state.isLoading) { partial = <BroadcastLiveView addSongToQueue={this.addSongToQueue.bind(this)} removeSongFromQueue={this.removeSongFromQueue.bind(this)} sourceInput={this.sourceInput.bind(this)} goProfile={this.goToProfile.bind(this)} startBroadcast={this.startBroadcast.bind(this)} stopBroadcast={this.stopBroadcast.bind(this)} startHTMLBroadcast={this.startHTMLBroadcast.bind(this)} handleMediaEnd={this.handleMediaEnd.bind(this)} submitSearch={this.submitSearch.bind(this)} loadMoreSongs={this.loadMoreSongs.bind(this)} isLive={this.props.location.state.isLive} state={this.state} /> } return ( <Card style={styles.container}> <NavBar title="Broadcast" history={this.history}/> {partial} </Card> ) } } var styles = { container:{ 'maxWidth': '1280px', 'margin': '15px auto', 'display': 'flex', 'flexDirection' :'column' } } reactMixin.onClass(BroadcastLive, History); export default BroadcastLive;
src/atoms/Trackable/__tests__/trackable.spec.js
policygenius/athenaeum
import React from 'react'; import { expect } from 'chai'; import { shallow, mount } from 'enzyme'; import Trackable from 'atoms/Trackable'; import { dataAttributes, dataAttrName } from 'atoms/Trackable/utils'; describe('<Trackable />', () => { describe('dataAttributes()', () => { it('takes a string and returns a lower+kebab case prefixed with data-', () => { expect(dataAttrName('SoMe Name')).to.be.equal('data-some-name'); }); it('takes an object and returns data-attributes', () => { const data = { name: 100, noName: 101 }; const dataAttr = dataAttributes(data); const dataKeys = Object.keys(data); const attrKeys = Object.keys(dataAttr); expect(attrKeys.length).to.equal(dataKeys.length); expect(attrKeys.includes(`data-${dataKeys[0]}`)).to.be.true; }); }); describe('renders', () => { it('child with data-attributes', () => { const data = { test: 100, womp: 1337 }; const wrapper = shallow( <Trackable data={data}> <div /> </Trackable> ); expect(wrapper.contains(<div data-test={data.test} data-womp={data.womp}></div>)).to.be.true; }); it('does not render nested Trackables', () => { const data1 = { womp: 101 }; const data2 = { womp: 1337 }; const wrapper = mount( <Trackable data={data2}> <Trackable data={data1}> <div /> </Trackable> </Trackable> ); expect(wrapper.contains(<div data-womp={101}></div>)).to.be.true; }); }); });
examples/js/cell-edit/blur-to-save-table.js
dana2208/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); const cellEditProp = { mode: 'click', blurToSave: true }; export default class BlurToSaveTable extends React.Component { render() { return ( <BootstrapTable data={ products } cellEdit={ cellEditProp }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
modules/dreamview/frontend/src/components/PNCMonitor/ScatterGraph.js
xiaoxq/apollo
import React from 'react'; import Chart from 'chart.js'; import _ from 'lodash'; import STORE from 'store'; const defaultPolygonProperties = { color: 'rgba(255, 0, 0, 0.8)', // red borderWidth: 2, pointRadius: 0, fill: false, showLine: true, showText: true, cubicInterpolationMode: 'monotone', lineTension: 0, }; Chart.plugins.register({ afterDatasetsDraw(chart, easing) { const fontSize = 15; const fontStyle = 'normal'; const fontFamily = 'Helvetica Neue'; chart.config.data.datasets.forEach((dataset, index) => { if (dataset.showText) { const meta = chart.getDatasetMeta(index); const element = meta.data[Math.floor(meta.data.length / 2)]; chart.ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily); chart.ctx.fillStyle = dataset.borderColor; chart.ctx.textAlign = 'center'; chart.ctx.textBaseline = 'middle'; const padding = 1; const position = element.tooltipPosition(); chart.ctx.fillText(dataset.text, position.x, position.y - (fontSize / 2) - padding); } else if (dataset.specialMarker === 'car') { chart.ctx.save(); const meta = chart.getDatasetMeta(index); const rotation = chart.data.datasets[index].data[0].heading || 0; const xAxis = chart.scales['x-axis-0']; const yAxis = chart.scales['y-axis-0']; const pixelPerUnit = { x: xAxis.width / (xAxis.max - xAxis.min), y: yAxis.height / (yAxis.max - yAxis.min), }; const dx = Math.cos(rotation) > 0 ? 1 : -1; const dy = Math.tan(rotation) * dx; const xInPixels = dx * pixelPerUnit.x; const yInPixels = dy * pixelPerUnit.y; const rotationInPixels = Math.atan2(yInPixels, xInPixels); const element = meta.data[0]; const position = element.tooltipPosition(); chart.ctx.font = Chart.helpers.fontString(20, fontStyle, fontFamily); chart.ctx.translate(position.x, position.y); chart.ctx.rotate(-rotationInPixels); // ChartJS's rotation is clockwise chart.ctx.fillStyle = dataset.borderColor; chart.ctx.fillText('\u27A1︎\uFE0E' /* ➡ */, 0, 0); chart.ctx.restore(); } }); }, }); Chart.defaults.global.defaultFontColor = '#FFFFFF'; function updateTickWindow(scale, windowSize, midValue) { const mid = midValue || Math.floor((scale.max + scale.min) / 2); scale.max = mid + windowSize / 2; scale.min = mid - windowSize / 2; } function syncXYWindowSize(scale) { function isValidValue(value) { return value !== null && value !== undefined && !isNaN(value) && isFinite(value); } function IDMatches(meta) { return scale.isHorizontal() ? meta.xAxisID === scale.id : meta.yAxisID === scale.id; } // calculate the range for both x and y const min = { x: null, y: null, }; const max = { x: null, y: null, }; const chart = scale.chart; const datasets = chart.data.datasets; Chart.helpers.each(datasets, (dataset, datasetIndex) => { const meta = chart.getDatasetMeta(datasetIndex); if (chart.isDatasetVisible(datasetIndex) && IDMatches(meta)) { Chart.helpers.each(dataset.data, (rawValue, index) => { if (!isValidValue(rawValue.x) || !isValidValue(rawValue.y) || meta.data[index].hidden) { return; } if (min.x === null || rawValue.x < min.x) { min.x = rawValue.x; } if (max.x === null || rawValue.x > max.x) { max.x = rawValue.x; } if (min.y === null || rawValue.y < min.y) { min.y = rawValue.y; } if (max.y === null || rawValue.y > max.y) { max.y = rawValue.y; } }); } }); // set min/max based on the larger range if (isValidValue(min.x) && isValidValue(min.y) && isValidValue(max.x) && isValidValue(max.y)) { const max_diff = Math.max(max.x - min.x, max.y - min.y); const mid = scale.isHorizontal() ? Math.floor((max.x + min.x) / 2) : Math.floor((max.y + min.y) / 2); scale.max = mid + max_diff / 2; scale.min = mid - max_diff / 2; } } export default class ScatterGraph extends React.Component { initializeCanvas(title, options) { this.name2idx = {}; const chartOptions = { title: { display: (title && title.length > 0), text: title, }, legend: { display: options.legend.display, labels: { filter: (legendItem, data) => { const hideLabel = _.get(data, `datasets[${legendItem.datasetIndex}].hideLabelInLegend`, false); return !hideLabel; }, }, }, tooltips: { enable: true, mode: 'nearest', intersect: false, }, aspectRatio: options.aspectRatio, }; if (options.axes) { if (!chartOptions.scales) { chartOptions.scales = {}; } for (const axis in options.axes) { const name = `${axis}Axes`; const setting = options.axes[axis]; const axisOptions = { id: `${axis}-axis-0`, scaleLabel: { display: !_.isEmpty(setting.labelString), labelString: setting.labelString, }, ticks: { min: setting.min, max: setting.max, minRotation: 0, maxRotation: 0, stepSize: setting.stepSize, // Overwrite chartjs tick formatter to keep maximum 4 decimals // and avoid scientific notation callback(tickValue, index, ticks) { // If we have lots of ticks, don't use the ones let delta = ticks.length > 3 ? ticks[2] - ticks[1] : ticks[1] - ticks[0]; // If we have a number like 2.5 as the delta, // figure out how many decimal places we need if (Math.abs(delta) > 1) { if (tickValue !== Math.floor(tickValue)) { // not an integer delta = tickValue - Math.floor(tickValue); } } const logDelta = Math.log10(Math.abs(delta)); let tickString = ''; if (Math.abs(tickValue) >= 1e-4) { let numDecimal = -1 * Math.floor(logDelta); numDecimal = Math.max(Math.min(numDecimal, 4), 0); tickString = tickValue.toFixed(numDecimal); } else { tickString = '0'; // never show decimal places for 0 } return tickString; }, }, gridLines: { color: 'rgba(153, 153, 153, 0.5)', zeroLineColor: 'rgba(153, 153, 153, 0.7)', }, }; if (!chartOptions.scales[name]) { chartOptions.scales[name] = []; } if (setting.windowSize) { axisOptions.afterDataLimits = (scale) => { updateTickWindow(scale, setting.windowSize, setting.midValue); }; } else if (options.syncXYWindowSize) { axisOptions.afterDataLimits = syncXYWindowSize; } chartOptions.scales[name].push(axisOptions); } } const ctx = this.canvasElement.getContext('2d'); this.chart = new Chart(ctx, { type: 'scatter', options: chartOptions }); } constructDataConfig(properties) { // basic properties const config = { label: null, // legend hideLabelInLegend: properties.hideLabelInLegend, showText: properties.showText, text: null, // text in the graph backgroundColor: properties.color, borderColor: properties.color, data: null, }; // additional properties for (const key in properties) { config[key] = properties[key]; } return config; } updateData(idx, name, properties, data) { const datasets = this.chart.data.datasets; const config = this.constructDataConfig(properties); if (datasets[idx] === undefined) { datasets.push(config); } else if (datasets[idx].text !== name) { datasets[idx] = config; } datasets[idx].label = name; datasets[idx].text = name; datasets[idx].data = data; } updateCar(name, point, properties) { // draw heading arrow { const arrowName = name; if (this.name2idx[arrowName] === undefined) { this.name2idx[arrowName] = this.chart.data.datasets.length; } const idx = this.name2idx[arrowName]; const arrowProperties = properties; arrowProperties.specialMarker = 'car'; arrowProperties.borderWidth = 0; arrowProperties.pointRadius = 0; this.updateData(idx, arrowName, arrowProperties, [point]); } // draw ego-vehicle bounding box { const polygonName = `${name}_car_bounding_box`; if (this.name2idx[polygonName] === undefined) { this.name2idx[polygonName] = this.chart.data.datasets.length; } const idx2 = this.name2idx[polygonName]; const polygon = STORE.hmi.calculateCarPolygonPoints(point.x, point.y, point.heading); const polygonProperties = { borderWidth: 1, pointRadius: 0, color: properties.color, showLine: true, fill: false, lineTension: 0, hideLabelInLegend: true, }; this.updateData(idx2, polygonName, polygonProperties, polygon); } } updateChart(props) { if (!props.data || !props.properties) { return; } const datasets = props.data; // Draw cars for (const name in props.properties.cars) { const nameInString = JSON.stringify(name); const point = _.get(datasets, `cars[${nameInString}]`, {}); const properties = _.get(props, `properties.cars[${nameInString}]`, {}); this.updateCar(name, point, properties); } // Draw lines for (const name in props.properties.lines) { if (this.name2idx[name] === undefined) { this.name2idx[name] = this.chart.data.datasets.length; } const idx = this.name2idx[name]; const nameInString = JSON.stringify(name); const properties = _.get(props, `properties.lines[${nameInString}]`, {}); const points = _.get(datasets, `lines[${nameInString}]`, []); this.updateData(idx, name, properties, points); } // Draw polygons let idx = Object.keys(this.name2idx).length; if (datasets.polygons) { for (const name in datasets.polygons) { const nameInString = JSON.stringify(name); const points = _.get(datasets, `polygons[${nameInString}]`); if (!points) { continue; } const properties = _.get(props, `properties.polygons[${nameInString}]`, defaultPolygonProperties); this.updateData(idx, name, properties, points); idx++; } } // Remove un-used polygons data this.chart.data.datasets.splice(idx, this.chart.data.datasets.length - idx); // Update chart this.chart.update(0); } componentDidMount() { const { title, options } = this.props; this.initializeCanvas(title, options); this.updateChart(this.props); } componentWillUnmount() { this.chart.destroy(); } componentWillReceiveProps(nextProps) { this.updateChart(nextProps); } render() { const { title, options, properties, data, } = this.props; return ( <div className="scatter-graph"> <canvas ref={(input) => { this.canvasElement = input; }} /> </div> ); } } function generateScatterGraph(setting, lineDatasets, carDatasets, polygonsDatasets) { if (!lineDatasets) { console.error('Graph data not found:', setting.title); return null; } if (!setting || !setting.properties || !setting.options) { console.error('Graph setting not found:', setting.title); return null; } return ( <ScatterGraph key={setting.title} title={setting.title} options={setting.options} properties={setting.properties} data={{ lines: lineDatasets, cars: carDatasets, polygons: polygonsDatasets }} /> ); } export { generateScatterGraph, };
app/react-icons/fa/500px.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class Fa500px extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m35.3 34.5l-0.2 0.2q-2.5 2.5-5.7 3.9-3.5 1.4-7.1 1.4-3.7 0-7.1-1.4-3.3-1.4-5.8-3.9-2.5-2.5-3.9-5.8-0.9-2.3-1.2-4.2-0.1-0.6 1.1-0.8 1.1-0.2 1.2 0.4 0.1 0.1 0.1 0.1 0.4 2 1 3.6 1.1 2.7 3.4 5 2.2 2.2 5 3.4 3 1.3 6.2 1.3 3.2 0 6.1-1.3 2.9-1.2 5.1-3.4l0.1-0.1q0.2-0.2 0.6-0.2 0.2 0.1 0.7 0.5 0.8 0.9 0.4 1.3z m-10.6-13.7l-1.4 1.5 1.4 1.4q0.4 0.5-0.2 1.1-0.4 0.4-0.7 0.4-0.2 0-0.4-0.3l-1.4-1.3-1.5 1.4q-0.1 0.2-0.3 0.2-0.4 0-0.7-0.4l-0.1 0q-0.4-0.4-0.4-0.7 0-0.1 0.2-0.4l1.5-1.4-1.5-1.5q-0.3-0.4 0.3-1 0.4-0.4 0.7-0.4 0.2 0 0.3 0.1l1.5 1.5 1.4-1.5q0.4-0.3 1.1 0.3 0.6 0.6 0.2 1z m10.6 1.3q0 2.6-1.1 5.1-1 2.3-2.8 4.1-1.8 1.8-4.2 2.8t-5.1 1.1-5-1.1-4.2-2.8q-1.8-1.8-2.8-4.1-0.3-0.7-0.3-0.9h-0.1q-0.2-0.6 1-1 1.1-0.4 1.3 0.3 0.9 2.2 2.2 3.7h0v-7.6q0.1-3.1 2.3-5.2 2.3-2.3 5.6-2.3 3.3 0 5.7 2.3t2.3 5.6q0 3.2-2.4 5.6t-5.6 2.3q-1.2 0-2.5-0.4-0.6-0.2-0.2-1.3 0.3-1.2 0.9-1l0.4 0.1q0.3 0 0.7 0.1t0.7 0.1q2.3 0 3.9-1.6t1.6-3.9q0-2.3-1.6-3.8-1.6-1.6-3.9-1.6-2.4 0-4 1.8-1.4 1.6-1.4 3.5v9.2q2.4 1.5 5.4 1.5 2.1 0 4.1-0.8t3.5-2.3 2.3-3.4 0.8-4.1q0-4.4-3.1-7.6-3.2-3.1-7.6-3.1-4.5 0-7.6 3.1-1.2 1.2-1.7 1.9l0 0.1q-0.2 0.2-0.3 0.3t-0.5 0.3-0.9-0.1q-0.4-0.1-0.8-0.4t-0.3-0.6v-15.2q0-0.3 0.2-0.5t0.6-0.3h19.6q0.7 0 0.7 1.2t-0.7 1.3h-18.1v10.7h0q0.9-0.9 2.3-1.8t2.4-1.4q2.4-1 5.1-1 2.7 0 5.1 1t4.2 2.8q1.8 1.8 2.8 4.2 1 2.5 1 5.1z m-0.7-13q0.2 0.2 0.2 0.4t-0.2 0.4-0.3 0.5q-0.6 0.6-0.9 0.6-0.2 0-0.4-0.2-2.3-2-4.6-3-2.8-1.2-6.1-1.2-3 0-5.9 1.1-0.6 0.2-1-0.8-0.2-0.6-0.2-0.9 0.1-0.4 0.4-0.4 2.9-1.3 6.7-1.3 3.6 0 7 1.4 3.1 1.3 5.3 3.4z"/></g> </IconBase> ); } }
src/components/ControlPanel/ControlPanel.js
mulesoft-labs/mule-match
import React from 'react'; import propTypes from './PropTypes'; import styles from './ControlPanel.css'; const onIgnoreFeature = (e, currentFeature, ignoreFeature) => { e.preventDefault(); ignoreFeature(currentFeature); }; const onSelectFeature = (e, currentFeature, selectFeature) => { e.preventDefault(); selectFeature(currentFeature); }; const ControlPanel = ({ currentFeature, selectFeature, ignoreFeature }) => ( <div className={styles.controlPanel}> <div display-if={currentFeature} className={styles.buttonNo} onClick={(e) => onIgnoreFeature(e, currentFeature, ignoreFeature)}> <a href="#" className={styles.triggerNo}></a> </div> <div display-if={currentFeature} className={styles.buttonInfo}> <a href={currentFeature.url} className={styles.triggerInfo} target="_blank"></a> </div> <div display-if={currentFeature} className={styles.buttonYes} onClick={(e) => onSelectFeature(e, currentFeature, selectFeature)}> <a href="#" className={styles.triggerYes}></a> </div> </div> ); ControlPanel.propTypes = propTypes; export default ControlPanel;
RCTRealtimeMessagingAndroid.js
realtime-framework/RCTRealtimeMessagingAndroid
// Created by Joao Caixinha on 02/04/15. // Copyright (c) 2015 Realtime. All rights reserved. // /** * @providesModule RCTRealtimeMessagingAndroid * @flow */ 'use strict'; import React, { Component } from 'react'; import { NativeModules } from 'react-native'; var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ortcClient = NativeModules.RealtimeMessagingAndroid; var RTEvents = {}; var instances = 0; class RCTRealtimeMessagingAndroid extends React.Component { id: String; RCTRealtimeMessagingAndroid(){ this.id = instances++; } constructor(props) { super(props); this.id = instances++; } RTConnect(config){ ortcClient.connect(config, this.id); } RTDisconnect(){ ortcClient.disconnect(this.id); } RTSubscribe(channel, subscribeOnReconnect: boolean){ ortcClient.subscribe(channel, subscribeOnReconnect, this.id); } RTSubscribeWithFilter(channel, subscribeOnReconnect: boolean, filter){ ortcClient.subscribeWithFilter(channel, subscribeOnReconnect, filter, this.id); } RTSubscribeWithBuffer(channel, subscriberId){ ortcClient.subscribeWithBuffer(channel, subscriberId, this.id); } RTSubscribeWithOptions(options){ ortcClient.subscribeWithOptions(options, this.id); } RTSubscribeWithNotifications(channel, subscribeOnReconnect: boolean){ ortcClient.subscribeWithNotifications(channel, subscribeOnReconnect, this.id); } RTUnsubscribe(channel){ ortcClient.unsubscribe(channel, this.id); } RTPublishMessage(channel, message, ttl, callBack){ ortcClient.publish(channel, message, ttl, this.id, callBack); } RTSendMessage(message, channel){ ortcClient.sendMessage(message, channel, this.id); } RTEnablePresence(aPrivateKey, channel, aMetadata:boolean){ ortcClient.enablePresence(aPrivateKey, channel, aMetadata, this.id); } RTDisablePresence(aPrivateKey, channel){ ortcClient.disablePresence(aPrivateKey, channel, this.id); } RTPresence(channel){ ortcClient.presence(channel, this.id); } RTIsSubscribed(channel, callBack: Function){ ortcClient.isSubscribed(channel, this.id, callBack); } // RTSaveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, callBack: Function){ // ortcClient.saveAuthentication(url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, this.id, callBack); // } RTGetHeartbeatTime(callBack: Function){ ortcClient.getHeartbeatTime(this.id, callBack); } RTSetHeartbeatTime(newHeartbeatTime){ ortcClient.setHeartbeatTime(newHeartbeatTime, this.id); } RTGetHeartbeatFails(callBack: Function){ ortcClient.getHeartbeatFails(this.id, callBack); } RTSetHeartbeatFails(newHeartbeatFails){ ortcClient.setHeartbeatFails(newHeartbeatFails, this.id); } RTIsHeartbeatActive(callBack: Function){ ortcClient.isHeartbeatActive(this.id, callBack); } RTEnableHeartbeat(){ ortcClient.enableHeartbeat(this.id); } RTDisableHeartbeat(){ ortcClient.disableHeartbeat(this.id); } /* Events list - onConnected - onDisconnect - onReconnect - onReconnecting - onSubscribed - onUnSubscribed - onExcption - onMessage - onPresence - onDisablePresence - onEnablePresence */ RTPushNotificationListener(callBack: Function){ require('RCTDeviceEventEmitter').addListener( 'onPushNotification', callBack ); ortcClient.checkForNotifications(); }; RTEventListener(notification, callBack: Function){ var modNotification = String(this.id) + '-' + notification; var channelExists = RTEvents[modNotification]; if (channelExists){ this.RTRemoveEventListener(notification); } RTEvents[modNotification] = ( require('RCTDeviceEventEmitter').addListener( modNotification, callBack ) ); }; RTRemoveEventListener(notification) { var modNotification = String(this.id) + '-' + notification; RTEvents[modNotification].remove(), delete RTEvents[modNotification]; }; } module.exports = RCTRealtimeMessagingAndroid;
node_modules/react-icons/lib/io/eye.js
bairrada97/festival
'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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var IoEye = function IoEye(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm17.5 10c7.7 0 13.4 5.5 17.5 10.1-4 3.9-9.7 9.9-17.5 9.9s-12.3-4.7-17.5-10c6.1-6.2 11.1-10 17.5-10z m0 17.1c3.8 0 7-3.2 7-7.1s-3.2-7.1-7-7.1-7 3.2-7 7.1 3.2 7.1 7 7.1z m0-9.6c0 1.4 1.1 2.5 2.5 2.5 0.6 0 1.1-0.2 1.6-0.5v0.5c0 2.3-1.8 4.1-4.1 4.1s-4.1-1.8-4.1-4.1 1.8-4.1 4.1-4.1h0.6c-0.4 0.4-0.6 1-0.6 1.6z' }) ) ); }; exports.default = IoEye; module.exports = exports['default'];
public/client.js
chtefi/react-isomorphic
import React from 'react'; import App from './App'; const payload = window.INITIAL_PAYLOAD; React.render(<App {...payload} />, document.getElementById('app'));
src/router/Logout.js
change-soft8/cs-project-antd
import React from 'react' const Logout = React.createClass({ render() { return <p>You are now logged out</p> } }) module.exports = Logout
src/containers/App/App.js
hahoocn/hahoo-admin
import React from 'react'; class App extends React.Component { static propTypes = { children: React.PropTypes.node, }; state = {} render() { // require('./App.css'); return ( <div> {this.props.children} </div> ); } } export default App;
ajax/libs/iCheck/1.0.1/demo/js/jquery.js
SirenHound/cdnjs
/*! * jQuery v1.8.3 jquery.com | jquery.org/license */ (function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={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,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
src/svg-icons/editor/insert-invitation.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorInsertInvitation = (props) => ( <SvgIcon {...props}> <path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/> </SvgIcon> ); EditorInsertInvitation = pure(EditorInsertInvitation); EditorInsertInvitation.displayName = 'EditorInsertInvitation'; EditorInsertInvitation.muiName = 'SvgIcon'; export default EditorInsertInvitation;
stories/InputString.stories.js
maputnik/editor
import React from 'react'; import {useActionState} from './helper'; import InputString from '../src/components/InputString'; import {InputContainer} from './ui'; import {withA11y} from '@storybook/addon-a11y'; export default { title: 'InputString', component: InputString, decorators: [withA11y], }; export const Basic = () => { const [value, setValue] = useActionState("onChange", "Hello world"); return ( <InputContainer> <InputString value={value} onChange={setValue} /> </InputContainer> ); }; export const WithDefault = () => { const [value, setValue] = useActionState("onChange", null); return ( <InputContainer> <InputString value={value} default={"Edit me..."} onChange={setValue} /> </InputContainer> ); }; export const Multiline = () => { const [value, setValue] = useActionState("onChange", "Hello\nworld"); return ( <InputContainer> <InputString multi={true} value={value} onChange={setValue} /> </InputContainer> ); }; export const MultilineWithDefault = () => { const [value, setValue] = useActionState("onChange", null); return ( <InputContainer> <InputString multi={true} default={"Edit\nme.."} value={value} onChange={setValue} /> </InputContainer> ); };
test/PaginationSpec.js
Cellule/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import Pagination from '../src/Pagination'; describe('Pagination', function () { it('Should have class', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination>Item content</Pagination> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pagination')); }); it('Should show the correct active button', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} activePage={3} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); assert.equal(pageButtons.length, 5); React.findDOMNode(pageButtons[2]).className.should.match(/\bactive\b/); }); it('Should call onSelect when page button is selected', function (done) { function onSelect(event, selectedEvent) { assert.equal(selectedEvent.eventKey, 2); done(); } let instance = ReactTestUtils.renderIntoDocument( <Pagination items={5} onSelect={onSelect} /> ); ReactTestUtils.Simulate.click( ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a')[1] ); }); it('Should only show part of buttons and active button in the middle of buttons when given maxButtons', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination items={30} activePage={10} maxButtons={9} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // 9 visible page buttons and 1 ellipsis button assert.equal(pageButtons.length, 10); // active button is the second one assert.equal(React.findDOMNode(pageButtons[0]).firstChild.innerText, '6'); React.findDOMNode(pageButtons[4]).className.should.match(/\bactive\b/); }); it('Should show the ellipsis, first, last, prev and next button', function () { let instance = ReactTestUtils.renderIntoDocument( <Pagination first={true} last={true} prev={true} next={true} maxButtons={3} activePage={10} items={20} /> ); let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li'); // add first, last, prev, next and ellipsis button assert.equal(pageButtons.length, 8); assert.equal(React.findDOMNode(pageButtons[0]).innerText, '«'); assert.equal(React.findDOMNode(pageButtons[1]).innerText, '‹'); assert.equal(React.findDOMNode(pageButtons[5]).innerText, '...'); assert.equal(React.findDOMNode(pageButtons[6]).innerText, '›'); assert.equal(React.findDOMNode(pageButtons[7]).innerText, '»'); }); });
packages/react-native-codegen/src/generators/components/GenerateShadowNodeH.js
hammerandchisel/react-native
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow strict * @format */ 'use strict'; import type {SchemaType} from '../../CodegenSchema'; // File path -> contents type FilesOutput = Map<string, string>; const template = ` /** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #pragma once ::_IMPORTS_::#include <react/components/::_LIBRARY_::/Props.h> #include <react/components/view/ConcreteViewShadowNode.h> namespace facebook { namespace react { ::_COMPONENT_CLASSES_:: } // namespace react } // namespace facebook `; const componentTemplate = ` extern const char ::_CLASSNAME_::ComponentName[]; /* * \`ShadowNode\` for <::_CLASSNAME_::> component. */ using ::_CLASSNAME_::ShadowNode = ConcreteViewShadowNode< ::_CLASSNAME_::ComponentName, ::_CLASSNAME_::Props::_EVENT_EMITTER_::>; `.trim(); module.exports = { generate( libraryName: string, schema: SchemaType, moduleSpecName: string, ): FilesOutput { const fileName = 'ShadowNodes.h'; let hasAnyEvents = false; const moduleResults = Object.keys(schema.modules) .map(moduleName => { const components = schema.modules[moduleName].components; // No components in this module if (components == null) { return null; } return Object.keys(components) .map(componentName => { const component = components[componentName]; if (component.interfaceOnly === true) { return; } const hasEvents = component.events.length > 0; if (hasEvents) { hasAnyEvents = true; } const eventEmitter = hasEvents ? `,\n${componentName}EventEmitter` : ''; const replacedTemplate = componentTemplate .replace(/::_CLASSNAME_::/g, componentName) .replace('::_EVENT_EMITTER_::', eventEmitter); return replacedTemplate; }) .join('\n\n'); }) .filter(Boolean) .join('\n\n'); const eventEmitterImport = `#include <react/components/${libraryName}/EventEmitters.h>\n`; const replacedTemplate = template .replace(/::_COMPONENT_CLASSES_::/g, moduleResults) .replace('::_LIBRARY_::', libraryName) .replace('::_IMPORTS_::', hasAnyEvents ? eventEmitterImport : ''); return new Map([[fileName, replacedTemplate]]); }, };
src/js/graph.js
bcongdon/sgdq-stats
import ReactDOM from 'react-dom' import React from 'react' import GraphApp from './GraphApp.js' import { createStore, applyMiddleware } from 'redux' import { Provider } from 'react-redux' import reducers from './reducers' import reduxThunk from 'redux-thunk' import 'react-select/dist/react-select.css' const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore) const store = createStoreWithMiddleware(reducers) ReactDOM.render( <Provider store={store}> <GraphApp /> </Provider>, document.getElementById('react-root') )
demo/components/textarea/TextAreaOptions.js
ctco/rosemary-ui
import React from 'react'; import {TextArea} from '../../../src'; import OptionsTable from '../../helper/OptionsTable'; export default () => { let propDescription = { }; return ( <OptionsTable component={TextArea} propDescription={propDescription} /> ); };
ajax/libs/6to5/1.14.9/browser.js
calvinf/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.to5=e()}}(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(require,module,exports){(function(global){var transform=module.exports=require("./transformation/transform");transform.transform=transform;transform.run=function(code,opts){opts=opts||{};opts.sourceMap="inline";return new Function(transform(code,opts).code)()};transform.load=function(url,callback,opts,hold){opts=opts||{};opts.filename=opts.filename||url;var xhr=global.ActiveXObject?new global.ActiveXObject("Microsoft.XMLHTTP"):new global.XMLHttpRequest;xhr.open("GET",url,true);if("overrideMimeType"in xhr)xhr.overrideMimeType("text/plain");xhr.onreadystatechange=function(){if(xhr.readyState!==4)return;var status=xhr.status;if(status===0||status===200){var param=[xhr.responseText,opts];if(!hold)transform.run.apply(transform,param);if(callback)callback(param)}else{throw new Error("Could not load "+url)}};xhr.send(null)};var runScripts=function(){var scripts=[];var types=["text/ecmascript-6","text/6to5"];var index=0;var exec=function(){var param=scripts[index];if(param instanceof Array){transform.run.apply(transform,param);index++;exec()}};var run=function(script,i){var opts={};if(script.src){transform.load(script.src,function(param){scripts[i]=param;exec()},opts,true)}else{opts.filename="embedded";scripts[i]=[script.innerHTML,opts]}};var _scripts=global.document.getElementsByTagName("script");for(var i in _scripts){var _script=_scripts[i];if(types.indexOf(_script.type)>=0)scripts.push(_script)}for(i in scripts){run(scripts[i],i)}exec()};if(global.addEventListener){global.addEventListener("DOMContentLoaded",runScripts,false)}else if(global.attachEvent){global.attachEvent("onload",runScripts)}}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transformation/transform":29}],2:[function(require,module,exports){module.exports=File;var SHEBANG_REGEX=/^\#\!.*/;var transform=require("./transformation/transform");var generate=require("./generation/generator");var Scope=require("./traverse/scope");var util=require("./util");var t=require("./types");var _=require("lodash");function File(opts){this.opts=File.normaliseOptions(opts);this.uids={};this.ast={}}File.declarations=["extends","class-props","apply-constructor","tagged-template-literal","interop-require","to-array","object-spread","has-own","slice"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{experimental:false,playground:false,whitespace:true,blacklist:[],whitelist:[],sourceMap:false,comments:true,filename:"unknown",modules:"common",runtime:false,code:true});opts.filename=opts.filename.replace(/\\/g,"/");opts.blacklist=util.arrayify(opts.blacklist);opts.whitelist=util.arrayify(opts.whitelist);_.defaults(opts,{moduleRoot:opts.sourceRoot});_.defaults(opts,{sourceRoot:opts.moduleRoot});_.defaults(opts,{filenameRelative:opts.filename});_.defaults(opts,{sourceFileName:opts.filenameRelative,sourceMapName:opts.filenameRelative});if(opts.runtime===true){opts.runtime="to5Runtime"}if(opts.playground){opts.experimental=true}transform._ensureTransformerNames("blacklist",opts.blacklist);transform._ensureTransformerNames("whitelist",opts.whitelist);return opts};File.prototype.toArray=function(node){if(t.isArrayExpression(node)){return node}else if(t.isIdentifier(node)&&node.name==="arguments"){return t.callExpression(t.memberExpression(this.addDeclaration("slice"),t.identifier("call")),[node])}else{return t.callExpression(this.addDeclaration("to-array"),[node])}};File.prototype.getModuleFormatter=function(type){var ModuleFormatter=_.isFunction(type)?type:transform.moduleFormatters[type];if(!ModuleFormatter){var loc=util.resolve(type);if(loc)ModuleFormatter=require(loc)}if(!ModuleFormatter){throw new ReferenceError("unknown module formatter type "+type)}return new ModuleFormatter(this)};File.prototype.parseShebang=function(code){var shebangMatch=code.match(SHEBANG_REGEX);if(shebangMatch){this.shebang=shebangMatch[0];code=code.replace(SHEBANG_REGEX,"")}return code};File.prototype.addDeclaration=function(name){if(!_.contains(File.declarations,name)){throw new ReferenceError("unknown declaration "+name)}var program=this.ast.program;var declar=program._declarations&&program._declarations[name];if(declar)return declar.id;var ref;var runtimeNamespace=this.opts.runtime;if(runtimeNamespace){name=t.identifier(t.toIdentifier(name));return t.memberExpression(t.identifier(runtimeNamespace),name)}else{ref=util.template(name)}var uid=this.generateUidIdentifier(name);this.scope.push({key:name,id:uid,init:ref});return uid};File.prototype.errorWithNode=function(node,msg,Error){Error=Error||SyntaxError;var loc=node.loc.start;var err=new Error("Line "+loc.line+": "+msg);err.loc=loc;return err};File.prototype.parse=function(code){code=(code||"")+"";var self=this;this.code=code;code=this.parseShebang(code);return util.parse(this.opts,code,function(tree){self.transform(tree);return self.generate()})};File.prototype.transform=function(ast){this.ast=ast;this.scope=new Scope(ast.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var self=this;_.each(transform.transformers,function(transformer){transformer.transform(self)})};File.prototype.generate=function(){var opts=this.opts;var ast=this.ast;if(!opts.code){return{code:"",map:null,ast:ast}}var result=generate(ast,opts,this.code);if(this.shebang){result.code=this.shebang+"\n"+result.code}if(opts.sourceMap==="inline"){result.code+="\n"+util.sourceMapToComment(result.map)}result.ast=result;return result};File.prototype.generateUid=function(name,scope){name=t.toIdentifier(name);scope=scope||this.scope;var uid;do{uid=this._generateUid(name)}while(scope.has(uid));return uid};File.prototype.generateUidIdentifier=function(name,scope){return t.identifier(this.generateUid(name,scope))};File.prototype._generateUid=function(name){var uids=this.uids;var i=uids[name]||1;var id=name;if(i>1)id+=i;uids[name]=i+1;return"_"+id}},{"./generation/generator":4,"./transformation/transform":29,"./traverse/scope":71,"./types":74,"./util":76,lodash:108}],3:[function(require,module,exports){module.exports=Buffer;var util=require("../util");var _=require("lodash");function Buffer(position,format){this.position=position;this._indent=format.indent.base;this.format=format;this.buf=""}Buffer.prototype.get=function(){return util.trimRight(this.buf)};Buffer.prototype.getIndent=function(){if(this.format.compact){return""}else{return util.repeat(this._indent,this.format.indent.style)}};Buffer.prototype.indentSize=function(){return this.getIndent().length};Buffer.prototype.indent=function(){this._indent++};Buffer.prototype.dedent=function(){this._indent--};Buffer.prototype.semicolon=function(){if(this.format.semicolons)this.push(";")};Buffer.prototype.ensureSemicolon=function(){if(!this.isLast(";"))this.semicolon()};Buffer.prototype.rightBrace=function(){this.newline(true);this.push("}")};Buffer.prototype.keyword=function(name){this.push(name);this.push(" ")};Buffer.prototype.space=function(){if(this.buf&&!this.isLast([" ","\n"])){this.push(" ")}};Buffer.prototype.removeLast=function(cha){if(!this.isLast(cha))return;this.buf=this.buf.slice(0,-1);this.position.unshift(cha)};Buffer.prototype.newline=function(i,removeLast){if(!this.buf)return;if(this.format.compact)return;if(this.endsWith("{\n"))return;if(_.isBoolean(i)){removeLast=i;i=null}if(_.isNumber(i)){if(this.endsWith(util.repeat(i,"\n")))return;var self=this;_.times(i,function(){self.newline(null,removeLast)});return}if(removeLast&&this.isLast("\n"))this.removeLast("\n");this.removeLast(" ");this.buf=this.buf.replace(/\n +$/,"\n");this._push("\n")};Buffer.prototype.push=function(str,noIndent){if(this._indent&&!noIndent&&str!=="\n"){var indent=this.getIndent();str=str.replace(/\n/g,"\n"+indent);if(this.isLast("\n"))str=indent+str}this._push(str)};Buffer.prototype._push=function(str){this.position.push(str);this.buf+=str};Buffer.prototype.endsWith=function(str){return this.buf.slice(-str.length)===str};Buffer.prototype.isLast=function(cha,trimRight){var buf=this.buf;if(trimRight)buf=util.trimRight(buf);var chars=[].concat(cha);return _.contains(chars,_.last(buf))}},{"../util":76,lodash:108}],4:[function(require,module,exports){module.exports=function(ast,opts,code){var gen=new CodeGenerator(ast,opts,code);return gen.generate()};module.exports.CodeGenerator=CodeGenerator;var Whitespace=require("./whitespace");var SourceMap=require("./source-map");var Position=require("./position");var Buffer=require("./buffer");var util=require("../util");var n=require("./node");var t=require("../types");var _=require("lodash");function CodeGenerator(ast,opts,code){opts=opts||{};this.comments=ast.comments||[];this.tokens=ast.tokens||[];this.format=CodeGenerator.normaliseOptions(opts);this.ast=ast;this.whitespace=new Whitespace(this.tokens,this.comments);this.position=new Position;this.map=new SourceMap(this.position,opts,code);this.buffer=new Buffer(this.position,this.format)}_.each(Buffer.prototype,function(fn,key){CodeGenerator.prototype[key]=function(){return fn.apply(this.buffer,arguments)}});CodeGenerator.normaliseOptions=function(opts){return _.merge({parentheses:true,semicolons:true,comments:opts.comments==null||opts.comments,compact:false,indent:{adjustMultilineComment:true,style:" ",base:0}},opts.format||{})};CodeGenerator.generators={templateLiterals:require("./generators/template-literals"),comprehensions:require("./generators/comprehensions"),expressions:require("./generators/expressions"),statements:require("./generators/statements"),playground:require("./generators/playground"),classes:require("./generators/classes"),methods:require("./generators/methods"),modules:require("./generators/modules"),types:require("./generators/types"),base:require("./generators/base"),jsx:require("./generators/jsx")};_.each(CodeGenerator.generators,function(generator){_.extend(CodeGenerator.prototype,generator)});CodeGenerator.prototype.generate=function(){var ast=this.ast;this.print(ast);return{map:this.map.get(),code:this.buffer.get()}};CodeGenerator.prototype.buildPrint=function(parent){var self=this;var print=function(node,opts){return self.print(node,parent,opts)};print.sequence=function(nodes,opts){opts=opts||{};opts.statement=true;return self.printJoin(print,nodes,opts)};print.join=function(nodes,opts){return self.printJoin(print,nodes,opts)};print.block=function(node){return self.printBlock(print,node)};print.indentOnComments=function(node){return self.printAndIndentOnComments(print,node)};return print};CodeGenerator.prototype.print=function(node,parent,opts){if(!node)return"";var self=this;opts=opts||{};var newline=function(leading){if(!opts.statement&&!n.isUserWhitespacable(node,parent)){return}var lines=0;if(node.start!=null){if(leading){lines=self.whitespace.getNewlinesBefore(node)}else{lines=self.whitespace.getNewlinesAfter(node)}}else{if(!leading)lines++;var needs=n.needsWhitespaceAfter;if(leading)needs=n.needsWhitespaceBefore;lines+=needs(node,parent)}self.newline(lines)};if(this[node.type]){this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");var needsParens=parent!==node._parent&&n.needsParens(node,parent);if(needsParens)this.push("(");this[node.type](node,this.buildPrint(node),parent);if(needsParens)this.push(")");this.map.mark(node,"end");if(opts.after)opts.after();newline(false);this.printTrailingComments(node,parent)}else{throw new ReferenceError("unknown node "+node.type)}};CodeGenerator.prototype.printJoin=function(print,nodes,opts){if(!nodes||!nodes.length)return;opts=opts||{};var self=this;var len=nodes.length;if(opts.indent)self.indent();_.each(nodes,function(node,i){print(node,{statement:opts.statement,after:function(){if(opts.iterator){opts.iterator(node,i)}if(opts.separator&&i<len-1){self.push(opts.separator)}}})});if(opts.indent)self.dedent()};CodeGenerator.prototype.printAndIndentOnComments=function(print,node){var indent=!!node.leadingComments;if(indent)this.indent();print(node);if(indent)this.dedent()};CodeGenerator.prototype.printBlock=function(print,node){if(t.isEmptyStatement(node)){this.semicolon()}else{this.push(" ");print(node)}};CodeGenerator.prototype.generateComment=function(comment){var val=comment.value;if(comment.type==="Line"){val="//"+val}else{val="/*"+val+"*/"}return val};CodeGenerator.prototype.printTrailingComments=function(node,parent){this._printComments(this.getComments("trailingComments",node,parent))};CodeGenerator.prototype.printLeadingComments=function(node,parent){this._printComments(this.getComments("leadingComments",node,parent))};CodeGenerator.prototype.getComments=function(key,node,parent){if(t.isExpressionStatement(parent)){return[]}var comments=[];var nodes=[node];var self=this;if(t.isExpressionStatement(node)){nodes.push(node.argument)}_.each(nodes,function(node){comments=comments.concat(self._getComments(key,node))});return comments};CodeGenerator.prototype._getComments=function(key,node){return node&&node[key]||[]};CodeGenerator.prototype._printComments=function(comments){if(this.format.compact)return;if(!this.format.comments)return;if(!comments||!comments.length)return;var self=this;_.each(comments,function(comment){self.newline(self.whitespace.getNewlinesBefore(comment));var column=self.position.column;var val=self.generateComment(comment);if(column&&!self.isLast(["\n"," ","[","{"])){self._push(" ");column++}if(comment.type==="Block"&&self.format.indent.adjustMultilineComment){var offset=comment.loc.start.column;if(offset){var newlineRegex=new RegExp("\\n\\s{1,"+offset+"}","g");val=val.replace(newlineRegex,"\n")}var indent=Math.max(self.indentSize(),column);val=val.replace(/\n/g,"\n"+util.repeat(indent))}if(column===0){val=self.getIndent()+val}self._push(val);self.newline(self.whitespace.getNewlinesAfter(comment))})}},{"../types":74,"../util":76,"./buffer":3,"./generators/base":5,"./generators/classes":6,"./generators/comprehensions":7,"./generators/expressions":8,"./generators/jsx":9,"./generators/methods":10,"./generators/modules":11,"./generators/playground":12,"./generators/statements":13,"./generators/template-literals":14,"./generators/types":15,"./node":16,"./position":19,"./source-map":20,"./whitespace":21,lodash:108}],5:[function(require,module,exports){exports.File=function(node,print){print(node.program)};exports.Program=function(node,print){print.sequence(node.body)};exports.BlockStatement=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();print.sequence(node.body,{indent:true});this.removeLast("\n");this.rightBrace()}}},{}],6:[function(require,module,exports){exports.ClassExpression=exports.ClassDeclaration=function(node,print){this.push("class");if(node.id){this.space();print(node.id)}if(node.superClass){this.push(" extends ");print(node.superClass)}this.space();print(node.body)};exports.ClassBody=function(node,print){if(node.body.length===0){this.push("{}")}else{this.push("{");this.newline();this.indent();print.sequence(node.body);this.dedent();this.rightBrace()}};exports.MethodDefinition=function(node,print){if(node.static){this.push("static ")}this._method(node,print)}},{}],7:[function(require,module,exports){exports.ComprehensionBlock=function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" of ");print(node.right);this.push(")")};exports.ComprehensionExpression=function(node,print){this.push(node.generator?"(":"[");print.join(node.blocks,{separator:" "});this.space();if(node.filter){this.keyword("if");this.push("(");print(node.filter);this.push(")");this.space()}print(node.body);this.push(node.generator?")":"]")}},{}],8:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.UnaryExpression=function(node,print){var hasSpace=/[a-z]$/.test(node.operator);var arg=node.argument;if(t.isUpdateExpression(arg)||t.isUnaryExpression(arg)){hasSpace=true}if(t.isUnaryExpression(arg)&&arg.operator==="!"){hasSpace=false}this.push(node.operator);if(hasSpace)this.space();print(node.argument)};exports.ParenthesizedExpression=function(node,print){this.push("(");print(node.expression);this.push(")")};exports.UpdateExpression=function(node,print){if(node.prefix){this.push(node.operator);print(node.argument)}else{print(node.argument);this.push(node.operator)}};exports.ConditionalExpression=function(node,print){print(node.test);this.push(" ? ");print(node.consequent);this.push(" : ");print(node.alternate)};exports.NewExpression=function(node,print){this.push("new ");print(node.callee);if(node.arguments.length||this.format.parentheses){this.push("(");print.join(node.arguments,{separator:", "});this.push(")")}};exports.SequenceExpression=function(node,print){print.join(node.expressions,{separator:", "})};exports.ThisExpression=function(){this.push("this")};exports.CallExpression=function(node,print){print(node.callee);this.push("(");print.join(node.arguments,{separator:", "});this.push(")")};var buildYieldAwait=function(keyword){return function(node,print){this.push(keyword);if(node.delegate)this.push("*");if(node.argument){this.space();print(node.argument)}}};exports.YieldExpression=buildYieldAwait("yield");exports.AwaitExpression=buildYieldAwait("await");exports.EmptyStatement=function(){this.semicolon()};exports.ExpressionStatement=function(node,print){print(node.expression);this.semicolon()};exports.BinaryExpression=exports.LogicalExpression=exports.AssignmentExpression=function(node,print){print(node.left);this.push(" "+node.operator+" ");print(node.right)};exports.MemberExpression=function(node,print){print(node.object);if(node.computed){this.push("[");print(node.property);this.push("]")}else{if(t.isLiteral(node.object)&&util.isInteger(node.object.value)){this.push(".")}this.push(".");print(node.property)}}},{"../../types":74,"../../util":76}],9:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.XJSAttribute=function(node,print){print(node.name);if(node.value){this.push("=");print(node.value)}};exports.XJSIdentifier=function(node){this.push(node.name)};exports.XJSNamespacedName=function(node,print){print(node.namespace);this.push(":");print(node.name)};exports.XJSMemberExpression=function(node,print){print(node.object);this.push(".");print(node.property)};exports.XJSSpreadAttribute=function(node,print){this.push("{...");print(node.argument);this.push("}")};exports.XJSExpressionContainer=function(node,print){this.push("{");print(node.expression);this.push("}")};exports.XJSElement=function(node,print){var self=this;var open=node.openingElement;print(open);if(open.selfClosing)return;this.indent();_.each(node.children,function(child){if(t.isLiteral(child)){self.push(child.value)}else{print(child)}});this.dedent();print(node.closingElement)};exports.XJSOpeningElement=function(node,print){this.push("<");print(node.name);if(node.attributes.length>0){this.space();print.join(node.attributes,{separator:" "})}this.push(node.selfClosing?" />":">")};exports.XJSClosingElement=function(node,print){this.push("</");print(node.name);this.push(">")};exports.XJSEmptyExpression=function(){}},{"../../types":74,lodash:108}],10:[function(require,module,exports){var t=require("../../types");exports._params=function(node,print){var self=this;this.push("(");print.join(node.params,{separator:", ",iterator:function(param,i){var def=node.defaults&&node.defaults[i];if(def){self.push(" = ");print(def)}}});if(node.rest){if(node.params.length){this.push(", ")}this.push("...");print(node.rest)}this.push(")")};exports._method=function(node,print){var value=node.value;var kind=node.kind;var key=node.key;if(!kind||kind==="init"){if(value.generator){this.push("*")}}else{this.push(kind+" ")}if(value.async)this.push("async ");if(node.computed){this.push("[");print(key);this.push("]")}else{print(key)}this._params(value,print);this.space();print(value.body)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,print){if(node.async)this.push("async ");this.push("function");if(node.generator)this.push("*");this.space();if(node.id)print(node.id);this._params(node,print);this.space();print(node.body)};exports.ArrowFunctionExpression=function(node,print){if(node.async)this.push("async ");if(node.params.length===1&&!node.defaults.length&&!node.rest&&t.isIdentifier(node.params[0])){print(node.params[0])}else{this._params(node,print)}this.push(" => ");print(node.body)}},{"../../types":74}],11:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ImportSpecifier=exports.ExportSpecifier=function(node,print){print(node.id);if(node.name){this.push(" as ");print(node.name)}};exports.ExportBatchSpecifier=function(){this.push("*")};exports.ExportDeclaration=function(node,print){this.push("export ");var specifiers=node.specifiers;if(node.default){this.push("default ")}if(node.declaration){print(node.declaration);if(t.isStatement(node.declaration))return}else{if(specifiers.length===1&&t.isExportBatchSpecifier(specifiers[0])){print(specifiers[0])}else{this.push("{");if(specifiers.length){this.space();print.join(specifiers,{separator:", "});this.space()}this.push("}")}if(node.source){this.push(" from ");print(node.source)}}this.ensureSemicolon()};exports.ImportDeclaration=function(node,print){var self=this;this.push("import ");var specfiers=node.specifiers;if(specfiers&&specfiers.length){var foundImportSpecifier=false;_.each(node.specifiers,function(spec,i){if(+i>0){self.push(", ")}if(!spec.default&&spec.type!=="ImportBatchSpecifier"&&!foundImportSpecifier){foundImportSpecifier=true;self.push("{ ")}print(spec)});if(foundImportSpecifier){this.push(" }")}this.push(" from ")}print(node.source);this.semicolon()};exports.ImportBatchSpecifier=function(node,print){this.push("* as ");print(node.name)}},{"../../types":74,lodash:108}],12:[function(require,module,exports){var _=require("lodash");_.each(["BindMemberExpression","BindFunctionExpression"],function(type){exports[type]=function(){throw new ReferenceError("Trying to render non-standard playground node "+JSON.stringify(type))}})},{lodash:108}],13:[function(require,module,exports){var t=require("../../types");exports.WithStatement=function(node,print){this.keyword("with");this.push("(");print(node.object);this.push(")");print.block(node.body)};exports.IfStatement=function(node,print){this.keyword("if");this.push("(");print(node.test);this.push(") ");print.indentOnComments(node.consequent);if(node.alternate){if(this.isLast("}"))this.space();this.keyword("else");print.indentOnComments(node.alternate)}};exports.ForStatement=function(node,print){this.keyword("for");this.push("(");print(node.init);this.push(";");if(node.test){this.space();print(node.test)}this.push(";");if(node.update){this.space();print(node.update)}this.push(")");print.block(node.body)};exports.WhileStatement=function(node,print){this.keyword("while");this.push("(");print(node.test);this.push(")");print.block(node.body)};var buildForXStatement=function(op){return function(node,print){this.keyword("for");this.push("(");print(node.left);this.push(" "+op+" ");print(node.right);this.push(")");print.block(node.body)}};exports.ForInStatement=buildForXStatement("in");exports.ForOfStatement=buildForXStatement("of");exports.DoWhileStatement=function(node,print){this.keyword("do");print(node.body);this.space();this.keyword("while");this.push("(");print(node.test);this.push(");")};var buildLabelStatement=function(prefix,key){return function(node,print){this.push(prefix);var label=node[key||"label"];if(label){this.space();print(label)}this.semicolon()}};exports.ContinueStatement=buildLabelStatement("continue");exports.ReturnStatement=buildLabelStatement("return","argument");exports.BreakStatement=buildLabelStatement("break");exports.LabeledStatement=function(node,print){print(node.label);this.push(": ");print(node.body)};exports.TryStatement=function(node,print){this.keyword("try");print(node.block);this.space();print(node.handler);if(node.finalizer){this.space();this.push("finally ");print(node.finalizer)}};exports.CatchClause=function(node,print){this.keyword("catch");this.push("(");print(node.param);this.push(") ");print(node.body)};exports.ThrowStatement=function(node,print){this.push("throw ");print(node.argument);this.semicolon()};exports.SwitchStatement=function(node,print){this.keyword("switch");this.push("(");print(node.discriminant);this.push(") {");print.sequence(node.cases,{indent:true});this.push("}")};exports.SwitchCase=function(node,print){if(node.test){this.push("case ");print(node.test);this.push(":")}else{this.push("default:")}this.space();print.sequence(node.consequent,{indent:true})};exports.DebuggerStatement=function(){this.push("debugger;")};exports.VariableDeclaration=function(node,print,parent){this.push(node.kind+" ");print.join(node.declarations,{separator:", "});if(!t.isFor(parent)){this.semicolon()}};exports.VariableDeclarator=function(node,print){if(node.init){print(node.id);this.push(" = ");print(node.init)}else{print(node.id)}}},{"../../types":74}],14:[function(require,module,exports){var _=require("lodash");exports.TaggedTemplateExpression=function(node,print){print(node.tag);print(node.quasi)};exports.TemplateElement=function(node){this._push(node.value.raw)};exports.TemplateLiteral=function(node,print){this.push("`");var quasis=node.quasis;var self=this;var len=quasis.length;_.each(quasis,function(quasi,i){print(quasi);if(i+1<len){self.push("${ ");print(node.expressions[i]);self.push(" }")}});this._push("`")}},{lodash:108}],15:[function(require,module,exports){var _=require("lodash");exports.Identifier=function(node){this.push(node.name)};exports.SpreadElement=exports.SpreadProperty=function(node,print){this.push("...");print(node.argument)};exports.VirtualPropertyExpression=function(node,print){print(node.object);this.push("::");print(node.property)};exports.ObjectExpression=exports.ObjectPattern=function(node,print){var props=node.properties;if(props.length){this.push("{");this.space();print.join(props,{separator:", ",indent:true});this.space();this.push("}")}else{this.push("{}")}};exports.Property=function(node,print){if(node.method||node.kind==="get"||node.kind==="set"){this._method(node,print)}else{if(node.computed){this.push("[");print(node.key);this.push("]")}else{print(node.key);if(node.shorthand)return}this.push(": ");print(node.value)}};exports.ArrayExpression=exports.ArrayPattern=function(node,print){var elems=node.elements;var self=this;var len=elems.length;this.push("[");_.each(elems,function(elem,i){if(!elem){self.push(",")}else{if(i>0)self.push(" ");print(elem);if(i<len-1)self.push(",")}});this.push("]")};exports.Literal=function(node){var val=node.value;var type=typeof val;if(type==="string"){val=JSON.stringify(val);val=val.replace(/[\u007f-\uffff]/g,function(c){return"\\u"+("0000"+c.charCodeAt(0).toString(16)).slice(-4)});this.push(val)}else if(type==="boolean"||type==="number"){this.push(JSON.stringify(val))}else if(node.regex){this.push("/"+node.regex.pattern+"/"+node.regex.flags)}else if(val===null){this.push("null")}}},{lodash:108}],16:[function(require,module,exports){module.exports=Node;var whitespace=require("./whitespace");var parens=require("./parentheses");var t=require("../../types");var _=require("lodash");var find=function(obj,node,parent){var result;_.each(obj,function(fn,type){if(t["is"+type](node)){result=fn(node,parent);if(result!=null)return false}});return result};function Node(node,parent){this.parent=parent;this.node=node}Node.prototype.isUserWhitespacable=function(){return t.isUserWhitespacable(this.node)};Node.prototype.needsWhitespace=function(type){var parent=this.parent;var node=this.node;if(!node)return 0;if(t.isExpressionStatement(node)){node=node.expression}var lines=find(whitespace[type].nodes,node,parent);if(lines)return lines;_.each(find(whitespace[type].list,node,parent),function(expr){lines=Node.needsWhitespace(expr,node,type);if(lines)return false});return lines||0};Node.prototype.needsWhitespaceBefore=function(){return this.needsWhitespace("before")};Node.prototype.needsWhitespaceAfter=function(){return this.needsWhitespace("after")};Node.prototype.needsParens=function(){var parent=this.parent;var node=this.node;if(!parent)return false;if(t.isNewExpression(parent)&&parent.callee===node){return t.isCallExpression(node)||_.some(node,function(val){return t.isCallExpression(val)})}return find(parens,node,parent)};_.each(Node.prototype,function(fn,key){Node[key]=function(node,parent){var n=new Node(node,parent);var args=_.toArray(arguments).slice(2);return n[key].apply(n,args)}})},{"../../types":74,"./parentheses":17,"./whitespace":18,lodash:108}],17:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var PRECEDENCE={};_.each([["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]],function(tier,i){_.each(tier,function(op){PRECEDENCE[op]=i})});exports.Binary=function(node,parent){if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isUnaryLike(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isBinary(parent)){var parentOp=parent.operator;var parentPos=PRECEDENCE[parentOp];var nodeOp=node.operator;var nodePos=PRECEDENCE[nodeOp];if(parentPos>nodePos){return true}if(parentPos===nodePos&&parent.right===node){return true}}};exports.BinaryExpression=function(node,parent){if(node.operator==="in"){if(t.isVariableDeclarator(parent)){return true}if(t.isFor(parent)){return true}}};exports.SequenceExpression=function(node,parent){if(t.isForStatement(parent)){return false}if(t.isExpressionStatement(parent)&&parent.expression===node){return false}return true};exports.YieldExpression=function(node,parent){return t.isBinary(parent)||t.isUnaryLike(parent)||t.isCallExpression(parent)||t.isMemberExpression(parent)||t.isNewExpression(parent)||t.isConditionalExpression(parent)||t.isYieldExpression(parent)};exports.Literal=function(node,parent){if(_.isNumber(node.value)&&t.isMemberExpression(parent)&&parent.object===node){return true}};exports.ClassExpression=function(node,parent){return t.isExpressionStatement(parent)};exports.UnaryLike=function(node,parent){return t.isMemberExpression(parent)&&parent.object===node};exports.FunctionExpression=function(node,parent){if(t.isExpressionStatement(parent)){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}};exports.AssignmentExpression=exports.ConditionalExpression=function(node,parent){if(t.isUnaryLike(parent)){return true}if(t.isBinary(parent)){return true}if(t.isCallExpression(parent)&&parent.callee===node){return true}if(t.isConditionalExpression(parent)&&parent.test===node){return true}if(t.isMemberExpression(parent)&&parent.object===node){return true}return false}},{"../../types":74,lodash:108}],18:[function(require,module,exports){var _=require("lodash");var t=require("../../types");exports.before={nodes:{Property:function(node,parent){if(parent.properties[0]===node){return 1}},SpreadProperty:function(node,parent){return exports.before.nodes.Property(node,parent)},SwitchCase:function(node,parent){if(parent.cases[0]===node){return 1 }},CallExpression:function(node){if(t.isFunction(node.callee)){return 1}}}};exports.after={nodes:{},list:{VariableDeclaration:function(node){return _.map(node.declarations,"init")},ArrayExpression:function(node){return node.elements},ObjectExpression:function(node){return node.properties}}};_.each({Function:1,Class:1,For:1,SwitchStatement:1,IfStatement:{before:1},CallExpression:{after:1},Literal:{after:1}},function(amounts,type){if(_.isNumber(amounts))amounts={after:amounts,before:amounts};_.each(amounts,function(amount,key){exports[key].nodes[type]=function(){return amount}})})},{"../../types":74,lodash:108}],19:[function(require,module,exports){module.exports=Position;var _=require("lodash");function Position(){this.line=1;this.column=0}Position.prototype.push=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line++;self.column=0}else{self.column++}})};Position.prototype.unshift=function(str){var self=this;_.each(str,function(cha){if(cha==="\n"){self.line--}else{self.column--}})}},{lodash:108}],20:[function(require,module,exports){module.exports=SourceMap;var sourceMap=require("source-map");var t=require("../types");function SourceMap(position,opts,code){this.position=position;this.opts=opts;if(opts.sourceMap){this.map=new sourceMap.SourceMapGenerator({file:opts.sourceMapName,sourceRoot:opts.sourceRoot});this.map.setSourceContent(opts.sourceFileName,code)}else{this.map=null}}SourceMap.prototype.get=function(){var map=this.map;if(map){return map.toJSON()}else{return map}};SourceMap.prototype.mark=function(node,type){var loc=node.loc;if(!loc)return;var map=this.map;if(!map)return;if(t.isProgram(node)||t.isFile(node))return;var position=this.position;var generated={line:position.line,column:position.column};var original=loc[type];if(generated.line===original.line&&generated.column===original.column)return;map.addMapping({source:this.opts.sourceFileName,generated:generated,original:original})}},{"../types":74,"source-map":116}],21:[function(require,module,exports){module.exports=Whitespace;var _=require("lodash");function Whitespace(tokens,comments){this.tokens=_.sortBy(tokens.concat(comments),"start");this.used=[]}Whitespace.prototype.getNewlinesBefore=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.start===token.start){startToken=tokens[i-1];endToken=token;return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesAfter=function(node){var startToken;var endToken;var tokens=this.tokens;_.each(tokens,function(token,i){if(node.end===token.end){startToken=token;endToken=tokens[i+1];return false}});return this.getNewlinesBetween(startToken,endToken)};Whitespace.prototype.getNewlinesBetween=function(startToken,endToken){var start=startToken?startToken.loc.end.line:1;var end=endToken.loc.start.line;var lines=0;for(var line=start;line<end;line++){if(!_.contains(this.used,line)){this.used.push(line);lines++}}return lines}},{lodash:108}],22:[function(require,module,exports){var t=require("./types");var _=require("lodash");var types=require("ast-types");var def=types.Type.def;var or=types.Type.or;def("File").bases("Node").build("program").field("program",def("Program"));def("ParenthesizedExpression").bases("Expression").build("expression").field("expression",def("Expression"));def("ImportBatchSpecifier").bases("Specifier").build("name").field("name",def("Identifier"));def("VirtualPropertyExpression").bases("Expression").build("object","property").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression")));def("BindMemberExpression").bases("Expression").build("object","property","arguments").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("arguments",[def("Expression")]);def("BindFunctionExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);types.finalize();var estraverse=require("estraverse");_.extend(estraverse.VisitorKeys,t.VISITOR_KEYS)},{"./types":74,"ast-types":91,estraverse:103,lodash:108}],23:[function(require,module,exports){module.exports=AMDFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function AMDFormatter(file){this.file=file;this.ids={}}util.inherits(AMDFormatter,CommonJSFormatter);AMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[t.literal("exports")];_.each(this.ids,function(id,name){names.push(t.literal(name))});names=t.arrayExpression(names);var params=_.values(this.ids);params.unshift(t.identifier("exports"));var container=t.functionExpression(null,params,t.blockStatement(body));var defineArgs=[names,container];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var call=t.callExpression(t.identifier("define"),defineArgs);program.body=[t.expressionStatement(call)]};AMDFormatter.prototype.getModuleName=function(){if(this.file.opts.amdModuleIds){return CommonJSFormatter.prototype.getModuleName.apply(this,arguments)}else{return null}};AMDFormatter.prototype._push=function(node){var id=node.source.value;var ids=this.ids;if(ids[id]){return ids[id]}else{return this.ids[id]=this.file.generateUidIdentifier(id)}};AMDFormatter.prototype.import=function(node){this._push(node)};AMDFormatter.prototype.importSpecifier=function(specifier,node,nodes){var key=t.getSpecifierName(specifier);var id=specifier.id;if(specifier.default){id=t.identifier("default")}var ref;if(t.isImportBatchSpecifier(specifier)){ref=this._push(node)}else{ref=t.memberExpression(this._push(node),id,false)}nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,ref)]))};AMDFormatter.prototype.exportSpecifier=function(specifier,node,nodes){var self=this;return this._exportSpecifier(function(){return self._push(node)},specifier,node,nodes)}},{"../../types":74,"../../util":76,"./common":25,lodash:108}],24:[function(require,module,exports){module.exports=CommonJSInteropFormatter;var CommonJSFormatter=require("./common");var util=require("../../util");var t=require("../../types");var _=require("lodash");function CommonJSInteropFormatter(file){CommonJSFormatter.apply(this,arguments);var has=false;_.each(file.ast.program.body,function(node){if(t.isExportDeclaration(node)&&!node.default)has=true});this.has=has}util.inherits(CommonJSInteropFormatter,CommonJSFormatter);CommonJSInteropFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){nodes.push(t.variableDeclaration("var",[t.variableDeclarator(variableName,t.callExpression(this.file.addDeclaration("interop-require"),[util.template("require",{MODULE_NAME:node.source.raw})]))]))}else{CommonJSFormatter.prototype.importSpecifier.apply(this,arguments)}};CommonJSInteropFormatter.prototype.export=function(node,nodes){if(node.default&&!this.has){var declar=node.declaration;var assign=util.template("exports-default-module",{VALUE:this._pushStatement(declar,nodes)},true);nodes.push(this._hoistExport(declar,assign));return}CommonJSFormatter.prototype.export.apply(this,arguments)};CommonJSInteropFormatter.prototype.exportSpecifier=function(){CommonJSFormatter.prototype.exportSpecifier.apply(this,arguments)}},{"../../types":74,"../../util":76,"./common":25,lodash:108}],25:[function(require,module,exports){module.exports=CommonJSFormatter;var util=require("../../util");var t=require("../../types");function CommonJSFormatter(file){this.file=file}CommonJSFormatter.prototype.getModuleName=function(){var opts=this.file.opts;var filenameRelative=opts.filenameRelative;var moduleName="";if(opts.moduleRoot){moduleName=opts.moduleRoot+"/"}if(!opts.filenameRelative){return moduleName+opts.filename.replace(/^\//,"")}if(opts.sourceRoot){var sourceRootRegEx=new RegExp("^"+opts.sourceRoot+"/?");filenameRelative=filenameRelative.replace(sourceRootRegEx,"")}filenameRelative=filenameRelative.replace(/\.(.*?)$/,"");moduleName+=filenameRelative;return moduleName};CommonJSFormatter.prototype.import=function(node,nodes){nodes.push(util.template("require",{MODULE_NAME:node.source.raw},true))};CommonJSFormatter.prototype.importSpecifier=function(specifier,node,nodes){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=t.identifier("default")}var templateName="require-assign";if(specifier.type!=="ImportBatchSpecifier")templateName+="-key";nodes.push(util.template(templateName,{VARIABLE_NAME:variableName,MODULE_NAME:node.source.raw,KEY:specifier.id}))};CommonJSFormatter.prototype._hoistExport=function(declar,assign){if(t.isFunctionDeclaration(declar)){assign._blockHoist=true}return assign};CommonJSFormatter.prototype._pushStatement=function(ref,nodes){if(t.isClass(ref)||t.isFunction(ref)){if(ref.id){nodes.push(t.toStatement(ref));ref=ref.id}}return ref};CommonJSFormatter.prototype.export=function(node,nodes){var declar=node.declaration;if(node.default){nodes.push(util.template("exports-default",{VALUE:this._pushStatement(declar,nodes)},true))}else{var assign;if(t.isVariableDeclaration(declar)){var decl=declar.declarations[0];if(decl.init){decl.init=util.template("exports-assign",{VALUE:decl.init,KEY:decl.id})}nodes.push(declar)}else{assign=util.template("exports-assign",{VALUE:declar.id,KEY:declar.id},true);nodes.push(t.toStatement(declar));nodes.push(assign);this._hoistExport(declar,assign)}}};CommonJSFormatter.prototype._exportSpecifier=function(getRef,specifier,node,nodes){var variableName=t.getSpecifierName(specifier);var inherits=false;if(node.specifiers.length===1)inherits=node;if(node.source){if(t.isExportBatchSpecifier(specifier)){nodes.push(util.template("exports-wildcard",{OBJECT:getRef()},true))}else{nodes.push(util.template("exports-assign-key",{VARIABLE_NAME:variableName.name,OBJECT:getRef(),KEY:specifier.id},true))}}else{nodes.push(util.template("exports-assign",{VALUE:specifier.id,KEY:variableName},true))}};CommonJSFormatter.prototype.exportSpecifier=function(specifier,node,nodes){this._exportSpecifier(function(){return t.callExpression(t.identifier("require"),[node.source])},specifier,node,nodes)}},{"../../types":74,"../../util":76}],26:[function(require,module,exports){module.exports=IgnoreFormatter;var t=require("../../types");function IgnoreFormatter(){}IgnoreFormatter.prototype.import=function(){};IgnoreFormatter.prototype.importSpecifier=function(){};IgnoreFormatter.prototype.export=function(node,nodes){var declar=t.toStatement(node.declaration,true);if(declar)nodes.push(t.inherits(declar,node))};IgnoreFormatter.prototype.exportSpecifier=function(){}},{"../../types":74}],27:[function(require,module,exports){module.exports=SystemFormatter;var util=require("../../util");var t=require("../../types");var _=require("lodash");var SETTER_MODULE_NAMESPACE=t.identifier("m");var DEFAULT_IDENTIFIER=t.identifier("default");var NULL_SETTER=t.literal(null);function SystemFormatter(file){this.exportedStatements=[];this.importedModule={};this.exportIdentifier=file.generateUidIdentifier("export");this.file=file}SystemFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var moduleName=this.file.opts.filename.replace(/^.*\//,"").replace(/\..*$/,"");var dependencies=Object.keys(this.importedModule).map(t.literal);var moduleNameVariableNode=t.variableDeclaration("var",[t.variableDeclarator(t.identifier("__moduleName"),t.literal(moduleName))]);body.splice(1,0,moduleNameVariableNode);var declaredSetters=_(this.importedModule).map().flatten().pluck("variableName").pluck("name").uniq().map(t.identifier).map(function(name){return t.variableDeclarator(name)}).value();if(declaredSetters.length){body.splice(2,0,t.variableDeclaration("var",declaredSetters))}var executeFunctionExpression=t.functionExpression(null,[],t.blockStatement(this.exportedStatements));var settersArrayExpression=t.arrayExpression(this._buildSetters());var moduleReturnStatement=t.returnStatement(t.objectExpression([t.property("init",t.identifier("setters"),settersArrayExpression),t.property("init",t.identifier("execute"),executeFunctionExpression)]));body.push(moduleReturnStatement);var runner=util.template("register",{MODULE_NAME:t.literal(moduleName),MODULE_DEPENDENCIES:t.arrayExpression(dependencies),MODULE_BODY:t.functionExpression(null,[this.exportIdentifier],t.blockStatement(body))});program.body=[t.expressionStatement(runner)]};SystemFormatter.prototype._buildSetters=function(){return _.map(this.importedModule,function(specs){if(!specs.length){return NULL_SETTER}var expressionStatements=_.map(specs,function(spec){var right=SETTER_MODULE_NAMESPACE;if(!spec.isBatch){right=t.memberExpression(right,spec.key)}return t.expressionStatement(t.assignmentExpression("=",spec.variableName,right))});return t.functionExpression(null,[SETTER_MODULE_NAMESPACE],t.blockStatement(expressionStatements))})};SystemFormatter.prototype.import=function(node){var MODULE_NAME=node.source.value;this.importedModule[MODULE_NAME]=this.importedModule[MODULE_NAME]||[]};SystemFormatter.prototype.importSpecifier=function(specifier,node){var variableName=t.getSpecifierName(specifier);if(specifier.default){specifier.id=DEFAULT_IDENTIFIER}var MODULE_NAME=node.source.value;this.importedModule[MODULE_NAME]=this.importedModule[MODULE_NAME]||[];this.importedModule[MODULE_NAME].push({variableName:variableName,isBatch:specifier.type==="ImportBatchSpecifier",key:specifier.id})};SystemFormatter.prototype._export=function(name,identifier){this.exportedStatements.push(t.expressionStatement(t.callExpression(this.exportIdentifier,[t.literal(name),identifier])))};SystemFormatter.prototype.export=function(node,nodes){var declar=node.declaration;var variableName,identifier;if(node.default){variableName=DEFAULT_IDENTIFIER.name;if(t.isClass(declar)||t.isFunction(declar)){if(!declar.id){declar.id=this.file.generateUidIdentifier("anonymous")}nodes.push(t.toStatement(declar));declar=declar.id}identifier=declar}else if(t.isVariableDeclaration(declar)){variableName=declar.declarations[0].id.name;identifier=declar.declarations[0].id;nodes.push(declar)}else{variableName=declar.id.name;identifier=declar.id;nodes.push(declar)}this._export(variableName,identifier)};SystemFormatter.prototype.exportSpecifier=function(specifier,node){var variableName=t.getSpecifierName(specifier);if(node.source){if(t.isExportBatchSpecifier(specifier)){var exportIdentifier=t.identifier("exports");this.exportedStatements.push(t.variableDeclaration("var",[t.variableDeclarator(exportIdentifier,this.exportIdentifier)]));this.exportedStatements.push(util.template("exports-wildcard",{OBJECT:t.identifier(node.source.value)},true))}else{this._export(variableName.name,t.memberExpression(t.identifier(node.source.value),specifier.id))}}else{this._export(variableName.name,specifier.id)}}},{"../../types":74,"../../util":76,lodash:108}],28:[function(require,module,exports){module.exports=UMDFormatter;var AMDFormatter=require("./amd");var util=require("../../util");var t=require("../../types");var _=require("lodash");function UMDFormatter(){AMDFormatter.apply(this,arguments)}util.inherits(UMDFormatter,AMDFormatter);UMDFormatter.prototype.transform=function(ast){var program=ast.program;var body=program.body;var names=[];_.each(this.ids,function(id,name){names.push(t.literal(name))});var ids=_.values(this.ids);var args=[t.identifier("exports")].concat(ids);var factory=t.functionExpression(null,args,t.blockStatement(body));var defineArgs=[t.arrayExpression([t.literal("exports")].concat(names))];var moduleName=this.getModuleName();if(moduleName)defineArgs.unshift(t.literal(moduleName));var runner=util.template("umd-runner-body",{AMD_ARGUMENTS:defineArgs,COMMON_ARGUMENTS:names.map(function(name){return t.callExpression(t.identifier("require"),[name])})});var call=t.callExpression(runner,[factory]);program.body=[t.expressionStatement(call)]}},{"../../types":74,"../../util":76,"./amd":23,lodash:108}],29:[function(require,module,exports){module.exports=transform;var Transformer=require("./transformer");var File=require("../file");var _=require("lodash");function transform(code,opts){var file=new File(opts);return file.parse(code)}transform._ensureTransformerNames=function(type,keys){_.each(keys,function(key){if(!_.has(transform.transformers,key)){throw new ReferenceError("unknown transformer "+key+" specified in "+type)}})};transform.transformers={};transform.moduleFormatters={common:require("./modules/common"),commonInterop:require("./modules/common-interop"),system:require("./modules/system"),ignore:require("./modules/ignore"),amd:require("./modules/amd"),umd:require("./modules/umd")};_.each({modules:require("./transformers/es6-modules"),propertyNameShorthand:require("./transformers/es6-property-name-shorthand"),arrayComprehension:require("./transformers/es7-array-comprehension"),generatorComprehension:require("./transformers/es7-generator-comprehension"),arrowFunctions:require("./transformers/es6-arrow-functions"),classes:require("./transformers/es6-classes"),computedPropertyNames:require("./transformers/es6-computed-property-names"),objectSpread:require("./transformers/es7-object-spread"),exponentiationOperator:require("./transformers/es7-exponentiation-operator"),spread:require("./transformers/es6-spread"),templateLiterals:require("./transformers/es6-template-literals"),propertyMethodAssignment:require("./transformers/es5-property-method-assignment"),defaultParameters:require("./transformers/es6-default-parameters"),restParameters:require("./transformers/es6-rest-parameters"),destructuring:require("./transformers/es6-destructuring"),forOf:require("./transformers/es6-for-of"),unicodeRegex:require("./transformers/es6-unicode-regex"),abstractReferences:require("./transformers/es7-abstract-references"),react:require("./transformers/react"),constants:require("./transformers/es6-constants"),letScoping:require("./transformers/es6-let-scoping"),generators:require("./transformers/es6-generators"),methodBinding:require("./transformers/playground-method-binding"),memoizationOperator:require("./transformers/playground-memoization-operator"),_blockHoist:require("./transformers/_block-hoist"),_declarations:require("./transformers/_declarations"),_aliasFunctions:require("./transformers/_alias-functions"),useStrict:require("./transformers/use-strict"),_propertyLiterals:require("./transformers/_property-literals"),_memberExpressioLiterals:require("./transformers/_member-expression-literals"),_moduleFormatter:require("./transformers/_module-formatter")},function(transformer,key){transform.transformers[key]=new Transformer(key,transformer)})},{"../file":2,"./modules/amd":23,"./modules/common":25,"./modules/common-interop":24,"./modules/ignore":26,"./modules/system":27,"./modules/umd":28,"./transformer":30,"./transformers/_alias-functions":31,"./transformers/_block-hoist":32,"./transformers/_declarations":33,"./transformers/_member-expression-literals":34,"./transformers/_module-formatter":35,"./transformers/_property-literals":36,"./transformers/es5-property-method-assignment":37,"./transformers/es6-arrow-functions":38,"./transformers/es6-classes":39,"./transformers/es6-computed-property-names":40,"./transformers/es6-constants":41,"./transformers/es6-default-parameters":42,"./transformers/es6-destructuring":43,"./transformers/es6-for-of":44,"./transformers/es6-generators":49,"./transformers/es6-let-scoping":54,"./transformers/es6-modules":55,"./transformers/es6-property-name-shorthand":56,"./transformers/es6-rest-parameters":57,"./transformers/es6-spread":58,"./transformers/es6-template-literals":59,"./transformers/es6-unicode-regex":60,"./transformers/es7-abstract-references":61,"./transformers/es7-array-comprehension":62,"./transformers/es7-exponentiation-operator":63,"./transformers/es7-generator-comprehension":64,"./transformers/es7-object-spread":65,"./transformers/playground-memoization-operator":66,"./transformers/playground-method-binding":67,"./transformers/react":68,"./transformers/use-strict":69,lodash:108}],30:[function(require,module,exports){module.exports=Transformer;var traverse=require("../traverse");var t=require("../types");var _=require("lodash");function Transformer(key,transformer){this.transformer=Transformer.normalise(transformer);this.key=key}Transformer.normalise=function(transformer){if(_.isFunction(transformer)){transformer={ast:transformer}}_.each(transformer,function(fns,type){if(type[0]==="_")return;if(_.isFunction(fns))fns={enter:fns};transformer[type]=fns});return transformer};Transformer.prototype.transform=function(file){if(!this.canRun(file))return;var transformer=this.transformer;var ast=file.ast;var astRun=function(key){if(transformer.ast&&transformer.ast[key]){transformer.ast[key](ast,file)}};astRun("enter");var build=function(exit){return function(node,parent,scope){var types=[node.type].concat(t.ALIAS_KEYS[node.type]||[]);var fns=transformer.all;_.each(types,function(type){fns=transformer[type]||fns});if(!fns)return;var fn=fns.enter;if(exit)fn=fns.exit;if(!fn)return;return fn(node,parent,file,scope)}};traverse(ast,{enter:build(),exit:build(true)});astRun("exit")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;if(key[0]!=="_"){var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false}return true}},{"../traverse":70,"../types":74,lodash:108}],31:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var go=function(getBody,node,file,scope){var argumentsId;var thisId;var getArgumentsId=function(){return argumentsId=argumentsId||file.generateUidIdentifier("arguments",scope)};var getThisId=function(){return thisId=thisId||file.generateUidIdentifier("this",scope)};traverse(node,function(node){if(!node._aliasFunction){if(t.isFunction(node)){return false}else{return}}traverse(node,function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return false}if(node._ignoreAliasFunctions)return false;var getId;if(t.isIdentifier(node)&&node.name==="arguments"){getId=getArgumentsId}else if(t.isThisExpression(node)){getId=getThisId}else{return}if(t.isReferenced(node,parent))return getId()});return false});var body;var pushDeclaration=function(id,init){body=body||getBody();body.unshift(t.variableDeclaration("var",[t.variableDeclarator(id,init)]))};if(argumentsId){pushDeclaration(argumentsId,t.identifier("arguments"))}if(thisId){pushDeclaration(thisId,t.identifier("this"))}};exports.Program=function(node,parent,file,scope){go(function(){return node.body},node,file,scope)};exports.FunctionDeclaration=exports.FunctionExpression=function(node,parent,file,scope){go(function(){t.ensureBlock(node);return node.body.body},node,file,scope)}},{"../../traverse":70,"../../types":74}],32:[function(require,module,exports){exports.BlockStatement=exports.Program={exit:function(node){var unshift=[];node.body=node.body.filter(function(bodyNode){if(bodyNode._blockHoist){unshift.push(bodyNode);return false}else{return true}});node.body=unshift.concat(node.body)}}},{}],33:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.BlockStatement=exports.Program=function(node){var kinds={};_.each(node._declarations,function(declar){var kind=declar.kind||"var";var declarNode=t.variableDeclarator(declar.id,declar.init);if(!declar.init){kinds[kind]=kinds[kind]||[];kinds[kind].push(declarNode)}else{node.body.unshift(t.variableDeclaration(kind,[declarNode]))}});_.each(kinds,function(declars,kind){node.body.unshift(t.variableDeclaration(kind,declars))})}},{"../../types":74,lodash:108}],34:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.MemberExpression=function(node){var prop=node.property;if(node.computed&&t.isLiteral(prop)&&t.isValidIdentifier(prop.value)){node.property=t.identifier(prop.value);node.computed=false}else if(!node.computed&&t.isIdentifier(prop)&&esutils.keyword.isKeywordES6(prop.name,true)){node.property=t.literal(prop.name);node.computed=true}}},{"../../types":74,esutils:107}],35:[function(require,module,exports){var transform=require("../transform");exports.ast={exit:function(ast,file){if(!transform.transformers.modules.canRun(file))return;if(file.moduleFormatter.transform){file.moduleFormatter.transform(ast)}}}},{"../transform":29}],36:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");exports.Property=function(node){var key=node.key;if(t.isLiteral(key)&&t.isValidIdentifier(key.value)){node.key=t.identifier(key.value);node.computed=false}else if(!node.computed&&t.isIdentifier(key)&&esutils.keyword.isKeywordES6(key.name,true)){node.key=t.literal(key.name)}}},{"../../types":74,esutils:107}],37:[function(require,module,exports){var util=require("../../util");var _=require("lodash");exports.Property=function(node){if(node.method)node.method=false};exports.ObjectExpression=function(node,parent,file){var mutatorMap={};node.properties=node.properties.filter(function(prop){if(prop.kind==="get"||prop.kind==="set"){util.pushMutatorMap(mutatorMap,prop.key,prop.kind,prop.value);return false}else{return true}});if(_.isEmpty(mutatorMap))return;var objId=util.getUid(parent,file);return util.template("object-define-properties-closure",{KEY:objId,OBJECT:node,CONTENT:util.template("object-define-properties",{OBJECT:objId,PROPS:util.buildDefineProperties(mutatorMap)})})}},{"../../util":76,lodash:108}],38:[function(require,module,exports){var t=require("../../types");exports.ArrowFunctionExpression=function(node){t.ensureBlock(node);node._aliasFunction=true;node.expression=false;node.type="FunctionExpression";return node}},{"../../types":74}],39:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ClassDeclaration=function(node,parent,file,scope){var built=new Class(node,file,scope).run();var declar=t.variableDeclaration("let",[t.variableDeclarator(node.id,built)]);t.inheritsComments(declar,node);return declar};exports.ClassExpression=function(node,parent,file,scope){return new Class(node,file,scope).run()};var getMemberExpressionObject=function(node){while(t.isMemberExpression(node)){node=node.object}return node};function Class(node,file,scope){this.scope=scope;this.node=node;this.file=file;this.instanceMutatorMap={};this.staticMutatorMap={};this.hasConstructor=false;this.className=node.id||file.generateUidIdentifier("class",scope);this.superName=node.superClass}Class.prototype.run=function(){var superClassArgument=this.superName;var superClassCallee=this.superName;var superName=this.superName;var className=this.className;var file=this.file;if(superName){if(t.isMemberExpression(superName)){superClassArgument=superClassCallee=getMemberExpressionObject(superName)}else if(!t.isIdentifier(superName)){superClassArgument=superName;superClassCallee=superName=file.generateUidIdentifier("ref",this.scope)}}this.superName=superName;var container=util.template("class",{CLASS_NAME:className});var block=container.callee.expression.body;var body=this.body=block.body;var constructor=this.constructor=body[0].declarations[0].init;if(this.node.id)constructor.id=className;var returnStatement=body.pop();if(superName){body.push(t.expressionStatement(t.callExpression(file.addDeclaration("extends"),[className,superName])));container.arguments.push(superClassArgument);container.callee.expression.params.push(superClassCallee)}this.buildBody();if(body.length===1){return constructor}else{body.push(returnStatement);return container}};Class.prototype.buildBody=function(){var constructor=this.constructor;var className=this.className;var superName=this.superName;var classBody=this.node.body.body;var body=this.body;var self=this;_.each(classBody,function(node){self.replaceInstanceSuperReferences(node);if(node.key.name==="constructor"){self.pushConstructor(node)}else{self.pushMethod(node)}});if(!this.hasConstructor&&superName){constructor.body.body.push(util.template("class-super-constructor-call",{SUPER_NAME:superName},true))}var instanceProps;var staticProps;if(!_.isEmpty(this.instanceMutatorMap)){var protoId=util.template("prototype-identifier",{CLASS_NAME:className});instanceProps=util.buildDefineProperties(this.instanceMutatorMap,protoId)}if(!_.isEmpty(this.staticMutatorMap)){staticProps=util.buildDefineProperties(this.staticMutatorMap,className)}if(instanceProps||staticProps){staticProps=staticProps||t.literal(null);var args=[className,staticProps];if(instanceProps)args.push(instanceProps);body.push(t.expressionStatement(t.callExpression(this.file.addDeclaration("class-props"),args)))}};Class.prototype.pushMethod=function(node){var methodName=node.key;var mutatorMap=this.instanceMutatorMap;if(node.static)mutatorMap=this.staticMutatorMap;var kind=node.kind;if(kind===""){kind="value";util.pushMutatorMap(mutatorMap,methodName,"writable",t.identifier("true"))}util.pushMutatorMap(mutatorMap,methodName,kind,node)};Class.prototype.superIdentifier=function(methodNode,id,parent){var methodName=methodNode.key;var superName=this.superName||t.identifier("Function");if(parent.property===id){return}else if(t.isCallExpression(parent,{callee:id})){parent.arguments.unshift(t.thisExpression());if(methodName.name==="constructor"){return t.memberExpression(superName,t.identifier("call"))}else{id=superName;if(!methodNode.static){id=t.memberExpression(id,t.identifier("prototype"))}id=t.memberExpression(id,methodName,methodNode.computed);return t.memberExpression(id,t.identifier("call"))}}else if(t.isMemberExpression(parent)&&!methodNode.static){return t.memberExpression(superName,t.identifier("prototype"))}else{return superName}};Class.prototype.replaceInstanceSuperReferences=function(methodNode){var method=methodNode.value;var self=this;traverse(method,function(node,parent){if(t.isIdentifier(node,{name:"super"})){return self.superIdentifier(methodNode,node,parent)}else if(t.isCallExpression(node)){var callee=node.callee;if(!t.isMemberExpression(callee))return;if(callee.object.name!=="super")return;callee.property=t.memberExpression(callee.property,t.identifier("call"));node.arguments.unshift(t.thisExpression())}})};Class.prototype.pushConstructor=function(method){if(method.kind!==""){throw this.file.errorWithNode(method,"illegal kind for constructor method")}var construct=this.constructor;var fn=method.value;this.hasConstructor=true;t.inherits(construct,fn);t.inheritsComments(construct,method);construct.defaults=fn.defaults;construct.params=fn.params;construct.body=fn.body;construct.rest=fn.rest}},{"../../traverse":70,"../../types":74,"../../util":76,lodash:108}],40:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node,parent,file){var hasComputed=false;var computed=[];node.properties=node.properties.filter(function(prop){if(prop.computed){hasComputed=true;computed.unshift(prop);return false}else{return true}});if(!hasComputed)return;var objId=util.getUid(parent,file);var container=util.template("function-return-obj",{KEY:objId,OBJECT:node});var containerCallee=container.callee.expression;var containerBody=containerCallee.body.body;containerCallee._aliasFunction=true;_.each(computed,function(prop){containerBody.unshift(t.expressionStatement(t.assignmentExpression("=",t.memberExpression(objId,prop.key,true),prop.value)))});return container}},{"../../types":74,"../../util":76,lodash:108}],41:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");var _=require("lodash");exports.Program=exports.BlockStatement=exports.ForInStatement=exports.ForOfStatement=exports.ForStatement=function(node,parent,file){var constants={}; var check=function(parent,names){_.each(names,function(nameNode,name){if(!_.has(constants,name))return;if(parent&&t.isBlockStatement(parent)&&parent!==constants[name])return;throw file.errorWithNode(nameNode,name+" is read-only")})};var getIds=function(node){return t.getIds(node,true,["MemberExpression"])};_.each(node.body,function(child,parent){if(child&&t.isVariableDeclaration(child,{kind:"const"})){_.each(child.declarations,function(declar){_.each(getIds(declar),function(nameNode,name){var names={};names[name]=nameNode;check(parent,names);constants[name]=parent});declar._ignoreConstant=true});child._ignoreConstant=true;child.kind="let"}});if(_.isEmpty(constants))return;traverse(node,function(child,parent){if(child._ignoreConstant)return;if(t.isVariableDeclaration(child))return;if(t.isVariableDeclarator(child)||t.isDeclaration(child)||t.isAssignmentExpression(child)){check(parent,getIds(child))}})}},{"../../traverse":70,"../../types":74,lodash:108}],42:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");exports.Function=function(node,parent,file,scope){if(!node.defaults||!node.defaults.length)return;t.ensureBlock(node);var ids=node.params.map(function(param){return t.getIds(param)});var closure=false;_.each(node.defaults,function(def,i){if(!def)return;var param=node.params[i];_.each(ids.slice(i),function(ids){var check=function(node,parent){if(!t.isIdentifier(node)||!t.isReferenced(node,parent))return;if(_.contains(ids,node.name)){throw file.errorWithNode(node,"Temporal dead zone - accessing a variable before it's initialized")}if(scope.has(node.name)){closure=true}};check(def,node);traverse(def,check)});var has=scope.get(param.name);if(has&&!_.contains(node.params,has)){closure=true}});var body=[];_.each(node.defaults,function(def,i){if(!def)return;body.push(util.template("if-undefined-set-to",{VARIABLE:node.params[i],DEFAULT:def},true))});if(closure){var container=t.functionExpression(null,[],node.body,node.generator);container._aliasFunction=true;body.push(t.returnStatement(t.callExpression(container,[])));node.body=t.blockStatement(body)}else{node.body.body=body.concat(node.body.body)}node.defaults=[]}},{"../../traverse":70,"../../types":74,"../../util":76,lodash:108}],43:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildVariableAssign=function(opts,id,init){var op=opts.operator;if(t.isMemberExpression(id))op="=";if(op){return t.expressionStatement(t.assignmentExpression("=",id,init))}else{return t.variableDeclaration(opts.kind,[t.variableDeclarator(id,init)])}};var push=function(opts,nodes,elem,parentId){if(t.isObjectPattern(elem)){pushObjectPattern(opts,nodes,elem,parentId)}else if(t.isArrayPattern(elem)){pushArrayPattern(opts,nodes,elem,parentId)}else{nodes.push(buildVariableAssign(opts,elem,parentId))}};var pushObjectPattern=function(opts,nodes,pattern,parentId){_.each(pattern.properties,function(prop,i){if(t.isSpreadProperty(prop)){var keys=[];_.each(pattern.properties,function(prop2,i2){if(i2>=i)return false;if(t.isSpreadProperty(prop2))return;var key=prop2.key;if(t.isIdentifier(key)){key=t.literal(prop2.key.name)}keys.push(key)});keys=t.arrayExpression(keys);var value=t.callExpression(opts.file.addDeclaration("object-spread"),[parentId,keys]);nodes.push(buildVariableAssign(opts,prop.argument,value))}else{var pattern2=prop.value;var patternId2=t.memberExpression(parentId,prop.key,prop.computed);if(t.isPattern(pattern2)){push(opts,nodes,pattern2,patternId2)}else{nodes.push(buildVariableAssign(opts,pattern2,patternId2))}}})};var pushArrayPattern=function(opts,nodes,pattern,parentId){var _parentId=opts.file.generateUidIdentifier("ref",opts.scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(_parentId,opts.file.toArray(parentId))]));parentId=_parentId;_.each(pattern.elements,function(elem,i){if(!elem)return;var newPatternId;if(t.isSpreadElement(elem)){newPatternId=opts.file.toArray(parentId);if(+i>0){newPatternId=t.callExpression(t.memberExpression(newPatternId,t.identifier("slice")),[t.literal(i)])}elem=elem.argument}else{newPatternId=t.memberExpression(parentId,t.literal(i),true)}push(opts,nodes,elem,newPatternId)})};var pushPattern=function(opts){var nodes=opts.nodes;var pattern=opts.pattern;var parentId=opts.id;var file=opts.file;var scope=opts.scope;if(!t.isMemberExpression(parentId)&&!t.isIdentifier(parentId)){var key=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(key,parentId)]));parentId=key}push(opts,nodes,pattern,parentId)};exports.ForInStatement=exports.ForOfStatement=function(node,parent,file,scope){var declar=node.left;if(!t.isVariableDeclaration(declar))return;var pattern=declar.declarations[0].id;if(!t.isPattern(pattern))return;var key=file.generateUidIdentifier("ref",scope);node.left=t.variableDeclaration(declar.kind,[t.variableDeclarator(key,null)]);var nodes=[];push({kind:declar.kind,file:file,scope:scope},nodes,pattern,key);t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.Function=function(node,parent,file,scope){var nodes=[];var hasDestructuring=false;node.params=node.params.map(function(pattern){if(!t.isPattern(pattern))return pattern;hasDestructuring=true;var parentId=file.generateUidIdentifier("ref",scope);pushPattern({kind:"var",nodes:nodes,pattern:pattern,id:parentId,file:file,scope:scope});return parentId});if(!hasDestructuring)return;t.ensureBlock(node);var block=node.body;block.body=nodes.concat(block.body)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(expr.type!=="AssignmentExpression")return;if(!t.isPattern(expr.left))return;var nodes=[];var ref=file.generateUidIdentifier("ref",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(ref,expr.right)]));push({operator:expr.operator,file:file,scope:scope},nodes,expr.left,ref);return nodes};exports.AssignmentExpression=function(node,parent,file,scope){if(parent.type==="ExpressionStatement")return;if(!t.isPattern(node.left))return;var tempName=file.generateUid("temp",scope);var ref=t.identifier(tempName);scope.push({key:tempName,id:ref});var nodes=[];nodes.push(t.assignmentExpression("=",ref,node.right));push({operator:node.operator,file:file,scope:scope},nodes,node.left,ref);nodes.push(ref);return t.toSequenceExpression(nodes,scope)};exports.VariableDeclaration=function(node,parent,file,scope){if(t.isForInStatement(parent)||t.isForOfStatement(parent))return;var nodes=[];var hasPattern=false;_.each(node.declarations,function(declar){if(t.isPattern(declar.id)){hasPattern=true;return false}});if(!hasPattern)return;_.each(node.declarations,function(declar){var patternId=declar.init;var pattern=declar.id;var opts={kind:node.kind,nodes:nodes,pattern:pattern,id:patternId,file:file,scope:scope};if(t.isPattern(pattern)&&patternId){pushPattern(opts)}else{nodes.push(buildVariableAssign(opts,declar.id,declar.init))}});if(!t.isProgram(parent)&&!t.isBlockStatement(parent)){var declar;_.each(nodes,function(node){declar=declar||t.variableDeclaration(node.kind,[]);if(!t.isVariableDeclaration(node)&&declar.kind!==node.kind){throw file.errorWithNode(node,"Cannot use this node within the current parent")}declar.declarations=declar.declarations.concat(node.declarations)});return declar}return nodes}},{"../../types":74,lodash:108}],44:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.ForOfStatement=function(node,parent,file,scope){var left=node.left;var declar;var stepKey=file.generateUidIdentifier("step",scope);var stepValue=t.memberExpression(stepKey,t.identifier("value"));if(t.isIdentifier(left)){declar=t.expressionStatement(t.assignmentExpression("=",left,stepValue))}else if(t.isVariableDeclaration(left)){declar=t.variableDeclaration(left.kind,[t.variableDeclarator(left.declarations[0].id,stepValue)])}else{throw file.errorWithNode(left,"Unknown node type "+left.type+" in ForOfStatement")}var node2=util.template("for-of",{ITERATOR_KEY:file.generateUidIdentifier("iterator",scope),STEP_KEY:stepKey,OBJECT:node.right});t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":74,"../../util":76}],45:[function(require,module,exports){var assert=require("assert");var loc=require("../util").loc;var t=require("../../../../types");exports.ParenthesizedExpression=function(expr,path,explodeViaTempVar,finish){return finish(this.explodeExpression(path.get("expression")))};exports.MemberExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.memberExpression(this.explodeExpression(path.get("object")),expr.computed?explodeViaTempVar(null,path.get("property")):expr.property,expr.computed))};exports.CallExpression=function(expr,path,explodeViaTempVar,finish){var oldCalleePath=path.get("callee");var newCallee=this.explodeExpression(oldCalleePath);if(!t.isMemberExpression(oldCalleePath.node)&&t.isMemberExpression(newCallee)){newCallee=t.sequenceExpression([t.literal(0),newCallee])}return finish(t.callExpression(newCallee,path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.NewExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.newExpression(explodeViaTempVar(null,path.get("callee")),path.get("arguments").map(function(argPath){return explodeViaTempVar(null,argPath)})))};exports.ObjectExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.objectExpression(path.get("properties").map(function(propPath){return t.property(propPath.value.kind,propPath.value.key,explodeViaTempVar(null,propPath.get("value")))})))};exports.ArrayExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.arrayExpression(path.get("elements").map(function(elemPath){return explodeViaTempVar(null,elemPath)})))};exports.SequenceExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var lastIndex=expr.expressions.length-1;var self=this;var result;path.get("expressions").each(function(exprPath){if(exprPath.name===lastIndex){result=self.explodeExpression(exprPath,ignoreResult)}else{self.explodeExpression(exprPath,true)}});return result};exports.LogicalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var after=loc();var result;if(!ignoreResult){result=this.makeTempVar()}var left=explodeViaTempVar(result,path.get("left"));if(expr.operator==="&&"){this.jumpIfNot(left,after)}else{assert.strictEqual(expr.operator,"||");this.jumpIf(left,after)}explodeViaTempVar(result,path.get("right"),ignoreResult);this.mark(after);return result};exports.ConditionalExpression=function(expr,path,explodeViaTempVar,finish,ignoreResult){var elseLoc=loc();var after=loc();var test=this.explodeExpression(path.get("test"));var result;this.jumpIfNot(test,elseLoc);if(!ignoreResult){result=this.makeTempVar()}explodeViaTempVar(result,path.get("consequent"),ignoreResult);this.jump(after);this.mark(elseLoc);explodeViaTempVar(result,path.get("alternate"),ignoreResult);this.mark(after);return result};exports.UnaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.unaryExpression(expr.operator,this.explodeExpression(path.get("argument")),!!expr.prefix))};exports.BinaryExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.binaryExpression(expr.operator,explodeViaTempVar(null,path.get("left")),explodeViaTempVar(null,path.get("right"))))};exports.AssignmentExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.assignmentExpression(expr.operator,this.explodeExpression(path.get("left")),this.explodeExpression(path.get("right"))))};exports.UpdateExpression=function(expr,path,explodeViaTempVar,finish){return finish(t.updateExpression(expr.operator,this.explodeExpression(path.get("argument")),expr.prefix))};exports.YieldExpression=function(expr,path){var after=loc();var arg=expr.argument&&this.explodeExpression(path.get("argument"));var result;if(arg&&expr.delegate){result=this.makeTempVar();this.emit(t.returnStatement(t.callExpression(this.contextProperty("delegateYield"),[arg,t.literal(result.property.name),after])));this.mark(after);return result}this.emitAssign(this.contextProperty("next"),after);this.emit(t.returnStatement(arg||null));this.mark(after);return this.contextProperty("sent")}},{"../../../../types":74,"../util":52,assert:93}],46:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var util=require("../util");var t=require("../../../../types");var runtimeKeysMethod=util.runtimeProperty("keys");var loc=util.loc;exports.ExpressionStatement=function(path){this.explodeExpression(path.get("expression"),true)};exports.LabeledStatement=function(path,stmt){this.explodeStatement(path.get("body"),stmt.label)};exports.WhileStatement=function(path,stmt,labelId){var before=loc();var after=loc();this.mark(before);this.jumpIfNot(this.explodeExpression(path.get("test")),after);this.leapManager.withEntry(new leap.LoopEntry(after,before,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(before);this.mark(after)};exports.DoWhileStatement=function(path,stmt,labelId){var first=loc();var test=loc();var after=loc();this.mark(first);this.leapManager.withEntry(new leap.LoopEntry(after,test,labelId),function(){this.explode(path.get("body"))});this.mark(test);this.jumpIf(this.explodeExpression(path.get("test")),first);this.mark(after)};exports.ForStatement=function(path,stmt,labelId){var head=loc();var update=loc();var after=loc();if(stmt.init){this.explode(path.get("init"),true)}this.mark(head);if(stmt.test){this.jumpIfNot(this.explodeExpression(path.get("test")),after)}else{}this.leapManager.withEntry(new leap.LoopEntry(after,update,labelId),function(){this.explodeStatement(path.get("body"))});this.mark(update);if(stmt.update){this.explode(path.get("update"),true)}this.jump(head);this.mark(after)};exports.ForInStatement=function(path,stmt,labelId){t.assertIdentifier(stmt.left);var head=loc();var after=loc();var keyIterNextFn=this.makeTempVar();this.emitAssign(keyIterNextFn,t.callExpression(runtimeKeysMethod,[this.explodeExpression(path.get("right"))]));this.mark(head);var keyInfoTmpVar=this.makeTempVar();this.jumpIf(t.memberExpression(t.assignmentExpression("=",keyInfoTmpVar,t.callExpression(keyIterNextFn,[])),t.identifier("done"),false),after);this.emitAssign(stmt.left,t.memberExpression(keyInfoTmpVar,t.identifier("value"),false));this.leapManager.withEntry(new leap.LoopEntry(after,head,labelId),function(){this.explodeStatement(path.get("body"))});this.jump(head);this.mark(after)};exports.BreakStatement=function(path,stmt){this.emitAbruptCompletion({type:"break",target:this.leapManager.getBreakLoc(stmt.label)})};exports.ContinueStatement=function(path,stmt){this.emitAbruptCompletion({type:"continue",target:this.leapManager.getContinueLoc(stmt.label)})};exports.SwitchStatement=function(path,stmt){var disc=this.emitAssign(this.makeTempVar(),this.explodeExpression(path.get("discriminant")));var after=loc();var defaultLoc=loc();var condition=defaultLoc;var caseLocs=[];var self=this;var cases=stmt.cases||[];for(var i=cases.length-1;i>=0;--i){var c=cases[i];t.assertSwitchCase(c);if(c.test){condition=t.conditionalExpression(t.binaryExpression("===",disc,c.test),caseLocs[i]=loc(),condition)}else{caseLocs[i]=defaultLoc}}this.jump(this.explodeExpression(new types.NodePath(condition,path,"discriminant")));this.leapManager.withEntry(new leap.SwitchEntry(after),function(){path.get("cases").each(function(casePath){var i=casePath.name;self.mark(caseLocs[i]);casePath.get("consequent").each(self.explodeStatement,self)})});this.mark(after);if(defaultLoc.value===-1){this.mark(defaultLoc);assert.strictEqual(after.value,defaultLoc.value)}};exports.IfStatement=function(path,stmt){var elseLoc=stmt.alternate&&loc();var after=loc();this.jumpIfNot(this.explodeExpression(path.get("test")),elseLoc||after);this.explodeStatement(path.get("consequent"));if(elseLoc){this.jump(after);this.mark(elseLoc);this.explodeStatement(path.get("alternate"))}this.mark(after)};exports.ReturnStatement=function(path){this.emitAbruptCompletion({type:"return",value:this.explodeExpression(path.get("argument"))})};exports.TryStatement=function(path,stmt){var after=loc();var self=this;var handler=stmt.handler;if(!handler&&stmt.handlers){handler=stmt.handlers[0]||null}var catchLoc=handler&&loc();var catchEntry=catchLoc&&new leap.CatchEntry(catchLoc,handler.param);var finallyLoc=stmt.finalizer&&loc();var finallyEntry=finallyLoc&&new leap.FinallyEntry(finallyLoc);var tryEntry=new leap.TryEntry(this.getUnmarkedCurrentLoc(),catchEntry,finallyEntry);this.tryEntries.push(tryEntry);this.updateContextPrevLoc(tryEntry.firstLoc);this.leapManager.withEntry(tryEntry,function(){this.explodeStatement(path.get("block"));if(catchLoc){if(finallyLoc){this.jump(finallyLoc)}else{this.jump(after)}this.updateContextPrevLoc(self.mark(catchLoc));var bodyPath=path.get("handler","body");var safeParam=this.makeTempVar();this.clearPendingException(tryEntry.firstLoc,safeParam);var catchScope=bodyPath.scope;var catchParamName=handler.param.name;t.assertCatchClause(catchScope.node);assert.strictEqual(catchScope.lookup(catchParamName),catchScope);types.visit(bodyPath,{visitIdentifier:function(path){if(path.value.name===catchParamName&&path.scope.lookup(catchParamName)===catchScope){return safeParam}this.traverse(path)}});this.leapManager.withEntry(catchEntry,function(){this.explodeStatement(bodyPath)})}if(finallyLoc){this.updateContextPrevLoc(this.mark(finallyLoc));this.leapManager.withEntry(finallyEntry,function(){this.explodeStatement(path.get("finalizer"))});this.emit(t.callExpression(this.contextProperty("finish"),[finallyEntry.firstLoc]))}});this.mark(after)};exports.ThrowStatement=function(path){this.emit(t.throwStatement(this.explodeExpression(path.get("argument"))))}},{"../../../../types":74,"../leap":50,"../util":52,assert:93,"ast-types":91}],47:[function(require,module,exports){exports.Emitter=Emitter;var explodeExpressions=require("./explode-expressions");var explodeStatements=require("./explode-statements");var assert=require("assert");var types=require("ast-types");var leap=require("../leap");var meta=require("../meta");var util=require("../util");var t=require("../../../../types");var _=require("lodash");var loc=util.loc;var n=types.namedTypes;function Emitter(contextId){assert.ok(this instanceof Emitter);t.assertIdentifier(contextId);this.contextId=contextId;this.listing=[];this.marked=[true];this.finalLoc=loc();this.tryEntries=[];this.leapManager=new leap.LeapManager(this)}Emitter.prototype.mark=function(loc){t.assertLiteral(loc);var index=this.listing.length;if(loc.value===-1){loc.value=index}else{assert.strictEqual(loc.value,index)}this.marked[index]=true;return loc};Emitter.prototype.emit=function(node){if(t.isExpression(node))node=t.expressionStatement(node);t.assertStatement(node);this.listing.push(node)};Emitter.prototype.emitAssign=function(lhs,rhs){this.emit(this.assign(lhs,rhs));return lhs};Emitter.prototype.assign=function(lhs,rhs){return t.expressionStatement(t.assignmentExpression("=",lhs,rhs))};Emitter.prototype.contextProperty=function(name,computed){return t.memberExpression(this.contextId,computed?t.literal(name):t.identifier(name),!!computed)};var volatileContextPropertyNames={prev:true,next:true,sent:true,rval:true};Emitter.prototype.isVolatileContextProperty=function(expr){if(t.isMemberExpression(expr)){if(expr.computed){return true}if(t.isIdentifier(expr.object)&&t.isIdentifier(expr.property)&&expr.object.name===this.contextId.name&&_.has(volatileContextPropertyNames,expr.property.name)){return true}}return false};Emitter.prototype.stop=function(rval){if(rval){this.setReturnValue(rval)}this.jump(this.finalLoc)};Emitter.prototype.setReturnValue=function(valuePath){t.assertExpression(valuePath.value);this.emitAssign(this.contextProperty("rval"),this.explodeExpression(valuePath))};Emitter.prototype.clearPendingException=function(tryLoc,assignee){t.assertLiteral(tryLoc);var catchCall=t.callExpression(this.contextProperty("catch",true),[tryLoc]);if(assignee){this.emitAssign(assignee,catchCall)}else{this.emit(catchCall)}};Emitter.prototype.jump=function(toLoc){this.emitAssign(this.contextProperty("next"),toLoc);this.emit(t.breakStatement())};Emitter.prototype.jumpIf=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);this.emit(t.ifStatement(test,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};Emitter.prototype.jumpIfNot=function(test,toLoc){t.assertExpression(test);t.assertLiteral(toLoc);var negatedTest;if(t.isUnaryExpression(test)&&test.operator==="!"){negatedTest=test.argument}else{negatedTest=t.unaryExpression("!",test)}this.emit(t.ifStatement(negatedTest,t.blockStatement([this.assign(this.contextProperty("next"),toLoc),t.breakStatement()])))};var nextTempId=0;Emitter.prototype.makeTempVar=function(){return this.contextProperty("t"+nextTempId++)};Emitter.prototype.getContextFunction=function(id){var node=t.functionExpression(id||null,[this.contextId],t.blockStatement([this.getDispatchLoop()]),false,false);node._aliasFunction=true;return node};Emitter.prototype.getDispatchLoop=function(){var self=this;var cases=[];var current;var alreadyEnded=false;self.listing.forEach(function(stmt,i){if(self.marked.hasOwnProperty(i)){cases.push(t.switchCase(t.literal(i),current=[]));alreadyEnded=false}if(!alreadyEnded){current.push(stmt);if(isSwitchCaseEnder(stmt))alreadyEnded=true}});this.finalLoc.value=this.listing.length;cases.push(t.switchCase(this.finalLoc,[]),t.switchCase(t.literal("end"),[t.returnStatement(t.callExpression(this.contextProperty("stop"),[]))]));return t.whileStatement(t.literal(true),t.switchStatement(t.assignmentExpression("=",this.contextProperty("prev"),this.contextProperty("next")),cases))};function isSwitchCaseEnder(stmt){return t.isBreakStatement(stmt)||t.isContinueStatement(stmt)||t.isReturnStatement(stmt)||t.isThrowStatement(stmt)}Emitter.prototype.getTryEntryList=function(){if(this.tryEntries.length===0){return null}var lastLocValue=0;return t.arrayExpression(this.tryEntries.map(function(tryEntry){var thisLocValue=tryEntry.firstLoc.value;assert.ok(thisLocValue>=lastLocValue,"try entries out of order");lastLocValue=thisLocValue;var ce=tryEntry.catchEntry;var fe=tryEntry.finallyEntry;var triple=[tryEntry.firstLoc,ce?ce.firstLoc:null];if(fe){triple[2]=fe.firstLoc}return t.arrayExpression(triple)}))};Emitter.prototype.explode=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var node=path.value;var self=this;n.Node.check(node);if(t.isStatement(node))return self.explodeStatement(path);if(t.isExpression(node))return self.explodeExpression(path,ignoreResult);if(t.isDeclaration(node))throw getDeclError(node);switch(node.type){case"Program":return path.get("body").map(self.explodeStatement,self);case"VariableDeclarator":throw getDeclError(node);case"Property":case"SwitchCase":case"CatchClause":throw new Error(node.type+" nodes should be handled by their parents");default:throw new Error("unknown Node of type "+JSON.stringify(node.type))}};function getDeclError(node){return new Error("all declarations should have been transformed into "+"assignments before the Exploder began its work: "+JSON.stringify(node))}Emitter.prototype.explodeStatement=function(path,labelId){assert.ok(path instanceof types.NodePath);var stmt=path.value;var self=this;t.assertStatement(stmt);if(labelId){t.assertIdentifier(labelId)}else{labelId=null}if(t.isBlockStatement(stmt)){return path.get("body").each(self.explodeStatement,self)}if(!meta.containsLeap(stmt)){self.emit(stmt);return}var fn=explodeStatements[stmt.type];if(fn){fn.call(this,path,stmt,labelId)}else{throw new Error("unknown Statement of type "+JSON.stringify(stmt.type))}};Emitter.prototype.emitAbruptCompletion=function(record){if(!isValidCompletion(record)){assert.ok(false,"invalid completion record: "+JSON.stringify(record))}assert.notStrictEqual(record.type,"normal","normal completions are not abrupt");var abruptArgs=[t.literal(record.type)];if(record.type==="break"||record.type==="continue"){t.assertLiteral(record.target);abruptArgs[1]=record.target}else if(record.type==="return"||record.type==="throw"){if(record.value){t.assertExpression(record.value);abruptArgs[1]=record.value}}this.emit(t.returnStatement(t.callExpression(this.contextProperty("abrupt"),abruptArgs)))};function isValidCompletion(record){var type=record.type;if(type==="normal"){return!_.has(record,"target")}if(type==="break"||type==="continue"){return!_.has(record,"value")&&t.isLiteral(record.target)}if(type==="return"||type==="throw"){return _.has(record,"value")&&!_.has(record,"target")}return false}Emitter.prototype.getUnmarkedCurrentLoc=function(){return t.literal(this.listing.length)};Emitter.prototype.updateContextPrevLoc=function(loc){if(loc){t.assertLiteral(loc);if(loc.value===-1){loc.value=this.listing.length}else{assert.strictEqual(loc.value,this.listing.length)}}else{loc=this.getUnmarkedCurrentLoc()}this.emitAssign(this.contextProperty("prev"),loc)};Emitter.prototype.explodeExpression=function(path,ignoreResult){assert.ok(path instanceof types.NodePath);var expr=path.value;if(expr){t.assertExpression(expr)}else{return expr}var self=this;function finish(expr){t.assertExpression(expr);if(ignoreResult){self.emit(expr)}else{return expr}}if(!meta.containsLeap(expr)){return finish(expr)}var hasLeapingChildren=meta.containsLeap.onlyChildren(expr);function explodeViaTempVar(tempVar,childPath,ignoreChildResult){assert.ok(childPath instanceof types.NodePath);assert.ok(!ignoreChildResult||!tempVar,"Ignoring the result of a child expression but forcing it to "+"be assigned to a temporary variable?");var result=self.explodeExpression(childPath,ignoreChildResult);if(ignoreChildResult){}else if(tempVar||hasLeapingChildren&&(self.isVolatileContextProperty(result)||meta.hasSideEffects(result))){result=self.emitAssign(tempVar||self.makeTempVar(),result)}return result}var fn=explodeExpressions[expr.type];if(fn){return fn.call(this,expr,path,explodeViaTempVar,finish,ignoreResult)}else{throw new Error("unknown Expression of type "+JSON.stringify(expr.type))}}},{"../../../../types":74,"../leap":50,"../meta":51,"../util":52,"./explode-expressions":45,"./explode-statements":46,assert:93,"ast-types":91,lodash:108}],48:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var t=require("../../../types");var _=require("lodash");exports.hoist=function(funPath){assert.ok(funPath instanceof types.NodePath);t.assertFunction(funPath.value);var vars={};function varDeclToExpr(vdec,includeIdentifiers){t.assertVariableDeclaration(vdec);var exprs=[];vdec.declarations.forEach(function(dec){vars[dec.id.name]=dec.id;if(dec.init){exprs.push(t.assignmentExpression("=",dec.id,dec.init))}else if(includeIdentifiers){exprs.push(dec.id)}});if(exprs.length===0)return null;if(exprs.length===1)return exprs[0];return t.sequenceExpression(exprs)}types.visit(funPath.get("body"),{visitVariableDeclaration:function(path){var expr=varDeclToExpr(path.value,false);if(expr===null){path.replace()}else{return t.expressionStatement(expr)}return false},visitForStatement:function(path){var init=path.value.init;if(t.isVariableDeclaration(init)){path.get("init").replace(varDeclToExpr(init,false))}this.traverse(path)},visitForInStatement:function(path){var left=path.value.left;if(t.isVariableDeclaration(left)){path.get("left").replace(varDeclToExpr(left,true))}this.traverse(path)},visitFunctionDeclaration:function(path){var node=path.value;vars[node.id.name]=node.id;var assignment=t.expressionStatement(t.assignmentExpression("=",node.id,t.functionExpression(node.id,node.params,node.body,node.generator,node.expression)));if(t.isBlockStatement(path.parent.node)){path.parent.get("body").unshift(assignment);path.replace()}else{path.replace(assignment)}return false},visitFunctionExpression:function(){return false}});var paramNames={};funPath.get("params").each(function(paramPath){var param=paramPath.value;if(t.isIdentifier(param)){paramNames[param.name]=param}else{}});var declarations=[];Object.keys(vars).forEach(function(name){if(!_.has(paramNames,name)){declarations.push(t.variableDeclarator(vars[name],null))}});if(declarations.length===0){return null}return t.variableDeclaration("var",declarations)}},{"../../../types":74,assert:93,"ast-types":91,lodash:108}],49:[function(require,module,exports){module.exports=require("./visit").transform},{"./visit":53}],50:[function(require,module,exports){exports.FunctionEntry=FunctionEntry;exports.FinallyEntry=FinallyEntry;exports.SwitchEntry=SwitchEntry;exports.LeapManager=LeapManager;exports.CatchEntry=CatchEntry;exports.LoopEntry=LoopEntry;exports.TryEntry=TryEntry;var assert=require("assert");var util=require("util");var t=require("../../../types");var inherits=util.inherits;function Entry(){assert.ok(this instanceof Entry)}function FunctionEntry(returnLoc){Entry.call(this);t.assertLiteral(returnLoc);this.returnLoc=returnLoc}inherits(FunctionEntry,Entry);function LoopEntry(breakLoc,continueLoc,label){Entry.call(this);t.assertLiteral(breakLoc);t.assertLiteral(continueLoc);if(label){t.assertIdentifier(label)}else{label=null}this.breakLoc=breakLoc;this.continueLoc=continueLoc;this.label=label}inherits(LoopEntry,Entry);function SwitchEntry(breakLoc){Entry.call(this);t.assertLiteral(breakLoc);this.breakLoc=breakLoc}inherits(SwitchEntry,Entry);function TryEntry(firstLoc,catchEntry,finallyEntry){Entry.call(this);t.assertLiteral(firstLoc);if(catchEntry){assert.ok(catchEntry instanceof CatchEntry)}else{catchEntry=null}if(finallyEntry){assert.ok(finallyEntry instanceof FinallyEntry)}else{finallyEntry=null}assert.ok(catchEntry||finallyEntry);this.firstLoc=firstLoc;this.catchEntry=catchEntry;this.finallyEntry=finallyEntry}inherits(TryEntry,Entry);function CatchEntry(firstLoc,paramId){Entry.call(this);t.assertLiteral(firstLoc);t.assertIdentifier(paramId);this.firstLoc=firstLoc;this.paramId=paramId}inherits(CatchEntry,Entry);function FinallyEntry(firstLoc){Entry.call(this);t.assertLiteral(firstLoc);this.firstLoc=firstLoc}inherits(FinallyEntry,Entry);function LeapManager(emitter){assert.ok(this instanceof LeapManager);var Emitter=require("./emit").Emitter;assert.ok(emitter instanceof Emitter);this.emitter=emitter;this.entryStack=[new FunctionEntry(emitter.finalLoc)]}LeapManager.prototype.withEntry=function(entry,callback){assert.ok(entry instanceof Entry);this.entryStack.push(entry);try{callback.call(this.emitter)}finally{var popped=this.entryStack.pop();assert.strictEqual(popped,entry)}};LeapManager.prototype._findLeapLocation=function(property,label){for(var i=this.entryStack.length-1;i>=0;--i){var entry=this.entryStack[i];var loc=entry[property];if(loc){if(label){if(entry.label&&entry.label.name===label.name){return loc}}else{return loc}}}return null};LeapManager.prototype.getBreakLoc=function(label){return this._findLeapLocation("breakLoc",label)};LeapManager.prototype.getContinueLoc=function(label){return this._findLeapLocation("continueLoc",label)}},{"../../../types":74,"./emit":47,assert:93,util:102}],51:[function(require,module,exports){var assert=require("assert");var types=require("ast-types");var m=require("private").makeAccessor();var _=require("lodash");var isArray=types.builtInTypes.array;var n=types.namedTypes;function makePredicate(propertyName,knownTypes){function onlyChildren(node){n.Node.check(node);var result=false;function check(child){if(result){}else if(isArray.check(child)){child.some(check)}else if(n.Node.check(child)){assert.strictEqual(result,false);result=predicate(child)}return result}types.eachField(node,function(name,child){check(child)});return result}function predicate(node){n.Node.check(node);var meta=m(node);if(_.has(meta,propertyName))return meta[propertyName]; if(_.has(opaqueTypes,node.type))return meta[propertyName]=false;if(_.has(knownTypes,node.type))return meta[propertyName]=true;return meta[propertyName]=onlyChildren(node)}predicate.onlyChildren=onlyChildren;return predicate}var opaqueTypes={FunctionExpression:true};var sideEffectTypes={CallExpression:true,ForInStatement:true,UnaryExpression:true,BinaryExpression:true,AssignmentExpression:true,UpdateExpression:true,NewExpression:true};var leapTypes={YieldExpression:true,BreakStatement:true,ContinueStatement:true,ReturnStatement:true,ThrowStatement:true};for(var type in leapTypes){if(_.has(leapTypes,type)){sideEffectTypes[type]=leapTypes[type]}}exports.hasSideEffects=makePredicate("hasSideEffects",sideEffectTypes);exports.containsLeap=makePredicate("containsLeap",leapTypes)},{assert:93,"ast-types":91,lodash:108,"private":109}],52:[function(require,module,exports){var t=require("../../../types");exports.runtimeProperty=function(name){return t.memberExpression(t.identifier("regeneratorRuntime"),t.identifier(name))};exports.loc=function(){return t.literal(-1)}},{"../../../types":74}],53:[function(require,module,exports){var runtimeProperty=require("./util").runtimeProperty;var Emitter=require("./emit").Emitter;var hoist=require("./hoist").hoist;var types=require("ast-types");var t=require("../../../types");var runtimeAsyncMethod=runtimeProperty("async");var runtimeWrapMethod=runtimeProperty("wrap");var runtimeMarkMethod=runtimeProperty("mark");exports.transform=function transform(node,file){return types.visit(node,{visitFunction:function(path){return visitor.call(this,path,file)}})};var visitor=function(path,file){this.traverse(path);var node=path.value;var scope;if(!node.generator&&!node.async){return}node.generator=false;if(node.expression){node.expression=false;node.body=t.blockStatement([t.returnStatement(node.body)])}if(node.async){awaitVisitor.visit(path.get("body"))}var outerFnId=node.id||(node.id=file.generateUidIdentifier("callee",scope));var innerFnId=t.identifier(node.id.name+"$");var contextId=file.generateUidIdentifier("context",scope);var vars=hoist(path);var emitter=new Emitter(contextId);emitter.explode(path.get("body"));var outerBody=[];if(vars&&vars.declarations.length>0){outerBody.push(vars)}var wrapArgs=[emitter.getContextFunction(innerFnId),node.async?t.literal(null):outerFnId,t.thisExpression()];var tryEntryList=emitter.getTryEntryList();if(tryEntryList){wrapArgs.push(tryEntryList)}var wrapCall=t.callExpression(node.async?runtimeAsyncMethod:runtimeWrapMethod,wrapArgs);outerBody.push(t.returnStatement(wrapCall));node.body=t.blockStatement(outerBody);if(node.async){node.async=false;return}if(t.isFunctionDeclaration(node)){var pp=path.parent;while(pp&&!(t.isBlockStatement(pp.value)||t.isProgram(pp.value))){pp=pp.parent}if(!pp){return}path.replace();node.type="FunctionExpression";var varDecl=t.variableDeclaration("var",[t.variableDeclarator(node.id,t.callExpression(runtimeMarkMethod,[node]))]);t.inheritsComments(varDecl,node);t.removeComments(node);varDecl._blockHoist=true;var bodyPath=pp.get("body");var bodyLen=bodyPath.value.length;for(var i=0;i<bodyLen;++i){var firstStmtPath=bodyPath.get(i);if(!shouldNotHoistAbove(firstStmtPath)){firstStmtPath.insertBefore(varDecl);return}}bodyPath.push(varDecl)}else{t.assertFunctionExpression(node);return t.callExpression(runtimeMarkMethod,[node])}};function shouldNotHoistAbove(stmtPath){var value=stmtPath.value;t.assertStatement(value);if(t.isExpressionStatement(value)&&t.isLiteral(value.expression)&&value.expression.value==="use strict"){return true}if(t.isVariableDeclaration(value)){for(var i=0;i<value.declarations.length;++i){var decl=value.declarations[i];if(t.isCallExpression(decl.init)&&types.astNodesAreEquivalent(decl.init.callee,runtimeMarkMethod)){return true}}}return false}var awaitVisitor=types.PathVisitor.fromMethodsObject({visitFunction:function(){return false},visitAwaitExpression:function(path){return t.yieldExpression(path.value.argument,false)}})},{"../../../types":74,"./emit":47,"./hoist":48,"./util":52,"ast-types":91}],54:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");var isLet=function(node){if(!t.isVariableDeclaration(node))return false;if(node._let)return true;if(node.kind!=="let")return false;node._let=true;node.kind="var";return true};var isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!isLet(node)};var standardiseLets=function(declars){_.each(declars,function(declar){delete declar._let})};exports.VariableDeclaration=function(node){isLet(node)};exports.For=function(node,parent,file,scope){var init=node.left||node.init;if(isLet(init)){t.ensureBlock(node);node.body._letDeclars=[init]}if(t.isLabeledStatement(parent)){node.label=parent.label}var letScoping=new LetScoping(node,node.body,parent,file,scope);letScoping.run();if(node.label&&!t.isLabeledStatement(parent)){return t.labeledStatement(node.label,node)}};exports.BlockStatement=function(block,parent,file,scope){if(!t.isFor(parent)){var letScoping=new LetScoping(false,block,parent,file,scope);letScoping.run()}};function LetScoping(forParent,block,parent,file,scope){this.forParent=forParent;this.parent=parent;this.scope=scope;this.block=block;this.file=file;this.letReferences={};this.body=[]}LetScoping.prototype.run=function(){var block=this.block;if(block._letDone)return;block._letDone=true;this.info=this.getInfo();this.remap();if(t.isFunction(this.parent))return this.noClosure();if(!this.info.keys.length)return this.noClosure();var referencesInClosure=this.getLetReferences();if(!referencesInClosure)return this.noClosure();this.has=this.checkFor();this.hoistVarDeclarations();standardiseLets(this.info.declarators);var letReferences=_.values(this.letReferences);var fn=t.functionExpression(null,letReferences,t.blockStatement(block.body));fn._aliasFunction=true;block.body=this.body;var params=this.getParams(letReferences);var call=t.callExpression(fn,params);var ret=this.file.generateUidIdentifier("ret",this.scope);var hasYield=traverse.hasType(fn.body,"YieldExpression",t.FUNCTION_TYPES);if(hasYield){fn.generator=true;call=t.yieldExpression(call,true)}this.build(ret,call)};LetScoping.prototype.noClosure=function(){standardiseLets(this.info.declarators)};LetScoping.prototype.remap=function(){var replacements=this.info.duplicates;var block=this.block;if(_.isEmpty(replacements))return;var replace=function(node,parent,scope){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope&&scope.hasOwn(node.name))return;node.name=replacements[node.name]||node.name};var traverseReplace=function(node,parent){replace(node,parent);traverse(node,replace)};var forParent=this.forParent;if(forParent){traverseReplace(forParent.right,forParent);traverseReplace(forParent.test,forParent);traverseReplace(forParent.update,forParent)}traverse(block,replace)};LetScoping.prototype.getInfo=function(){var block=this.block;var scope=this.scope;var file=this.file;var opts={outsideKeys:[],declarators:block._letDeclars||[],duplicates:{},keys:[]};var duplicates=function(id,key){var has=scope.parentGet(key);if(has&&has!==id){opts.duplicates[key]=id.name=file.generateUid(key,scope)}};_.each(opts.declarators,function(declar){opts.declarators.push(declar);var keys=t.getIds(declar,true);_.each(keys,duplicates);keys=_.keys(keys);opts.outsideKeys=opts.outsideKeys.concat(keys);opts.keys=opts.keys.concat(keys)});_.each(block.body,function(declar){if(!isLet(declar))return;_.each(t.getIds(declar,true),function(id,key){duplicates(id,key);opts.keys.push(key)})});return opts};LetScoping.prototype.checkFor=function(){var has={hasContinue:false,hasReturn:false,hasBreak:false};var forParent=this.forParent;traverse(this.block,function(node){var replace;if(t.isFunction(node)||t.isFor(node)){return false}if(forParent&&node&&!node.label){if(t.isBreakStatement(node)){has.hasBreak=true;replace=t.returnStatement(t.literal("break"))}else if(t.isContinueStatement(node)){has.hasContinue=true;replace=t.returnStatement(t.literal("continue"))}}if(t.isReturnStatement(node)){has.hasReturn=true;replace=t.returnStatement(t.objectExpression([t.property("init",t.identifier("v"),node.argument||t.identifier("undefined"))]))}if(replace)return t.inherits(replace,node)});return has};LetScoping.prototype.hoistVarDeclarations=function(){var self=this;traverse(this.block,function(node){if(t.isForStatement(node)){if(isVar(node.init)){node.init=t.sequenceExpression(self.pushDeclar(node.init))}}else if(t.isFor(node)){if(isVar(node.left)){node.left=node.left.declarations[0].id}}else if(isVar(node)){return self.pushDeclar(node).map(t.expressionStatement)}else if(t.isFunction(node)){return false}})};LetScoping.prototype.getParams=function(params){var info=this.info;params=_.cloneDeep(params);_.each(params,function(param){param.name=info.duplicates[param.name]||param.name});return params};LetScoping.prototype.getLetReferences=function(){var closurify=false;var self=this;traverse(this.block,function(node,parent,scope){if(t.isFunction(node)){traverse(node,function(node,parent){if(!t.isIdentifier(node))return;if(!t.isReferenced(node,parent))return;if(scope.hasOwn(node.name))return;closurify=true;if(!_.contains(self.info.outsideKeys,node.name))return;self.letReferences[node.name]=node});return false}else if(t.isFor(node)){return false}});return closurify};LetScoping.prototype.pushDeclar=function(node){this.body.push(t.variableDeclaration(node.kind,node.declarations.map(function(declar){return t.variableDeclarator(declar.id)})));var replace=[];_.each(node.declarations,function(declar){if(!declar.init)return;var expr=t.assignmentExpression("=",declar.id,declar.init);replace.push(t.inherits(expr,declar))});return replace};LetScoping.prototype.build=function(ret,call){var has=this.has;if(has.hasReturn||has.hasBreak||has.hasContinue){this.buildHas(ret,call)}else{this.body.push(t.expressionStatement(call))}};LetScoping.prototype.buildHas=function(ret,call){var body=this.body;body.push(t.variableDeclaration("var",[t.variableDeclarator(ret,call)]));var forParent=this.forParent;var retCheck;var has=this.has;var cases=[];if(has.hasReturn){retCheck=util.template("let-scoping-return",{RETURN:ret})}if(has.hasBreak||has.hasContinue){var label=forParent.label=forParent.label||this.file.generateUidIdentifier("loop",this.scope);if(has.hasBreak){cases.push(t.switchCase(t.literal("break"),[t.breakStatement(label)]))}if(has.hasContinue){cases.push(t.switchCase(t.literal("continue"),[t.continueStatement(label)]))}if(has.hasReturn){cases.push(t.switchCase(null,[retCheck]))}if(cases.length===1){var single=cases[0];body.push(t.ifStatement(t.binaryExpression("===",ret,single.test),single.consequent[0]))}else{body.push(t.switchStatement(ret,cases))}}else{if(has.hasReturn)body.push(retCheck)}}},{"../../traverse":70,"../../types":74,"../../util":76,lodash:108}],55:[function(require,module,exports){var _=require("lodash");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){_.each(node.specifiers,function(specifier){file.moduleFormatter.importSpecifier(specifier,node,nodes,parent)})}else{file.moduleFormatter.import(node,nodes,parent)}return nodes};exports.ExportDeclaration=function(node,parent,file){var nodes=[];if(node.declaration){file.moduleFormatter.export(node,nodes,parent)}else{_.each(node.specifiers,function(specifier){file.moduleFormatter.exportSpecifier(specifier,node,nodes,parent)})}return nodes}},{lodash:108}],56:[function(require,module,exports){exports.Property=function(node){if(!node.shorthand)return;node.shorthand=false}},{}],57:[function(require,module,exports){var t=require("../../types");exports.Function=function(node,parent,file){if(!node.rest)return;var rest=node.rest;delete node.rest;t.ensureBlock(node);var call=file.toArray(t.identifier("arguments"));if(node.params.length){call.arguments.push(t.literal(node.params.length))}call._ignoreAliasFunctions=true;node.body.body.unshift(t.variableDeclaration("var",[t.variableDeclarator(rest,call)]))}},{"../../types":74}],58:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var getSpreadLiteral=function(spread,file){return file.toArray(spread.argument)};var hasSpread=function(nodes){var has=false;_.each(nodes,function(node){if(t.isSpreadElement(node)){has=true;return false}});return has};var build=function(props,file){var nodes=[];var _props=[];var push=function(){if(!_props.length)return;nodes.push(t.arrayExpression(_props));_props=[]};_.each(props,function(prop){if(t.isSpreadElement(prop)){push();nodes.push(getSpreadLiteral(prop,file))}else{_props.push(prop)}});push();return nodes};exports.ArrayExpression=function(node,parent,file){var elements=node.elements;if(!hasSpread(elements))return;var nodes=build(elements,file);var first=nodes.shift();if(!t.isArrayExpression(first)){nodes.unshift(first);first=t.arrayExpression([])}return t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)};exports.CallExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var contextLiteral=t.literal(null);node.arguments=[];var nodes;if(args.length===1&&args[0].argument.name==="arguments"){nodes=[args[0].argument]}else{nodes=build(args,file)}var first=nodes.shift();if(nodes.length){node.arguments.push(t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes))}else{node.arguments.push(first)}var callee=node.callee;if(t.isMemberExpression(callee)){contextLiteral=callee.object;if(callee.computed){callee.object=t.memberExpression(callee.object,callee.property,true);callee.property=t.identifier("apply");callee.computed=false}else{callee.property=t.memberExpression(callee.property,t.identifier("apply"))}}else{node.callee=t.memberExpression(node.callee,t.identifier("apply"))}node.arguments.unshift(contextLiteral)};exports.NewExpression=function(node,parent,file){var args=node.arguments;if(!hasSpread(args))return;var nodes=build(args,file);var first=nodes.shift();if(nodes.length){args=t.callExpression(t.memberExpression(first,t.identifier("concat")),nodes)}else{args=first}return t.callExpression(file.addDeclaration("apply-constructor"),[node.callee,args])}},{"../../types":74,lodash:108}],59:[function(require,module,exports){var t=require("../../types");var _=require("lodash");var buildBinaryExpression=function(left,right){return t.binaryExpression("+",left,right)};exports.TaggedTemplateExpression=function(node,parent,file){var args=[];var quasi=node.quasi;var strings=[];var raw=[];_.each(quasi.quasis,function(elem){strings.push(t.literal(elem.value.cooked));raw.push(t.literal(elem.value.raw))});args.push(t.callExpression(file.addDeclaration("tagged-template-literal"),[t.arrayExpression(strings),t.arrayExpression(raw)]));args=args.concat(quasi.expressions);return t.callExpression(node.tag,args)};exports.TemplateLiteral=function(node){var nodes=[];_.each(node.quasis,function(elem){nodes.push(t.literal(elem.value.raw));var expr=node.expressions.shift();if(expr){if(t.isBinary(expr))expr=t.parenthesizedExpression(expr);nodes.push(expr)}});if(nodes.length>1){var last=_.last(nodes);if(t.isLiteral(last,{value:""}))nodes.pop();var root=buildBinaryExpression(nodes.shift(),nodes.shift());_.each(nodes,function(node){root=buildBinaryExpression(root,node)});return root}else{return nodes[0]}}},{"../../types":74,lodash:108}],60:[function(require,module,exports){var rewritePattern=require("regexpu/rewrite-pattern");var _=require("lodash");exports.Literal=function(node){var regex=node.regex;if(!regex)return;var flags=regex.flags.split("");if(!_.contains(regex.flags,"u"))return;_.pull(flags,"u");regex.pattern=rewritePattern(regex.pattern,regex.flags);regex.flags=flags.join("")}},{lodash:108,"regexpu/rewrite-pattern":115}],61:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var container=function(parent,call,ret){if(t.isExpressionStatement(parent)){return call}else{var exprs=[];if(t.isSequenceExpression(call)){exprs=call.expressions}else{exprs.push(call)}exprs.push(ret);return t.sequenceExpression(exprs)}};exports.AssignmentExpression=function(node,parent,file,scope){var left=node.left;if(!t.isVirtualPropertyExpression(left))return;var value=node.right;var temp;if(!t.isExpressionStatement(parent)){if(t.isDynamic(value)){var tempName=file.generateUid("temp");temp=value=t.identifier(tempName);scope.push({key:tempName,id:temp})}}var call=util.template("abstract-expression-set",{PROPERTY:left.property,OBJECT:left.object,VALUE:value});if(temp){call=t.sequenceExpression([t.assignmentExpression("=",temp,node.right),call])}return container(parent,call,value)};exports.UnaryExpression=function(node,parent){var arg=node.argument;if(!t.isVirtualPropertyExpression(arg))return;if(node.operator!=="delete")return;var call=util.template("abstract-expression-delete",{PROPERTY:arg.property,OBJECT:arg.object});return container(parent,call,t.literal(true))};exports.CallExpression=function(node,parent,file,scope){var callee=node.callee;if(!t.isVirtualPropertyExpression(callee))return;var temp;if(t.isDynamic(callee.object)){var tempName=file.generateUid("temp");temp=t.identifier(tempName);scope.push({key:tempName,id:temp})}var call=util.template("abstract-expression-call",{PROPERTY:callee.property,OBJECT:temp||callee.object});call.arguments=call.arguments.concat(node.arguments);if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,callee.object),call])}else{return call}};exports.VirtualPropertyExpression=function(node){return util.template("abstract-expression-get",{PROPERTY:node.property,OBJECT:node.object})}},{"../../types":74,"../../util":76}],62:[function(require,module,exports){var util=require("../../util");var t=require("../../types");var _=require("lodash");var single=function(node,file){var block=node.blocks[0];var templateName="array-expression-comprehension-map";if(node.filter)templateName="array-expression-comprehension-filter";var result=util.template(templateName,{STATEMENT:node.body,FILTER:node.filter,ARRAY:file.toArray(block.right),KEY:block.left});_.each([result.callee.object,result],function(call){if(t.isCallExpression(call)){call.arguments[0]._aliasFunction=true}});return result};var multiple=function(node,file){var uid=file.generateUidIdentifier("arr");var container=util.template("array-comprehension-container",{KEY:uid});container.callee.expression._aliasFunction=true;var block=container.callee.expression.body;var body=block.body;var returnStatement=body.pop();body.push(exports._build(node,function(){return util.template("array-push",{STATEMENT:node.body,KEY:uid},true)}));body.push(returnStatement);return container};exports._build=function(node,buildBody){var self=node.blocks.shift();if(!self)return;var child=exports._build(node,buildBody);if(!child){child=buildBody();if(node.filter){child=t.ifStatement(node.filter,t.blockStatement([child]))}}return t.forOfStatement(t.variableDeclaration("var",[t.variableDeclarator(self.left)]),self.right,t.blockStatement([child]))};exports.ComprehensionExpression=function(node,parent,file){if(node.generator)return;if(node.blocks.length===1){return single(node,file)}else{return multiple(node,file)}}},{"../../types":74,"../../util":76,lodash:108}],63:[function(require,module,exports){var t=require("../../types");var pow=t.memberExpression(t.identifier("Math"),t.identifier("pow"));exports.AssignmentExpression=function(node){if(node.operator!=="**=")return;node.operator="=";node.right=t.callExpression(pow,[node.left,node.right])};exports.BinaryExpression=function(node){if(node.operator!=="**")return;return t.callExpression(pow,[node.left,node.right])}},{"../../types":74}],64:[function(require,module,exports){var arrayComprehension=require("./es7-array-comprehension");var t=require("../../types");exports.ComprehensionExpression=function(node){if(!node.generator)return;var body=[];var container=t.functionExpression(null,[],t.blockStatement(body),true);body.push(arrayComprehension._build(node,function(){return t.expressionStatement(t.yieldExpression(node.body))}));return t.callExpression(container,[])}},{"../../types":74,"./es7-array-comprehension":62}],65:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.ObjectExpression=function(node){var hasSpread=false;_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){hasSpread=true;return false}});if(!hasSpread)return;var args=[];var props=[];var push=function(){if(!props.length)return;args.push(t.objectExpression(props));props=[]};_.each(node.properties,function(prop){if(t.isSpreadProperty(prop)){push();args.push(prop.argument)}else{props.push(prop)}});push();if(!t.isObjectExpression(args[0])){args.unshift(t.objectExpression([]))}return t.callExpression(t.memberExpression(t.identifier("Object"),t.identifier("assign")),args)}},{"../../types":74,lodash:108}],66:[function(require,module,exports){var t=require("../../types");var isMemo=function(node){var is=t.isAssignmentExpression(node)&&node.operator==="?=";if(is)t.assertMemberExpression(node.left);return is};var getPropRef=function(nodes,prop,file,scope){if(t.isIdentifier(prop)){return t.literal(prop.name)}else{var temp=file.generateUidIdentifier("propKey",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,prop)]));return temp}};var getObjRef=function(nodes,obj,file,scope){if(t.isDynamic(obj)){var temp=file.generateUidIdentifier("obj",scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(temp,obj)]));return temp}else{return obj}};var buildHasOwn=function(obj,prop,file){return t.unaryExpression("!",t.callExpression(t.memberExpression(file.addDeclaration("has-own"),t.identifier("call")),[obj,prop]),true)};var buildAbsoluteRef=function(left,obj,prop){var computed=left.computed||t.isLiteral(prop);return t.memberExpression(obj,prop,computed)};var buildAssignment=function(expr,obj,prop){return t.assignmentExpression("=",buildAbsoluteRef(expr.left,obj,prop),expr.right)};exports.ExpressionStatement=function(node,parent,file,scope){var expr=node.expression;if(!isMemo(expr))return;var nodes=[];var left=expr.left;var obj=getObjRef(nodes,left.object,file,scope);var prop=getPropRef(nodes,left.property,file,scope);nodes.push(t.ifStatement(buildHasOwn(obj,prop,file),t.expressionStatement(buildAssignment(expr,obj,prop))));return nodes};exports.AssignmentExpression=function(node,parent,file,scope){if(t.isExpressionStatement(parent))return;if(!isMemo(node))return;var nodes=[];var left=node.left;var obj=getObjRef(nodes,left.object,file,scope);var prop=getPropRef(nodes,left.property,file,scope);nodes.push(t.logicalExpression("&&",buildHasOwn(obj,prop,file),buildAssignment(node,obj,prop)));nodes.push(buildAbsoluteRef(left,obj,prop));return t.toSequenceExpression(nodes,scope)}},{"../../types":74}],67:[function(require,module,exports){var t=require("../../types");var _=require("lodash");exports.BindMemberExpression=function(node,parent,file,scope){var object=node.object;var prop=node.property;var temp;if(t.isDynamic(object)){var tempName=file.generateUid("temp",scope);temp=object=t.identifier(tempName);scope.push({key:tempName,id:temp})}var call=t.callExpression(t.memberExpression(t.memberExpression(object,prop),t.identifier("bind")),[object].concat(node.arguments));if(temp){return t.sequenceExpression([t.assignmentExpression("=",temp,node.object),call])}else{return call}};exports.BindFunctionExpression=function(node,parent,file,scope){var buildCall=function(args){var param=file.generateUidIdentifier("val",scope);return t.functionExpression(null,[param],t.blockStatement([t.returnStatement(t.callExpression(t.memberExpression(param,node.callee),args))]))};if(_.find(node.arguments,t.isDynamic)){var argsIdName=file.generateUid("args",scope);var argsId=t.identifier(argsIdName);scope.push({key:argsIdName,id:argsId});return t.sequenceExpression([t.assignmentExpression("=",argsId,t.arrayExpression(node.arguments)),buildCall(node.arguments.map(function(node,i){return t.memberExpression(argsId,t.literal(i),true)}))])}else{return buildCall(node.arguments)}}},{"../../types":74,lodash:108}],68:[function(require,module,exports){var esutils=require("esutils");var t=require("../../types");var _=require("lodash");exports.XJSIdentifier=function(node){if(esutils.keyword.isIdentifierName(node.name)){node.type="Identifier"}else{return t.literal(node.name)}};exports.XJSNamespacedName=function(node,parent,file){throw file.errorWithNode(node,"Namespace tags are not supported. ReactJSX is not XML.")};exports.XJSMemberExpression={exit:function(node){node.computed=t.isLiteral(node.property);node.type="MemberExpression"}};exports.XJSExpressionContainer=function(node){return node.expression};exports.XJSAttribute={exit:function(node){var value=node.value||t.literal(true);return t.property("init",node.name,value)}};exports.XJSOpeningElement={exit:function(node){var tagExpr=node.name;var args=[];var tagName;if(t.isIdentifier(tagExpr)){tagName=tagExpr.name}else if(t.isLiteral(tagExpr)){tagName=tagExpr.value}if(tagName&&(/[a-z]/.exec(tagName[0])||_.contains(tagName,"-"))){args.push(t.literal(tagName))}else{args.push(tagExpr)}var props=node.attributes;if(props.length){var _props=[];var objs=[];var pushProps=function(){if(!_props.length)return;objs.push(t.objectExpression(_props));_props=[]};while(props.length){var prop=props.shift();if(t.isXJSSpreadAttribute(prop)){pushProps();objs.push(prop.argument)}else{_props.push(prop)}}pushProps();if(objs.length===1){props=objs[0]}else{if(!t.isObjectExpression(objs[0])){objs.unshift(t.objectExpression([]))}props=t.callExpression(t.memberExpression(t.identifier("React"),t.identifier("__spread")),objs)}}else{props=t.literal(null)}args.push(props);tagExpr=t.memberExpression(t.identifier("React"),t.identifier("createElement"));return t.callExpression(tagExpr,args)}};exports.XJSElement={exit:function(node){var callExpr=node.openingElement;_.each(node.children,function(child){if(t.isLiteral(child)){var lines=child.value.split(/\r\n|\n|\r/);_.each(lines,function(line,i){var isFirstLine=i===0;var isLastLine=i===lines.length-1;var trimmedLine=line.replace(/\t/g," ");if(!isFirstLine){trimmedLine=trimmedLine.replace(/^[ ]+/,"")}if(!isLastLine){trimmedLine=trimmedLine.replace(/[ ]+$/,"")}if(trimmedLine){callExpr.arguments.push(t.literal(trimmedLine))}});return}else if(t.isXJSEmptyExpression(child)){return}callExpr.arguments.push(child)});return t.inherits(callExpr,node)}};var addDisplayName=function(id,call){if(!call||!t.isCallExpression(call))return;var callee=call.callee;if(!t.isMemberExpression(callee))return;var obj=callee.object;if(!t.isIdentifier(obj,{name:"React"}))return;var prop=callee.property;if(!t.isIdentifier(prop,{name:"createClass"}))return;var args=call.arguments;if(args.length!==1)return;var first=args[0];if(!t.isObjectExpression(first))return;var props=first.properties;var safe=true;_.each(props,function(prop){if(t.isIdentifier(prop.key,{name:"displayName"})){return safe=false}});if(safe){props.unshift(t.property("init",t.identifier("displayName"),t.literal(id)))}};exports.AssignmentExpression=exports.Property=exports.VariableDeclarator=function(node){var left,right;if(t.isAssignmentExpression(node)){left=node.left;right=node.right}else if(t.isProperty(node)){left=node.key;right=node.value}else if(t.isVariableDeclarator(node)){left=node.id;right=node.init}if(t.isMemberExpression(left)){left=left.property}if(t.isIdentifier(left)){addDisplayName(left.name,right)}}},{"../../types":74,esutils:107,lodash:108}],69:[function(require,module,exports){var t=require("../../types");module.exports=function(ast){var body=ast.program.body;var first=body[0];var noStrict=!first||!t.isExpressionStatement(first)||!t.isLiteral(first.expression)||first.expression.value!=="use strict";if(noStrict){body.unshift(t.expressionStatement(t.literal("use strict")))}}},{"../../types":74}],70:[function(require,module,exports){module.exports=traverse;var Scope=require("./scope");var t=require("../types");var _=require("lodash");function traverse(parent,callbacks,opts){if(!parent)return;if(_.isArray(parent)){_.each(parent,function(node){traverse(node,callbacks,opts)});return}var keys=t.VISITOR_KEYS[parent.type];if(!keys)return;opts=opts||{};if(_.isArray(opts))opts={blacklist:opts};var blacklistTypes=opts.blacklist||[];if(_.isFunction(callbacks))callbacks={enter:callbacks};for(var i in keys){var key=keys[i];var nodes=parent[key];if(!nodes)continue;var updated=false;var handle=function(obj,key){var node=obj[key];if(!node)return;if(blacklistTypes.indexOf(node.type)>-1)return;var maybeReplace=function(result){if(result===false)return;if(result!=null){updated=true;node=obj[key]=result;if(_.isArray(result)&&_.contains(t.STATEMENT_OR_BLOCK_KEYS,key)&&!t.isBlockStatement(obj)){t.ensureBlock(obj,key)}}};var opts2={scope:opts.scope,blacklist:opts.blacklist};if(t.isScope(node))opts2.scope=new Scope(node,opts.scope);if(callbacks.enter){var result=callbacks.enter(node,parent,opts2.scope);maybeReplace(result);if(result===false)return}traverse(node,callbacks,opts2);if(callbacks.exit){maybeReplace(callbacks.exit(node,parent,opts2.scope))}};if(_.isArray(nodes)){for(i in nodes){handle(nodes,i)}if(updated)parent[key]=_.flatten(parent[key])}else{handle(parent,key)}}}traverse.removeProperties=function(tree){var clear=function(node){delete node._scopeReferences;delete node._declarations;delete node.extendedRange;delete node._parent;delete node._scope;delete node.tokens;delete node.range;delete node.start;delete node.end;delete node.loc;delete node.raw;clearComments(node.trailingComments);clearComments(node.leadingComments)};var clearComments=function(comments){_.each(comments,clear)};clear(tree);traverse(tree,clear);return tree};traverse.hasType=function(tree,type,blacklistTypes){blacklistTypes=[].concat(blacklistTypes||[]);var has=false;if(_.contains(blacklistTypes,tree.type))return false;if(tree.type===type)return true;traverse(tree,function(node){if(node.type===type){has=true;return false}},{blacklist:blacklistTypes});return has}},{"../types":74,"./scope":71,lodash:108}],71:[function(require,module,exports){module.exports=Scope;var traverse=require("./index");var t=require("../types");var _=require("lodash");var FOR_KEYS=["left","init"];function Scope(block,parent){this.parent=parent;this.block=block;this.references=this.getReferences()}Scope.add=function(node,references){if(!node)return;_.merge(references,t.getIds(node,true))};Scope.prototype.getReferences=function(){var block=this.block;if(block._scopeReferences)return block._scopeReferences;var references=block._scopeReferences={};var add=function(node){Scope.add(node,references)};if(t.isFor(block)){_.each(FOR_KEYS,function(key){var node=block[key];if(t.isLet(node))add(node)});block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){_.each(block.body,function(node){if(t.isLet(node))add(node)})}if(t.isCatchClause(block)){add(block.param)}if(t.isProgram(block)||t.isFunction(block)){traverse(block,function(node,parent,scope){if(t.isFor(node)){_.each(FOR_KEYS,function(key){var declar=node[key];if(t.isVar(declar))add(declar)})}if(t.isFunction(node))return false;if(t.isIdentifier(node)&&t.isReferenced(node,parent)&&!scope.has(node.name)){add(node)}if(t.isDeclaration(node)&&!t.isLet(node)){add(node)}},{scope:this})}if(t.isFunction(block)){add(block.rest);_.each(block.params,function(param){add(param)})}return references};Scope.prototype.push=function(opts){var block=this.block;if(t.isFor(block)||t.isCatchClause(block)||t.isFunction(block)){t.ensureBlock(block);block=block.body}if(t.isBlockStatement(block)||t.isProgram(block)){block._declarations=block._declarations||{};block._declarations[opts.key]={kind:opts.kind,id:opts.id,init:opts.init}}else{throw new TypeError("cannot add a declaration here in node type "+block.type)}};Scope.prototype.add=function(node){Scope.add(node,this.references)};Scope.prototype.get=function(id){return id&&(this.getOwn(id)||this.parentGet(id)) };Scope.prototype.getOwn=function(id){return _.has(this.references,id)&&this.references[id]};Scope.prototype.parentGet=function(id){return this.parent&&this.parent.get(id)};Scope.prototype.has=function(id){return id&&(this.hasOwn(id)||this.parentHas(id))};Scope.prototype.hasOwn=function(id){return!!this.getOwn(id)};Scope.prototype.parentHas=function(id){return this.parent&&this.parent.has(id)}},{"../types":74,"./index":70,lodash:108}],72:[function(require,module,exports){module.exports={ExpressionStatement:["Statement"],BreakStatement:["Statement"],ContinueStatement:["Statement"],DebuggerStatement:["Statement"],DoWhileStatement:["Statement"],IfStatement:["Statement"],ReturnStatement:["Statement"],SwitchStatement:["Statement"],ThrowStatement:["Statement"],TryStatement:["Statement"],WhileStatement:["Statement"],WithStatement:["Statement"],EmptyStatement:["Statement"],LabeledStatement:["Statement"],VariableDeclaration:["Statement","Declaration"],ExportDeclaration:["Statement","Declaration"],ImportDeclaration:["Statement","Declaration"],ArrowFunctionExpression:["Scope","Function"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary"],BinaryExpression:["Binary"],UnaryExpression:["UnaryLike"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class"],ForOfStatement:["Statement","For","Scope"],ForInStatement:["Statement","For","Scope"],ForStatement:["Statement","For","Scope"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable"]}},{}],73:[function(require,module,exports){module.exports={ArrayExpression:["elements"],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"],Identifier:["name"],IfStatement:["test","consequent","alternate"],Literal:["value"],LogicalExpression:["operator","left","right"],MemberExpression:["object","property","computed"],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ParenthesizedExpression:["expression"],Program:["body"],Property:["kind","key","value","computed"],ReturnStatement:["argument"],SequenceExpression:["expressions"],ThrowExpression:["argument"],UnaryExpression:["operator","argument","prefix"],VariableDeclaration:["kind","declarations"],VariableDeclarator:["id","init"],YieldExpression:["argument","delegate"]}},{}],74:[function(require,module,exports){var esutils=require("esutils");var _=require("lodash");var t=exports;var addAssert=function(type,is){t["assert"+type]=function(node,opts){opts=opts||{};if(!is(node,opts)){throw new Error("Expected type "+JSON.stringify(type)+" with option "+JSON.stringify(opts))}}};t.STATEMENT_OR_BLOCK_KEYS=["consequent","body"];t.VISITOR_KEYS=require("./visitor-keys");_.each(t.VISITOR_KEYS,function(keys,type){var is=t["is"+type]=function(node,opts){return node&&node.type===type&&t.shallowEqual(node,opts)};addAssert(type,is)});t.BUILDER_KEYS=_.defaults(require("./builder-keys"),t.VISITOR_KEYS);_.each(t.BUILDER_KEYS,function(keys,type){t[type[0].toLowerCase()+type.slice(1)]=function(){var args=arguments;var node={type:type};_.each(keys,function(key,i){node[key]=args[i]});return node}});t.ALIAS_KEYS=require("./alias-keys");var _aliases={};_.each(t.ALIAS_KEYS,function(aliases,type){_.each(aliases,function(alias){var types=_aliases[alias]=_aliases[alias]||[];types.push(type)})});_.each(_aliases,function(types,type){t[type.toUpperCase()+"_TYPES"]=types;var is=t["is"+type]=function(node,opts){return node&&_.contains(types,node.type)&&t.shallowEqual(node,opts)};addAssert(type,is)});t.isExpression=function(node){return!t.isStatement(node)};addAssert("Expression",t.isExpression);t.toSequenceExpression=function(nodes,scope){var exprs=[];_.each(nodes,function(node){if(t.isExpression(node)){exprs.push(node)}if(t.isExpressionStatement(node)){exprs.push(node.expression)}else if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){scope.push({kind:node.kind,key:declar.id.name,id:declar.id});exprs.push(t.assignmentExpression("=",declar.id,declar.init))})}});return t.sequenceExpression(exprs)};t.shallowEqual=function(actual,expected){var same=true;if(expected){_.each(expected,function(val,key){if(actual[key]!==val){return same=false}})}return same};t.isDynamic=function(node){if(t.isParenthesizedExpression(node)||t.isExpressionStatement(node)){return t.isDynamic(node.expression)}else if(t.isIdentifier(node)||t.isLiteral(node)||t.isThisExpression(node)){return false}else if(t.isMemberExpression(node)){return t.isDynamic(node.object)||t.isDynamic(node.property)}else{return true}};t.isReferenced=function(node,parent){if(t.isProperty(parent)&&parent.key===node)return false;if(t.isVariableDeclarator(parent)&&parent.id===node)return false;var isMemberExpression=t.isMemberExpression(parent);var isComputedProperty=isMemberExpression&&parent.property===node&&parent.computed;var isObject=isMemberExpression&&parent.object===node;if(!isMemberExpression||isComputedProperty||isObject)return true;return false};t.toIdentifier=function(name){if(t.isIdentifier(name))return name.name;name=name.replace(/[^a-zA-Z0-9]/g,"-");name=name.replace(/^[-0-9]+/,"");name=name.replace(/[-_\s]+(.)?/g,function(match,c){return c?c.toUpperCase():""});return name};t.isValidIdentifier=function(name){return _.isString(name)&&esutils.keyword.isIdentifierName(name)&&!esutils.keyword.isKeywordES6(name,true)};t.ensureBlock=function(node,key){key=key||"body";node[key]=t.toBlock(node[key],node)};t.toStatement=function(node,ignore){if(t.isStatement(node)){return node}var mustHaveId=false;var newType;if(t.isClass(node)){mustHaveId=true;newType="ClassDeclaration"}else if(t.isFunction(node)){mustHaveId=true;newType="FunctionDeclaration"}if(mustHaveId&&!node.id){newType=false}if(!newType){if(ignore){return false}else{throw new Error("cannot turn "+node.type+" to a statement")}}node.type=newType;return node};t.toBlock=function(node,parent){if(t.isBlockStatement(node)){return node}if(!_.isArray(node)){if(!t.isStatement(node)){if(t.isFunction(parent)){node=t.returnStatement(node)}else{node=t.expressionStatement(node)}}node=[node]}return t.blockStatement(node)};t.getIds=function(node,map,ignoreTypes){ignoreTypes=ignoreTypes||[];var search=[].concat(node);var ids={};while(search.length){var id=search.shift();if(!id)continue;if(_.contains(ignoreTypes,id.type))continue;var nodeKey=t.getIds.nodes[id.type];var arrKey=t.getIds.arrays[id.type];if(t.isIdentifier(id)){ids[id.name]=id}else if(nodeKey){if(id[nodeKey])search.push(id[nodeKey])}else if(arrKey){search=search.concat(id[arrKey]||[])}}if(!map)ids=_.keys(ids);return ids};t.getIds.nodes={AssignmentExpression:"left",ImportSpecifier:"id",ExportSpecifier:"id",VariableDeclarator:"id",FunctionDeclaration:"id",ClassDeclaration:"id",ParenthesizedExpression:"expression",MemeberExpression:"object",SpreadElement:"argument",Property:"value"};t.getIds.arrays={ExportDeclaration:"specifiers",ImportDeclaration:"specifiers",VariableDeclaration:"declarations",ArrayPattern:"elements",ObjectPattern:"properties"};t.isLet=function(node){return t.isVariableDeclaration(node)&&(node.kind!=="var"||node._let)};t.isVar=function(node){return t.isVariableDeclaration(node,{kind:"var"})&&!node._let};t.removeComments=function(child){delete child.leadingComments;delete child.trailingComments;return child};t.inheritsComments=function(child,parent){child.leadingComments=_.compact([].concat(child.leadingComments,parent.leadingComments));child.trailingComments=_.compact([].concat(child.trailingComments,parent.trailingComments));return child};t.removeComments=function(node){delete node.leadingComments;delete node.trailingComments};t.inherits=function(child,parent){child.loc=parent.loc;child.end=parent.end;child.range=parent.range;child.start=parent.start;t.inheritsComments(child,parent);return child};t.getSpecifierName=function(specifier){return specifier.name||specifier.id}},{"./alias-keys":72,"./builder-keys":73,"./visitor-keys":75,esutils:107,lodash:108}],75:[function(require,module,exports){module.exports={ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],AssignmentExpression:["left","right"],AwaitExpression:["argument"],BinaryExpression:["left","right"],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"],ParenthesizedExpression:["expression"],BindFunctionExpression:["callee","arguments"],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"],XJSAttribute:["name","value"],XJSClosingElement:["name"],XJSElement:["openingElement","closingElement","children"],XJSEmptyExpression:[],XJSExpressionContainer:["expression"],XJSIdentifier:[],XJSMemberExpression:["object","property"],XJSNamespacedName:["namespace","name"],XJSOpeningElement:["name","attributes"],XJSSpreadAttribute:["argument"],YieldExpression:["argument"]}},{}],76:[function(require,module,exports){(function(Buffer,__dirname){require("./patch");var estraverse=require("estraverse");var traverse=require("./traverse");var acorn=require("acorn-6to5");var path=require("path");var util=require("util");var fs=require("fs");var t=require("./types");var _=require("lodash");exports.inherits=util.inherits;exports.canCompile=function(filename,altExts){var exts=altExts||[".js",".jsx",".es6"];var ext=path.extname(filename);return _.contains(exts,ext)};exports.isInteger=function(i){return _.isNumber(i)&&i%1===0};exports.resolve=function(loc){try{return require.resolve(loc)}catch(err){return null}};exports.trimRight=function(str){return str.replace(/[\n\s]+$/g,"")};exports.list=function(val){return val?val.split(","):[]};exports.regexify=function(val){if(!val)return new RegExp(/.^/);if(_.isArray(val))val=val.join("|");if(_.isString(val))return new RegExp(val);if(_.isRegExp(val))return val;throw new TypeError("illegal type for regexify")};exports.arrayify=function(val){if(!val)return[];if(_.isString(val))return exports.list(val);if(_.isArray(val))return val;throw new TypeError("illegal type for arrayify")};exports.getUid=function(parent,file){var node;if(t.isAssignmentExpression(parent)){node=parent.left}else if(t.isVariableDeclarator(parent)){node=parent.id}var id="ref";if(t.isIdentifier(node))id=node.name;return file.generateUidIdentifier(id)};exports.isAbsolute=function(loc){if(!loc)return false;if(loc[0]==="/")return true;if(loc[1]===":"&&loc[2]==="\\")return true;return false};exports.sourceMapToComment=function(map){var json=JSON.stringify(map);var base64=new Buffer(json).toString("base64");return"//# sourceMappingURL=data:application/json;base64,"+base64};exports.pushMutatorMap=function(mutatorMap,key,kind,method){var alias;if(t.isIdentifier(key)){alias=key.name;if(method.computed)alias="computed:"+alias}else if(t.isLiteral(key)){alias=String(key.value)}else{alias=JSON.stringify(traverse.removeProperties(_.cloneDeep(key)))}var map;if(_.has(mutatorMap,alias)){map=mutatorMap[alias]}else{map={}}mutatorMap[alias]=map;map._key=key;if(method.computed){map._computed=true}map[kind]=method};exports.buildDefineProperties=function(mutatorMap){var objExpr=t.objectExpression([]);_.each(mutatorMap,function(map){var mapNode=t.objectExpression([]);var propNode=t.property("init",map._key,mapNode,map._computed);_.each(map,function(node,key){if(key[0]==="_")return;node=_.clone(node);var inheritNode=node;if(t.isMethodDefinition(node))node=node.value;var prop=t.property("init",t.identifier(key),node);t.inheritsComments(prop,inheritNode);t.removeComments(inheritNode);mapNode.properties.push(prop)});objExpr.properties.push(propNode)});return objExpr};exports.template=function(name,nodes,keepExpression){var template=exports.templates[name];if(!template)throw new ReferenceError("unknown template "+name);if(nodes===true){keepExpression=true;nodes=null}template=_.cloneDeep(template);if(!_.isEmpty(nodes)){traverse(template,function(node){if(t.isIdentifier(node)&&_.has(nodes,node.name)){var newNode=nodes[node.name];if(_.isString(newNode)){node.name=newNode}else{return newNode}}})}var node=template.body[0];if(!keepExpression&&t.isExpressionStatement(node)){node=node.expression;if(t.isParenthesizedExpression(node))node=node.expression}return node};exports.codeFrame=function(lines,lineNumber,colNumber){colNumber=Math.max(colNumber,0);lines=lines.split("\n");var start=Math.max(lineNumber-3,0);var end=Math.min(lines.length,lineNumber+3);var width=(end+"").length;if(!lineNumber&&!colNumber){start=0;end=lines.length}return"\n"+lines.slice(start,end).map(function(line,i){var curr=i+start+1;var gutter=curr===lineNumber?"> ":" ";var sep=curr+exports.repeat(width+1);gutter+=sep+"| ";var str=gutter+line;if(colNumber&&curr===lineNumber){str+="\n";str+=exports.repeat(gutter.length-2);str+="|"+exports.repeat(colNumber)+"^"}return str}).join("\n")};exports.repeat=function(width,cha){cha=cha||" ";return new Array(width+1).join(cha)};exports.parse=function(opts,code,callback){try{var comments=[];var tokens=[];var ast=acorn.parse(code,{allowReturnOutsideFunction:true,preserveParens:true,ecmaVersion:opts.experimental?7:6,playground:opts.playground,strictMode:true,onComment:comments,locations:true,onToken:tokens,ranges:true});estraverse.attachComments(ast,comments,tokens);ast=t.file(ast,comments,tokens);traverse(ast,function(node,parent){node._parent=parent});if(callback){return callback(ast)}else{return ast}}catch(err){if(!err._6to5){err._6to5=true;var message=opts.filename+": "+err.message;var loc=err.loc;if(loc){var frame=exports.codeFrame(code,loc.line,loc.column);message+=frame}if(err.stack)err.stack=err.stack.replace(err.message,message);err.message=message}throw err}};exports.parseTemplate=function(loc,code){var ast=exports.parse({filename:loc},code).program;return traverse.removeProperties(ast)};var loadTemplates=function(){var templates={};var templatesLoc=__dirname+"/templates";if(!fs.existsSync(templatesLoc)){throw new Error("no templates directory - this is most likely the "+"result of a broken `npm publish`. Please report to "+"https://githut.com/6to5/6to5/issues")}_.each(fs.readdirSync(templatesLoc),function(name){if(name[0]===".")return;var key=path.basename(name,path.extname(name));var loc=templatesLoc+"/"+name;var code=fs.readFileSync(loc,"utf8");templates[key]=exports.parseTemplate(loc,code)});return templates};try{exports.templates=require("../../templates.json")}catch(err){if(err.code!=="MODULE_NOT_FOUND")throw err;exports.templates=loadTemplates()}}).call(this,require("buffer").Buffer,"/lib/6to5")},{"../../templates.json":126,"./patch":22,"./traverse":70,"./types":74,"acorn-6to5":77,buffer:94,estraverse:103,fs:92,lodash:108,path:99,util:102}],77:[function(require,module,exports){(function(root,mod){if(typeof exports=="object"&&typeof module=="object")return mod(exports);if(typeof define=="function"&&define.amd)return define(["exports"],mod);mod(root.acorn||(root.acorn={}))})(this,function(exports){"use strict";exports.version="0.9.1";var options,input,inputLen,sourceFile;exports.parse=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();var startPos=options.locations?[tokPos,new Position]:tokPos;initParserState();return parseTopLevel(options.program||startNodeAt(startPos))};var defaultOptions=exports.defaultOptions={playground:false,ecmaVersion:5,strictSemicolons:false,allowTrailingCommas:true,forbidReserved:false,allowReturnOutsideFunction:false,locations:false,onToken:null,onComment:null,ranges:false,program:null,sourceFile:null,directSourceFile:null,preserveParens:false};exports.parseExpressionAt=function(inpt,pos,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState(pos);initParserState();return parseExpression()};var isArray=function(obj){return Object.prototype.toString.call(obj)==="[object Array]"};function setOptions(opts){options={};for(var opt in defaultOptions)options[opt]=opts&&has(opts,opt)?opts[opt]:defaultOptions[opt];sourceFile=options.sourceFile||null;if(isArray(options.onToken)){var tokens=options.onToken;options.onToken=function(token){tokens.push(token)}}if(isArray(options.onComment)){var comments=options.onComment;options.onComment=function(block,text,start,end,startLoc,endLoc){var comment={type:block?"Block":"Line",value:text,start:start,end:end};if(options.locations){comment.loc=new SourceLocation;comment.loc.start=startLoc;comment.loc.end=endLoc}if(options.ranges)comment.range=[start,end];comments.push(comment)}}if(options.strictMode){strict=true}if(options.ecmaVersion>=7){isKeyword=isEcma7Keyword}else if(options.ecmaVersion===6){isKeyword=isEcma6Keyword}else{isKeyword=isEcma5AndLessKeyword}}var getLineInfo=exports.getLineInfo=function(input,offset){for(var line=1,cur=0;;){lineBreak.lastIndex=cur;var match=lineBreak.exec(input);if(match&&match.index<offset){++line;cur=match.index+match[0].length}else break}return{line:line,column:offset-cur}};function Token(){this.type=tokType;this.value=tokVal;this.start=tokStart;this.end=tokEnd;if(options.locations){this.loc=new SourceLocation;this.loc.end=tokEndLoc;this.startLoc=tokStartLoc;this.endLoc=tokEndLoc}if(options.ranges)this.range=[tokStart,tokEnd]}exports.Token=Token;exports.tokenize=function(inpt,opts){input=String(inpt);inputLen=input.length;setOptions(opts);initTokenState();skipSpace();function getToken(forceRegexp){lastEnd=tokEnd;readToken(forceRegexp);return new Token}getToken.jumpTo=function(pos,reAllowed){tokPos=pos;if(options.locations){tokCurLine=1;tokLineStart=lineBreak.lastIndex=0;var match;while((match=lineBreak.exec(input))&&match.index<pos){++tokCurLine;tokLineStart=match.index+match[0].length}}tokRegexpAllowed=reAllowed;skipSpace()};getToken.noRegexp=function(){tokRegexpAllowed=false};getToken.options=options;return getToken};var tokPos;var tokStart,tokEnd;var tokStartLoc,tokEndLoc;var tokType,tokVal;var tokRegexpAllowed;var tokCurLine,tokLineStart;var lastStart,lastEnd,lastEndLoc;var inFunction,inGenerator,inAsync,labels,strict,inXJSChild,inXJSTag,inXJSChildExpression;var metParenL;var inTemplate;function initParserState(){lastStart=lastEnd=tokPos;if(options.locations)lastEndLoc=new Position;inFunction=inGenerator=inAsync=strict=false;labels=[];skipSpace();readToken()}function raise(pos,message){var loc=getLineInfo(input,pos);message+=" ("+loc.line+":"+loc.column+")";var err=new SyntaxError(message);err.pos=pos;err.loc=loc;err.raisedAt=tokPos;throw err}var empty=[];var _num={type:"num"},_regexp={type:"regexp"},_string={type:"string"};var _name={type:"name"},_eof={type:"eof"};var _xjsName={type:"xjsName"},_xjsText={type:"xjsText"};var _break={keyword:"break"},_case={keyword:"case",beforeExpr:true},_catch={keyword:"catch"};var _continue={keyword:"continue"},_debugger={keyword:"debugger"},_default={keyword:"default"};var _do={keyword:"do",isLoop:true},_else={keyword:"else",beforeExpr:true};var _finally={keyword:"finally"},_for={keyword:"for",isLoop:true},_function={keyword:"function"};var _if={keyword:"if"},_return={keyword:"return",beforeExpr:true},_switch={keyword:"switch"};var _throw={keyword:"throw",beforeExpr:true},_try={keyword:"try"},_var={keyword:"var"};var _let={keyword:"let"},_const={keyword:"const"};var _while={keyword:"while",isLoop:true},_with={keyword:"with"},_new={keyword:"new",beforeExpr:true};var _this={keyword:"this"};var _class={keyword:"class"},_extends={keyword:"extends",beforeExpr:true};var _export={keyword:"export"},_import={keyword:"import"};var _yield={keyword:"yield",beforeExpr:true};var _async={keyword:"async"},_await={keyword:"await",beforeExpr:true};var _null={keyword:"null",atomValue:null},_true={keyword:"true",atomValue:true};var _false={keyword:"false",atomValue:false};var _in={keyword:"in",binop:7,beforeExpr:true};var keywordTypes={"break":_break,"case":_case,"catch":_catch,"continue":_continue,"debugger":_debugger,"default":_default,"do":_do,"else":_else,"finally":_finally,"for":_for,"function":_function,"if":_if,"return":_return,"switch":_switch,"throw":_throw,"try":_try,"var":_var,let:_let,"const":_const,"while":_while,"with":_with,"null":_null,"true":_true,"false":_false,"new":_new,"in":_in,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:true},"this":_this,"typeof":{keyword:"typeof",prefix:true,beforeExpr:true},"void":{keyword:"void",prefix:true,beforeExpr:true},"delete":{keyword:"delete",prefix:true,beforeExpr:true},"class":_class,"extends":_extends,"export":_export,"import":_import,"yield":_yield,await:_await,async:_async};var _bracketL={type:"[",beforeExpr:true},_bracketR={type:"]"},_braceL={type:"{",beforeExpr:true};var _braceR={type:"}"},_parenL={type:"(",beforeExpr:true},_parenR={type:")"};var _comma={type:",",beforeExpr:true},_semi={type:";",beforeExpr:true};var _colon={type:":",beforeExpr:true},_dot={type:"."},_question={type:"?",beforeExpr:true};var _arrow={type:"=>",beforeExpr:true},_bquote={type:"`"},_dollarBraceL={type:"${",beforeExpr:true};var _ltSlash={type:"</"};var _ellipsis={type:"...",prefix:true,beforeExpr:true};var _doubleColon={type:"::",beforeExpr:true};var _slash={binop:10,beforeExpr:true},_eq={isAssign:true,beforeExpr:true};var _assign={isAssign:true,beforeExpr:true};var _incDec={postfix:true,prefix:true,isUpdate:true},_prefix={prefix:true,beforeExpr:true};var _logicalOR={binop:1,beforeExpr:true};var _logicalAND={binop:2,beforeExpr:true};var _bitwiseOR={binop:3,beforeExpr:true};var _bitwiseXOR={binop:4,beforeExpr:true};var _bitwiseAND={binop:5,beforeExpr:true};var _equality={binop:6,beforeExpr:true};var _relational={binop:7,beforeExpr:true};var _bitShift={binop:8,beforeExpr:true};var _plusMin={binop:9,prefix:true,beforeExpr:true};var _modulo={binop:10,beforeExpr:true};var _star={binop:10,beforeExpr:true};var _exponent={binop:10,beforeExpr:true};var _lt={binop:7,beforeExpr:true},_gt={binop:7,beforeExpr:true};exports.tokTypes={bracketL:_bracketL,bracketR:_bracketR,braceL:_braceL,braceR:_braceR,parenL:_parenL,parenR:_parenR,comma:_comma,semi:_semi,colon:_colon,dot:_dot,ellipsis:_ellipsis,question:_question,slash:_slash,eq:_eq,name:_name,eof:_eof,num:_num,regexp:_regexp,string:_string,arrow:_arrow,bquote:_bquote,dollarBraceL:_dollarBraceL,star:_star,assign:_assign,xjsName:_xjsName,xjsText:_xjsText,doubleColon:_doubleColon,exponent:_exponent};for(var kw in keywordTypes)exports.tokTypes["_"+kw]=keywordTypes[kw];function makePredicate(words){words=words.split(" ");var f="",cats=[];out:for(var i=0;i<words.length;++i){for(var j=0;j<cats.length;++j)if(cats[j][0].length==words[i].length){cats[j].push(words[i]);continue out}cats.push([words[i]])}function compareTo(arr){if(arr.length==1)return f+="return str === "+JSON.stringify(arr[0])+";";f+="switch(str){";for(var i=0;i<arr.length;++i)f+="case "+JSON.stringify(arr[i])+":";f+="return true}return false;"}if(cats.length>3){cats.sort(function(a,b){return b.length-a.length});f+="switch(str.length){";for(var i=0;i<cats.length;++i){var cat=cats[i];f+="case "+cat[0].length+":";compareTo(cat)}f+="}"}else{compareTo(words)}return new Function("str",f)}var isReservedWord3=makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");var isReservedWord5=makePredicate("class enum extends super const export import");var isStrictReservedWord=makePredicate("implements interface let package private protected public static yield");var isStrictBadIdWord=makePredicate("eval arguments");var ecma5AndLessKeywords="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 isEcma5AndLessKeyword=makePredicate(ecma5AndLessKeywords);var ecma6AndLessKeywords=ecma5AndLessKeywords+" let const class extends export import yield";var isEcma6Keyword=makePredicate(ecma6AndLessKeywords);var isEcma7Keyword=makePredicate(ecma6AndLessKeywords+" async await");var isKeyword=isEcma5AndLessKeyword;var nonASCIIwhitespace=/[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;var nonASCIIidentifierStartChars="ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԯԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠ-ࢲऄ-हऽॐक़-ॡॱ-ঀঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤞᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚝꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꧠ-ꧤꧦ-ꧯꧺ-ꧾꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꩾ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ";var nonASCIIidentifierChars="̀-ͯ҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-٩ٰۖ-ۜ۟-۪ۤۧۨ-ۭ۰-۹ܑܰ-݊ަ-ް߀-߉߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣤ-ःऺ-़ा-ॏ॑-ॗॢॣ०-९ঁ-ঃ়া-ৄেৈো-্ৗৢৣ০-৯ਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑ੦-ੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣ૦-૯ଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣ୦-୯ஂா-ூெ-ைொ-்ௗ௦-௯ఀ-ఃా-ౄె-ైొ-్ౕౖౢౣ౦-౯ಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣ೦-೯ഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣ൦-൯ංඃ්ා-ුූෘ-ෟ෦-෯ෲෳัิ-ฺ็-๎๐-๙ັິ-ູົຼ່-ໍ໐-໙༘༙༠-༩༹༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှ၀-၉ၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝០-៩᠋-᠍᠐-᠙ᢩᤠ-ᤫᤰ-᤻᥆-᥏ᦰ-ᧀᧈᧉ᧐-᧙ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼-᪉᪐-᪙᪰-᪽ᬀ-ᬄ᬴-᭄᭐-᭙᭫-᭳ᮀ-ᮂᮡ-ᮭ᮰-᮹᯦-᯳ᰤ-᰷᱀-᱉᱐-᱙᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷼-᷿‌‍‿⁀⁔⃐-⃥⃜⃡-⃰⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꘠-꘩꙯ꙴ-꙽ꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-꣄꣐-꣙꣠-꣱꤀-꤉ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀꧐-꧙ꧥ꧰-꧹ꨩ-ꨶꩃꩌꩍ꩐-꩙ꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭꯰-꯹ﬞ︀-️︠-︭︳︴﹍-﹏0-9_";var nonASCIIidentifierStart=new RegExp("["+nonASCIIidentifierStartChars+"]");var nonASCIIidentifier=new RegExp("["+nonASCIIidentifierStartChars+nonASCIIidentifierChars+"]");var newline=/[\n\r\u2028\u2029]/;var lineBreak=/\r\n|[\n\r\u2028\u2029]/g;var isIdentifierStart=exports.isIdentifierStart=function(code){if(code<65)return code===36;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifierStart.test(String.fromCharCode(code))};var isIdentifierChar=exports.isIdentifierChar=function(code){if(code<48)return code===36;if(code<58)return true;if(code<65)return false;if(code<91)return true;if(code<97)return code===95;if(code<123)return true;return code>=170&&nonASCIIidentifier.test(String.fromCharCode(code))};function Position(){this.line=tokCurLine;this.column=tokPos-tokLineStart}function initTokenState(pos){if(pos){tokPos=pos;tokLineStart=Math.max(0,input.lastIndexOf("\n",pos));tokCurLine=input.slice(0,tokLineStart).split(newline).length}else{tokCurLine=1;tokPos=tokLineStart=0}tokRegexpAllowed=true;metParenL=0;inTemplate=inXJSChild=inXJSTag=false}function finishToken(type,val,shouldSkipSpace){tokEnd=tokPos;if(options.locations)tokEndLoc=new Position;tokType=type;if(shouldSkipSpace!==false)skipSpace();tokVal=val;tokRegexpAllowed=type.beforeExpr;if(options.onToken){options.onToken(new Token)}}function skipBlockComment(){var startLoc=options.onComment&&options.locations&&new Position;var start=tokPos,end=input.indexOf("*/",tokPos+=2);if(end===-1)raise(tokPos-2,"Unterminated comment");tokPos=end+2;if(options.locations){lineBreak.lastIndex=start;var match;while((match=lineBreak.exec(input))&&match.index<tokPos){++tokCurLine;tokLineStart=match.index+match[0].length}}if(options.onComment)options.onComment(true,input.slice(start+2,end),start,tokPos,startLoc,options.locations&&new Position)}function skipLineComment(startSkip){var start=tokPos;var startLoc=options.onComment&&options.locations&&new Position;var ch=input.charCodeAt(tokPos+=startSkip);while(tokPos<inputLen&&ch!==10&&ch!==13&&ch!==8232&&ch!==8233){++tokPos;ch=input.charCodeAt(tokPos)}if(options.onComment)options.onComment(false,input.slice(start+startSkip,tokPos),start,tokPos,startLoc,options.locations&&new Position)}function skipSpace(){while(tokPos<inputLen){var ch=input.charCodeAt(tokPos);if(ch===32){++tokPos}else if(ch===13){++tokPos;var next=input.charCodeAt(tokPos);if(next===10){++tokPos}if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch===10||ch===8232||ch===8233){++tokPos;if(options.locations){++tokCurLine;tokLineStart=tokPos}}else if(ch>8&&ch<14){++tokPos}else if(ch===47){var next=input.charCodeAt(tokPos+1);if(next===42){skipBlockComment()}else if(next===47){skipLineComment(2)}else break}else if(ch===160){++tokPos}else if(ch>=5760&&nonASCIIwhitespace.test(String.fromCharCode(ch))){++tokPos}else{break}}}function readToken_dot(){var next=input.charCodeAt(tokPos+1);if(next>=48&&next<=57)return readNumber(true);var next2=input.charCodeAt(tokPos+2);if(options.ecmaVersion>=6&&next===46&&next2===46){tokPos+=3;return finishToken(_ellipsis)}else{++tokPos;return finishToken(_dot)}}function readToken_slash(){var next=input.charCodeAt(tokPos+1);if(tokRegexpAllowed){++tokPos;return readRegexp()}if(next===61)return finishOp(_assign,2);return finishOp(_slash,1)}function readToken_modulo(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_modulo,1)}function readToken_mult(){var type=_star;var width=1;var next=input.charCodeAt(tokPos+1);if(options.ecmaVersion>=7&&next===42){width++;next=input.charCodeAt(tokPos+2);type=_exponent}if(next===61){width++;type=_assign}return finishOp(type,width)}function readToken_pipe_amp(code){var next=input.charCodeAt(tokPos+1);if(next===code)return finishOp(code===124?_logicalOR:_logicalAND,2);if(next===61)return finishOp(_assign,2);return finishOp(code===124?_bitwiseOR:_bitwiseAND,1)}function readToken_caret(){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_assign,2);return finishOp(_bitwiseXOR,1)}function readToken_plus_min(code){var next=input.charCodeAt(tokPos+1); if(next===code){if(next==45&&input.charCodeAt(tokPos+2)==62&&newline.test(input.slice(lastEnd,tokPos))){skipLineComment(3);skipSpace();return readToken()}return finishOp(_incDec,2)}if(next===61)return finishOp(_assign,2);return finishOp(_plusMin,1)}function readToken_lt_gt(code){var next=input.charCodeAt(tokPos+1);var size=1;if(next===code){size=code===62&&input.charCodeAt(tokPos+2)===62?3:2;if(input.charCodeAt(tokPos+size)===61)return finishOp(_assign,size+1);return finishOp(_bitShift,size)}if(next==33&&code==60&&input.charCodeAt(tokPos+2)==45&&input.charCodeAt(tokPos+3)==45){skipLineComment(4);skipSpace();return readToken()}if(next===61){size=input.charCodeAt(tokPos+2)===61?3:2;return finishOp(_relational,size)}if(next===47){size=2;return finishOp(_ltSlash,size)}return code===60?finishOp(_lt,size):finishOp(_gt,size,!inXJSTag)}function readToken_eq_excl(code){var next=input.charCodeAt(tokPos+1);if(next===61)return finishOp(_equality,input.charCodeAt(tokPos+2)===61?3:2);if(code===61&&next===62&&options.ecmaVersion>=6){tokPos+=2;return finishToken(_arrow)}return finishOp(code===61?_eq:_prefix,1)}function getTemplateToken(code){if(tokType===_string){if(code===96){++tokPos;return finishToken(_bquote)}else if(code===36&&input.charCodeAt(tokPos+1)===123){tokPos+=2;return finishToken(_dollarBraceL)}}if(code===125){++tokPos;return finishToken(_braceR,undefined,false)}return readTmplString()}function getTokenFromCode(code){switch(code){case 46:return readToken_dot();case 40:++tokPos;return finishToken(_parenL);case 41:++tokPos;return finishToken(_parenR);case 59:++tokPos;return finishToken(_semi);case 44:++tokPos;return finishToken(_comma);case 91:++tokPos;return finishToken(_bracketL);case 93:++tokPos;return finishToken(_bracketR);case 123:++tokPos;return finishToken(_braceL);case 125:++tokPos;return finishToken(_braceR,undefined,!inXJSChild);case 63:++tokPos;return finishToken(_question);case 58:++tokPos;if(options.ecmaVersion>=7){var next=input.charCodeAt(tokPos);if(next===58){++tokPos;return finishToken(_doubleColon)}}return finishToken(_colon);case 96:if(options.ecmaVersion>=6){++tokPos;return finishToken(_bquote,undefined,false)}case 48:var next=input.charCodeAt(tokPos+1);if(next===120||next===88)return readRadixNumber(16);if(options.ecmaVersion>=6){if(next===111||next===79)return readRadixNumber(8);if(next===98||next===66)return readRadixNumber(2)}case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return readNumber(false);case 34:case 39:return inXJSTag?readXJSStringLiteral():readString(code);case 47:return readToken_slash();case 37:return readToken_modulo();case 42:return readToken_mult();case 124:case 38:return readToken_pipe_amp(code);case 94:return readToken_caret();case 43:case 45:return readToken_plus_min(code);case 60:case 62:return readToken_lt_gt(code);case 61:case 33:return readToken_eq_excl(code);case 126:return finishOp(_prefix,1)}return false}function readToken(forceRegexp){if(!forceRegexp)tokStart=tokPos;else tokPos=tokStart+1;if(options.locations)tokStartLoc=new Position;if(forceRegexp)return readRegexp();if(tokPos>=inputLen)return finishToken(_eof);var code=input.charCodeAt(tokPos);if(inXJSChild&&tokType!==_braceL&&code!==60&&code!==123&&code!==125){return readXJSText(["<","{"])}if(inTemplate)return getTemplateToken(code);if(isIdentifierStart(code)||code===92)return readWord();var tok=getTokenFromCode(code);if(tok===false){var ch=String.fromCharCode(code);if(ch==="\\"||nonASCIIidentifierStart.test(ch))return readWord();raise(tokPos,"Unexpected character '"+ch+"'")}return tok}function finishOp(type,size,shouldSkipSpace){var str=input.slice(tokPos,tokPos+size);tokPos+=size;finishToken(type,str,shouldSkipSpace)}var regexpUnicodeSupport=false;try{new RegExp("￿","u");regexpUnicodeSupport=true}catch(e){}function readRegexp(){var content="",escaped,inClass,start=tokPos;for(;;){if(tokPos>=inputLen)raise(start,"Unterminated regular expression");var ch=nextChar();if(newline.test(ch))raise(start,"Unterminated regular expression");if(!escaped){if(ch==="[")inClass=true;else if(ch==="]"&&inClass)inClass=false;else if(ch==="/"&&!inClass)break;escaped=ch==="\\"}else escaped=false;++tokPos}var content=input.slice(start,tokPos);++tokPos;var mods=readWord1();var tmp=content;if(mods){var validFlags=/^[gmsiy]*$/;if(options.ecmaVersion>=6)validFlags=/^[gmsiyu]*$/;if(!validFlags.test(mods))raise(start,"Invalid regular expression flag");if(mods.indexOf("u")>=0&&!regexpUnicodeSupport){tmp=tmp.replace(/\\u\{([0-9a-fA-F]{5,6})\}/g,"x").replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"x")}}try{new RegExp(tmp)}catch(e){if(e instanceof SyntaxError)raise(start,"Error parsing regular expression: "+e.message);raise(e)}try{var value=new RegExp(content,mods)}catch(err){value=null}return finishToken(_regexp,{pattern:content,flags:mods,value:value})}function readInt(radix,len){var start=tokPos,total=0;for(var i=0,e=len==null?Infinity:len;i<e;++i){var code=input.charCodeAt(tokPos),val;if(code>=97)val=code-97+10;else if(code>=65)val=code-65+10;else if(code>=48&&code<=57)val=code-48;else val=Infinity;if(val>=radix)break;++tokPos;total=total*radix+val}if(tokPos===start||len!=null&&tokPos-start!==len)return null;return total}function readRadixNumber(radix){tokPos+=2;var val=readInt(radix);if(val==null)raise(tokStart+2,"Expected number in radix "+radix);if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");return finishToken(_num,val)}function readNumber(startsWithDot){var start=tokPos,isFloat=false,octal=input.charCodeAt(tokPos)===48;if(!startsWithDot&&readInt(10)===null)raise(start,"Invalid number");if(input.charCodeAt(tokPos)===46){++tokPos;readInt(10);isFloat=true}var next=input.charCodeAt(tokPos);if(next===69||next===101){next=input.charCodeAt(++tokPos);if(next===43||next===45)++tokPos;if(readInt(10)===null)raise(start,"Invalid number");isFloat=true}if(isIdentifierStart(input.charCodeAt(tokPos)))raise(tokPos,"Identifier directly after number");var str=input.slice(start,tokPos),val;if(isFloat)val=parseFloat(str);else if(!octal||str.length===1)val=parseInt(str,10);else if(/[89]/.test(str)||strict)raise(start,"Invalid number");else val=parseInt(str,8);return finishToken(_num,val)}function readCodePoint(){var ch=input.charCodeAt(tokPos),code;if(ch===123){if(options.ecmaVersion<6)unexpected();++tokPos;code=readHexChar(input.indexOf("}",tokPos)-tokPos);++tokPos;if(code>1114111)unexpected()}else{code=readHexChar(4)}if(code<=65535){return String.fromCharCode(code)}var cu1=(code-65536>>10)+55296;var cu2=(code-65536&1023)+56320;return String.fromCharCode(cu1,cu2)}function readString(quote){++tokPos;var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===quote){++tokPos;return finishToken(_string,out)}if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){raise(tokStart,"Unterminated string constant")}out+=String.fromCharCode(ch)}}}function readTmplString(){var out="";for(;;){if(tokPos>=inputLen)raise(tokStart,"Unterminated string constant");var ch=input.charCodeAt(tokPos);if(ch===96||ch===36&&input.charCodeAt(tokPos+1)===123)return finishToken(_string,out);if(ch===92){out+=readEscapedChar()}else{++tokPos;if(newline.test(String.fromCharCode(ch))){if(ch===13&&input.charCodeAt(tokPos)===10){++tokPos;ch=10}if(options.locations){++tokCurLine;tokLineStart=tokPos}}out+=String.fromCharCode(ch)}}}function readEscapedChar(){var ch=input.charCodeAt(++tokPos);var octal=/^[0-7]+/.exec(input.slice(tokPos,tokPos+3));if(octal)octal=octal[0];while(octal&&parseInt(octal,8)>255)octal=octal.slice(0,-1);if(octal==="0")octal=null;++tokPos;if(octal){if(strict)raise(tokPos-2,"Octal literal in strict mode");tokPos+=octal.length-1;return String.fromCharCode(parseInt(octal,8))}else{switch(ch){case 110:return"\n";case 114:return"\r";case 120:return String.fromCharCode(readHexChar(2));case 117:return readCodePoint();case 116:return" ";case 98:return"\b";case 118:return" ";case 102:return"\f";case 48:return"\x00";case 13:if(input.charCodeAt(tokPos)===10)++tokPos;case 10:if(options.locations){tokLineStart=tokPos;++tokCurLine}return"";default:return String.fromCharCode(ch)}}}var XHTMLEntities={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 readXJSEntity(){var str="",count=0,entity;var ch=nextChar();if(ch!=="&")raise(tokPos,"Entity must start with an ampersand");tokPos++;while(tokPos<inputLen&&count++<10){ch=nextChar();tokPos++;if(ch===";"){break}str+=ch}if(str[0]==="#"&&str[1]==="x"){entity=String.fromCharCode(parseInt(str.substr(2),16))}else if(str[0]==="#"){entity=String.fromCharCode(parseInt(str.substr(1),10))}else{entity=XHTMLEntities[str]}return entity}function readXJSText(stopChars){var str="";while(tokPos<inputLen){var ch=nextChar();if(stopChars.indexOf(ch)!==-1){break}if(ch==="&"){str+=readXJSEntity()}else{++tokPos;if(ch==="\r"&&nextChar()==="\n"){str+=ch;++tokPos;ch="\n"}if(ch==="\n"&&options.locations){tokLineStart=tokPos;++tokCurLine}str+=ch}}return finishToken(_xjsText,str)}function readXJSStringLiteral(){var quote=input.charCodeAt(tokPos);if(quote!==34&&quote!==39){raise("String literal must starts with a quote")}++tokPos;readXJSText([String.fromCharCode(quote)]);if(quote!==input.charCodeAt(tokPos)){unexpected()}++tokPos;return finishToken(tokType,tokVal)}function readHexChar(len){var n=readInt(16,len);if(n===null)raise(tokStart,"Bad character escape sequence");return n}var containsEsc;function readWord1(){containsEsc=false;var word,first=true,start=tokPos;for(;;){var ch=input.charCodeAt(tokPos);if(isIdentifierChar(ch)||inXJSTag&&ch===45){if(containsEsc)word+=nextChar();++tokPos}else if(ch===92&&!inXJSTag){if(!containsEsc)word=input.slice(start,tokPos);containsEsc=true;if(input.charCodeAt(++tokPos)!=117)raise(tokPos,"Expecting Unicode escape sequence \\uXXXX");++tokPos;var esc=readHexChar(4);var escStr=String.fromCharCode(esc);if(!escStr)raise(tokPos-1,"Invalid Unicode escape");if(!(first?isIdentifierStart(esc):isIdentifierChar(esc)))raise(tokPos-4,"Invalid Unicode escape");word+=escStr}else{break}first=false}return containsEsc?word:input.slice(start,tokPos)}function readWord(){var word=readWord1();var type=inXJSTag?_xjsName:_name;if(!containsEsc&&isKeyword(word))type=keywordTypes[word];return finishToken(type,word)}function next(){lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;readToken()}function setStrict(strct){strict=strct;tokPos=tokStart;if(options.locations){while(tokPos<tokLineStart){tokLineStart=input.lastIndexOf("\n",tokLineStart-2)+1;--tokCurLine}}skipSpace();readToken()}function Node(){this.type=null;this.start=tokStart;this.end=null}exports.Node=Node;function SourceLocation(){this.start=tokStartLoc;this.end=null;if(sourceFile!==null)this.source=sourceFile}function startNode(){var node=new Node;if(options.locations)node.loc=new SourceLocation;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[tokStart,0];return node}function storeCurrentPos(){return options.locations?[tokStart,tokStartLoc]:tokStart}function startNodeAt(pos){var node=new Node,start=pos;if(options.locations){node.loc=new SourceLocation;node.loc.start=start[1];start=pos[0]}node.start=start;if(options.directSourceFile)node.sourceFile=options.directSourceFile;if(options.ranges)node.range=[start,0];return node}function finishNode(node,type){node.type=type;node.end=lastEnd;if(options.locations)node.loc.end=lastEndLoc;if(options.ranges)node.range[1]=lastEnd;return node}function isUseStrict(stmt){return options.ecmaVersion>=5&&stmt.type==="ExpressionStatement"&&stmt.expression.type==="Literal"&&stmt.expression.value==="use strict"}function eat(type){if(tokType===type){next();return true}else{return false}}function canInsertSemicolon(){return!options.strictSemicolons&&(tokType===_eof||tokType===_braceR||newline.test(input.slice(lastEnd,tokStart)))}function semicolon(){if(!eat(_semi)&&!canInsertSemicolon())unexpected()}function expect(type){eat(type)||unexpected()}function nextChar(){return input.charAt(tokPos)}function unexpected(pos){raise(pos!=null?pos:tokStart,"Unexpected token")}function has(obj,propName){return Object.prototype.hasOwnProperty.call(obj,propName)}function toAssignable(node,allowSpread,checkType){if(options.ecmaVersion>=6&&node){switch(node.type){case"Identifier":case"MemberExpression":break;case"ObjectExpression":node.type="ObjectPattern";for(var i=0;i<node.properties.length;i++){var prop=node.properties[i];if(prop.type==="Property"&&prop.kind!=="init")unexpected(prop.key.start);toAssignable(prop.value,false,checkType)}break;case"ArrayExpression":node.type="ArrayPattern";for(var i=0,lastI=node.elements.length-1;i<=lastI;i++){toAssignable(node.elements[i],i===lastI,checkType)}break;case"SpreadElement":if(allowSpread){toAssignable(node.argument,false,checkType);checkSpreadAssign(node.argument)}else{unexpected(node.start)}break;default:if(checkType)unexpected(node.start)}}return node}function checkSpreadAssign(node){if(node.type!=="Identifier"&&node.type!=="ArrayPattern")unexpected(node.start)}function checkFunctionParam(param,nameHash){switch(param.type){case"Identifier":if(isStrictReservedWord(param.name)||isStrictBadIdWord(param.name))raise(param.start,"Defining '"+param.name+"' in strict mode");if(has(nameHash,param.name))raise(param.start,"Argument name clash in strict mode");nameHash[param.name]=true;break;case"ObjectPattern":for(var i=0;i<param.properties.length;i++)checkFunctionParam(param.properties[i].value,nameHash);break;case"ArrayPattern":for(var i=0;i<param.elements.length;i++){var elem=param.elements[i];if(elem)checkFunctionParam(elem,nameHash)}break}}function checkPropClash(prop,propHash){if(options.ecmaVersion>=6)return;var key=prop.key,name;switch(key.type){case"Identifier":name=key.name;break;case"Literal":name=String(key.value);break;default:return}var kind=prop.kind||"init",other;if(has(propHash,name)){other=propHash[name];var isGetSet=kind!=="init";if((strict||isGetSet)&&other[kind]||!(isGetSet^other.init))raise(key.start,"Redefinition of property")}else{other=propHash[name]={init:false,get:false,set:false}}other[kind]=true}function checkLVal(expr,isBinding){switch(expr.type){case"Identifier":if(strict&&(isStrictBadIdWord(expr.name)||isStrictReservedWord(expr.name)))raise(expr.start,isBinding?"Binding "+expr.name+" in strict mode":"Assigning to "+expr.name+" in strict mode");break;case"MemberExpression":if(!isBinding)break;case"ObjectPattern":for(var i=0;i<expr.properties.length;i++){var prop=expr.properties[i];if(prop.type==="Property")prop=prop.value;checkLVal(prop,isBinding)}break;case"ArrayPattern":for(var i=0;i<expr.elements.length;i++){var elem=expr.elements[i];if(elem)checkLVal(elem,isBinding)}break;case"SpreadProperty":case"SpreadElement":case"VirtualPropertyExpression":break;default:raise(expr.start,"Assigning to rvalue")}}function parseTopLevel(node){var first=true;if(!node.body)node.body=[];while(tokType!==_eof){var stmt=parseStatement();node.body.push(stmt);if(first&&isUseStrict(stmt))setStrict(true);first=false}lastStart=tokStart;lastEnd=tokEnd;lastEndLoc=tokEndLoc;return finishNode(node,"Program")}var loopLabel={kind:"loop"},switchLabel={kind:"switch"};function parseStatement(){if(tokType===_slash||tokType===_assign&&tokVal=="/=")readToken(true);var starttype=tokType,node=startNode();switch(starttype){case _break:case _continue:return parseBreakContinueStatement(node,starttype.keyword);case _debugger:return parseDebuggerStatement(node);case _do:return parseDoStatement(node);case _for:return parseForStatement(node);case _async:return parseAsync(node,true);case _function:return parseFunctionStatement(node);case _class:return parseClass(node,true);case _if:return parseIfStatement(node);case _return:return parseReturnStatement(node);case _switch:return parseSwitchStatement(node);case _throw:return parseThrowStatement(node);case _try:return parseTryStatement(node);case _var:case _let:case _const:return parseVarStatement(node,starttype.keyword);case _while:return parseWhileStatement(node);case _with:return parseWithStatement(node);case _braceL:return parseBlock();case _semi:return parseEmptyStatement(node);case _export:return parseExport(node);case _import:return parseImport(node);default:var maybeName=tokVal,expr=parseExpression();if(starttype===_name&&expr.type==="Identifier"&&eat(_colon))return parseLabeledStatement(node,maybeName,expr);else return parseExpressionStatement(node,expr)}}function parseBreakContinueStatement(node,keyword){var isBreak=keyword=="break";next();if(eat(_semi)||canInsertSemicolon())node.label=null;else if(tokType!==_name)unexpected();else{node.label=parseIdent();semicolon()}for(var i=0;i<labels.length;++i){var lab=labels[i];if(node.label==null||lab.name===node.label.name){if(lab.kind!=null&&(isBreak||lab.kind==="loop"))break;if(node.label&&isBreak)break}}if(i===labels.length)raise(node.start,"Unsyntactic "+keyword);return finishNode(node,isBreak?"BreakStatement":"ContinueStatement")}function parseDebuggerStatement(node){next();semicolon();return finishNode(node,"DebuggerStatement")}function parseDoStatement(node){next();labels.push(loopLabel);node.body=parseStatement();labels.pop();expect(_while);node.test=parseParenExpression();semicolon();return finishNode(node,"DoWhileStatement")}function parseForStatement(node){next();labels.push(loopLabel);expect(_parenL);if(tokType===_semi)return parseFor(node,null);if(tokType===_var||tokType===_let){var init=startNode(),varKind=tokType.keyword,isLet=tokType===_let;next();parseVar(init,true,varKind);finishNode(init,"VariableDeclaration");if((tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of")&&init.declarations.length===1&&!(isLet&&init.declarations[0].init))return parseForIn(node,init);return parseFor(node,init)}var init=parseExpression(false,true);if(tokType===_in||options.ecmaVersion>=6&&tokType===_name&&tokVal==="of"){checkLVal(init);return parseForIn(node,init)}return parseFor(node,init)}function parseFunctionStatement(node){next();return parseFunction(node,true,false)}function parseAsync(node,isStatement){if(options.ecmaVersion<7){unexpected()}next();switch(tokType){case _function:next();return parseFunction(node,isStatement,true);if(!isStatement)unexpected();case _name:var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(node,[id],true)}case _parenL:var oldParenL=++metParenL;var exprList=[];next();if(tokType!==_parenR){var val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){return parseArrowExpression(node,exprList,true)}default:unexpected()}}function parseIfStatement(node){next();node.test=parseParenExpression();node.consequent=parseStatement();node.alternate=eat(_else)?parseStatement():null;return finishNode(node,"IfStatement")}function parseReturnStatement(node){if(!inFunction&&!options.allowReturnOutsideFunction)raise(tokStart,"'return' outside of function");next();if(eat(_semi)||canInsertSemicolon())node.argument=null;else{node.argument=parseExpression();semicolon()}return finishNode(node,"ReturnStatement")}function parseSwitchStatement(node){next();node.discriminant=parseParenExpression();node.cases=[];expect(_braceL);labels.push(switchLabel);for(var cur,sawDefault;tokType!=_braceR;){if(tokType===_case||tokType===_default){var isCase=tokType===_case;if(cur)finishNode(cur,"SwitchCase");node.cases.push(cur=startNode());cur.consequent=[];next();if(isCase)cur.test=parseExpression();else{if(sawDefault)raise(lastStart,"Multiple default clauses");sawDefault=true;cur.test=null}expect(_colon)}else{if(!cur)unexpected();cur.consequent.push(parseStatement())}}if(cur)finishNode(cur,"SwitchCase");next();labels.pop();return finishNode(node,"SwitchStatement")}function parseThrowStatement(node){next();if(newline.test(input.slice(lastEnd,tokStart)))raise(lastEnd,"Illegal newline after throw");node.argument=parseExpression();semicolon();return finishNode(node,"ThrowStatement")}function parseTryStatement(node){next();node.block=parseBlock();node.handler=null;if(tokType===_catch){var clause=startNode();next();expect(_parenL);clause.param=parseIdent();if(strict&&isStrictBadIdWord(clause.param.name))raise(clause.param.start,"Binding "+clause.param.name+" in strict mode");expect(_parenR);clause.guard=null;clause.body=parseBlock();node.handler=finishNode(clause,"CatchClause")}node.guardedHandlers=empty;node.finalizer=eat(_finally)?parseBlock():null;if(!node.handler&&!node.finalizer)raise(node.start,"Missing catch or finally clause");return finishNode(node,"TryStatement")}function parseVarStatement(node,kind){next();parseVar(node,false,kind);semicolon();return finishNode(node,"VariableDeclaration")}function parseWhileStatement(node){next();node.test=parseParenExpression();labels.push(loopLabel);node.body=parseStatement();labels.pop();return finishNode(node,"WhileStatement")}function parseWithStatement(node){if(strict)raise(tokStart,"'with' in strict mode");next();node.object=parseParenExpression();node.body=parseStatement();return finishNode(node,"WithStatement")}function parseEmptyStatement(node){next();return finishNode(node,"EmptyStatement")}function parseLabeledStatement(node,maybeName,expr){for(var i=0;i<labels.length;++i)if(labels[i].name===maybeName)raise(expr.start,"Label '"+maybeName+"' is already declared");var kind=tokType.isLoop?"loop":tokType===_switch?"switch":null;labels.push({name:maybeName,kind:kind});node.body=parseStatement();labels.pop();node.label=expr;return finishNode(node,"LabeledStatement")}function parseExpressionStatement(node,expr){node.expression=expr;semicolon();return finishNode(node,"ExpressionStatement")}function parseParenExpression(){expect(_parenL);var val=parseExpression();expect(_parenR);return val}function parseBlock(allowStrict){var node=startNode(),first=true,oldStrict;node.body=[];expect(_braceL);while(!eat(_braceR)){var stmt=parseStatement();node.body.push(stmt);if(first&&allowStrict&&isUseStrict(stmt)){oldStrict=strict;setStrict(strict=true)}first=false}if(oldStrict===false)setStrict(false);return finishNode(node,"BlockStatement")}function parseFor(node,init){node.init=init;expect(_semi);node.test=tokType===_semi?null:parseExpression();expect(_semi);node.update=tokType===_parenR?null:parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,"ForStatement")}function parseForIn(node,init){var type=tokType===_in?"ForInStatement":"ForOfStatement";next();node.left=init;node.right=parseExpression();expect(_parenR);node.body=parseStatement();labels.pop();return finishNode(node,type)}function parseVar(node,noIn,kind){node.declarations=[];node.kind=kind;for(;;){var decl=startNode();decl.id=options.ecmaVersion>=6?toAssignable(parseExprAtom()):parseIdent();checkLVal(decl.id,true);decl.init=eat(_eq)?parseExpression(true,noIn):kind===_const.keyword?unexpected():null;node.declarations.push(finishNode(decl,"VariableDeclarator"));if(!eat(_comma))break}return node}function parseExpression(noComma,noIn){var start=storeCurrentPos();var expr=parseMaybeAssign(noIn);if(!noComma&&tokType===_comma){var node=startNodeAt(start);node.expressions=[expr];while(eat(_comma))node.expressions.push(parseMaybeAssign(noIn));return finishNode(node,"SequenceExpression")}return expr}function parseMaybeAssign(noIn){var start=storeCurrentPos();var left=parseMaybeConditional(noIn);if(tokType.isAssign){var node=startNodeAt(start);node.operator=tokVal;node.left=tokType===_eq?toAssignable(left):left;checkLVal(left);next();node.right=parseMaybeAssign(noIn);return finishNode(node,"AssignmentExpression")}return left}function parseMaybeConditional(noIn){var start=storeCurrentPos();var expr=parseExprOps(noIn);if(eat(_question)){var node=startNodeAt(start);if(eat(_eq)){var left=node.left=toAssignable(expr);if(left.type!=="MemberExpression")raise(left.start,"You can only use member expressions in memoization assignment");node.right=parseMaybeAssign(noIn);node.operator="?=";return finishNode(node,"AssignmentExpression")}node.test=expr;node.consequent=parseExpression(true);expect(_colon);node.alternate=parseExpression(true,noIn);return finishNode(node,"ConditionalExpression")}return expr}function parseExprOps(noIn){var start=storeCurrentPos();return parseExprOp(parseMaybeUnary(),start,-1,noIn)}function parseExprOp(left,leftStart,minPrec,noIn){var prec=tokType.binop;if(prec!=null&&(!noIn||tokType!==_in)){if(prec>minPrec){var node=startNodeAt(leftStart);node.left=left;node.operator=tokVal;var op=tokType;next();var start=storeCurrentPos();node.right=parseExprOp(parseMaybeUnary(),start,prec,noIn);finishNode(node,op===_logicalOR||op===_logicalAND?"LogicalExpression":"BinaryExpression");return parseExprOp(node,leftStart,minPrec,noIn)}}return left}function parseMaybeUnary(){if(tokType.prefix){var node=startNode(),update=tokType.isUpdate,nodeType;if(tokType===_ellipsis){nodeType="SpreadElement"}else{nodeType=update?"UpdateExpression":"UnaryExpression";node.operator=tokVal;node.prefix=true}tokRegexpAllowed=true;next();node.argument=parseMaybeUnary();if(update)checkLVal(node.argument);else if(strict&&node.operator==="delete"&&node.argument.type==="Identifier")raise(node.start,"Deleting local variable in strict mode");return finishNode(node,nodeType)}var start=storeCurrentPos();var expr=parseExprSubscripts();while(tokType.postfix&&!canInsertSemicolon()){var node=startNodeAt(start);node.operator=tokVal;node.prefix=false;node.argument=expr;checkLVal(expr);next();expr=finishNode(node,"UpdateExpression")}return expr}function parseExprSubscripts(){var start=storeCurrentPos();return parseSubscripts(parseExprAtom(),start)}function parseSubscripts(base,start,noCalls){if(options.playground&&eat(_colon)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return parseSubscripts(finishNode(node,"BindMemberExpression"),start,noCalls)}else if(eat(_doubleColon)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);return parseSubscripts(finishNode(node,"VirtualPropertyExpression"),start,noCalls)}else if(eat(_dot)){var node=startNodeAt(start);node.object=base;node.property=parseIdent(true);node.computed=false;return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(eat(_bracketL)){var node=startNodeAt(start);node.object=base;node.property=parseExpression();node.computed=true;expect(_bracketR);return parseSubscripts(finishNode(node,"MemberExpression"),start,noCalls)}else if(!noCalls&&eat(_parenL)){var node=startNodeAt(start);node.callee=base;node.arguments=parseExprList(_parenR,false);return parseSubscripts(finishNode(node,"CallExpression"),start,noCalls)}else if(tokType===_bquote){var node=startNodeAt(start);node.tag=base;node.quasi=parseTemplate();return parseSubscripts(finishNode(node,"TaggedTemplateExpression"),start,noCalls)}return base}function parseExprAtom(){switch(tokType){case _this:var node=startNode();next();return finishNode(node,"ThisExpression");case _yield:if(inGenerator)return parseYield();case _await:if(inAsync)return parseAwait();case _name:var start=storeCurrentPos();var id=parseIdent(tokType!==_name);if(eat(_arrow)){return parseArrowExpression(startNodeAt(start),[id])}return id;case _regexp:var node=startNode();node.regex={pattern:tokVal.pattern,flags:tokVal.flags};node.value=tokVal.value;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _num:case _string:case _xjsText:var node=startNode();node.value=tokVal;node.raw=input.slice(tokStart,tokEnd);next();return finishNode(node,"Literal");case _null:case _true:case _false:var node=startNode();node.value=tokType.atomValue;node.raw=tokType.keyword;next();return finishNode(node,"Literal");case _parenL:var start=storeCurrentPos();var val,exprList;next();if(options.ecmaVersion>=7&&tokType===_for){val=parseComprehension(startNodeAt(start),true)}else{var oldParenL=++metParenL;if(tokType!==_parenR){val=parseExpression();exprList=val.type==="SequenceExpression"?val.expressions:[val]}else{exprList=[]}expect(_parenR);if(metParenL===oldParenL&&eat(_arrow)){val=parseArrowExpression(startNodeAt(start),exprList)}else{if(!val)unexpected(lastStart);if(options.ecmaVersion>=6){for(var i=0;i<exprList.length;i++){if(exprList[i].type==="SpreadElement")unexpected()}}if(options.preserveParens){var par=startNodeAt(start);par.expression=val;val=finishNode(par,"ParenthesizedExpression")}}}return val;case _bracketL:var node=startNode();next();if(options.ecmaVersion>=7&&tokType===_for){return parseComprehension(node,false)}node.elements=parseExprList(_bracketR,true,true);return finishNode(node,"ArrayExpression");case _braceL:return parseObj();case _async:return parseAsync(startNode(),false);case _function:var node=startNode();next();return parseFunction(node,false,false);case _class:return parseClass(startNode(),false);case _new:return parseNew();case _bquote:return parseTemplate();case _lt:return parseXJSElement();case _colon:return parseBindFunctionExpression();default:unexpected()}}function parseBindFunctionExpression(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL)){node.arguments=parseExprList(_parenR,false)}else{node.arguments=[]}return finishNode(node,"BindFunctionExpression")}function parseNew(){var node=startNode();next();var start=storeCurrentPos();node.callee=parseSubscripts(parseExprAtom(),start,true);if(eat(_parenL))node.arguments=parseExprList(_parenR,false); else node.arguments=empty;return finishNode(node,"NewExpression")}function parseTemplate(){var node=startNode();node.expressions=[];node.quasis=[];inTemplate=true;next();for(;;){var elem=startNode();elem.value={cooked:tokVal,raw:input.slice(tokStart,tokEnd)};elem.tail=false;next();node.quasis.push(finishNode(elem,"TemplateElement"));if(tokType===_bquote){elem.tail=true;break}inTemplate=false;expect(_dollarBraceL);node.expressions.push(parseExpression());inTemplate=true;tokPos=tokEnd;expect(_braceR)}inTemplate=false;next();return finishNode(node,"TemplateLiteral")}function parseObj(){var node=startNode(),first=true,propHash={};node.properties=[];next();while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var prop=startNode(),isGenerator,isAsync;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}if(options.ecmaVersion>=6){prop.method=false;prop.shorthand=false;isGenerator=eat(_star)}if(options.ecmaVersion>=7&&tokType===_ellipsis){if(isAsync||isGenerator)unexpected();prop=parseMaybeUnary();prop.type="SpreadProperty";node.properties.push(prop);continue}parsePropertyName(prop);if(eat(_colon)){prop.value=parseExpression(true);prop.kind="init"}else if(options.ecmaVersion>=6&&tokType===_parenL){prop.kind="init";prop.method=true;prop.value=parseMethod(isGenerator,isAsync)}else if(options.ecmaVersion>=5&&!prop.computed&&prop.key.type==="Identifier"&&(prop.key.name==="get"||prop.key.name==="set")){if(isGenerator||isAsync)unexpected();prop.kind=prop.key.name;parsePropertyName(prop);prop.value=parseMethod(false,false)}else if(options.ecmaVersion>=6&&!prop.computed&&prop.key.type==="Identifier"){prop.kind="init";prop.value=prop.key;prop.shorthand=true}else unexpected();checkPropClash(prop,propHash);node.properties.push(finishNode(prop,"Property"))}return finishNode(node,"ObjectExpression")}function parsePropertyName(prop){if(options.ecmaVersion>=6){if(eat(_bracketL)){prop.computed=true;prop.key=parseExpression();expect(_bracketR);return}else{prop.computed=false}}prop.key=tokType===_num||tokType===_string?parseExprAtom():parseIdent(true)}function initFunction(node,isAsync){node.id=null;node.params=[];if(options.ecmaVersion>=6){node.defaults=[];node.rest=null;node.generator=false}if(options.ecmaVersion>=7){node.async=isAsync}}function parseFunction(node,isStatement,isAsync,allowExpressionBody){initFunction(node,isAsync);if(options.ecmaVersion>=6){if(isAsync&&tokType===_star)unexpected();node.generator=eat(_star)}if(isStatement||tokType===_name){node.id=parseIdent()}parseFunctionParams(node);parseFunctionBody(node,allowExpressionBody);return finishNode(node,isStatement?"FunctionDeclaration":"FunctionExpression")}function parseMethod(isGenerator,isAsync){var node=startNode();initFunction(node,isAsync);parseFunctionParams(node);var allowExpressionBody;if(options.ecmaVersion>=6){node.generator=isGenerator;allowExpressionBody=true}else{allowExpressionBody=false}parseFunctionBody(node,allowExpressionBody);return finishNode(node,"FunctionExpression")}function parseArrowExpression(node,params,isAsync){initFunction(node,isAsync);var defaults=node.defaults,hasDefaults=false;for(var i=0,lastI=params.length-1;i<=lastI;i++){var param=params[i];if(param.type==="AssignmentExpression"&&param.operator==="="){hasDefaults=true;params[i]=param.left;defaults.push(param.right)}else{toAssignable(param,i===lastI,true);defaults.push(null);if(param.type==="SpreadElement"){params.length--;node.rest=param.argument;break}}}node.params=params;if(!hasDefaults)node.defaults=[];parseFunctionBody(node,true);return finishNode(node,"ArrowFunctionExpression")}function parseFunctionParams(node){var defaults=[],hasDefaults=false;expect(_parenL);for(;;){if(eat(_parenR)){break}else if(options.ecmaVersion>=6&&eat(_ellipsis)){node.rest=toAssignable(parseExprAtom(),false,true);checkSpreadAssign(node.rest);expect(_parenR);defaults.push(null);break}else{node.params.push(options.ecmaVersion>=6?toAssignable(parseExprAtom(),false,true):parseIdent());if(options.ecmaVersion>=6){if(eat(_eq)){hasDefaults=true;defaults.push(parseExpression(true))}else{defaults.push(null)}}if(!eat(_comma)){expect(_parenR);break}}}if(hasDefaults)node.defaults=defaults}function parseFunctionBody(node,allowExpression){var isExpression=allowExpression&&tokType!==_braceL;var oldInAsync=inAsync;inAsync=node.async;if(isExpression){node.body=parseExpression(true);node.expression=true}else{var oldInFunc=inFunction,oldInGen=inGenerator,oldLabels=labels;inFunction=true;inGenerator=node.generator;labels=[];node.body=parseBlock(true);node.expression=false;inFunction=oldInFunc;inGenerator=oldInGen;labels=oldLabels}inAsync=oldInAsync;if(strict||!isExpression&&node.body.body.length&&isUseStrict(node.body.body[0])){var nameHash={};if(node.id)checkFunctionParam(node.id,{});for(var i=0;i<node.params.length;i++)checkFunctionParam(node.params[i],nameHash);if(node.rest)checkFunctionParam(node.rest,nameHash)}}function parseClass(node,isStatement){next();node.id=tokType===_name?parseIdent():isStatement?unexpected():null;node.superClass=eat(_extends)?parseExpression():null;var classBody=startNode();classBody.body=[];expect(_braceL);while(!eat(_braceR)){var method=startNode();if(tokType===_name&&tokVal==="static"){next();method["static"]=true}else{method["static"]=false}var isAsync=false;if(options.ecmaVersion>=7){isAsync=eat(_async);if(isAsync&&tokType===_star)unexpected()}var isGenerator=eat(_star);parsePropertyName(method);if(tokType!==_parenL&&!method.computed&&method.key.type==="Identifier"&&(method.key.name==="get"||method.key.name==="set")){if(isGenerator||isAsync)unexpected();method.kind=method.key.name;parsePropertyName(method)}else{method.kind=""}method.value=parseMethod(isGenerator,isAsync);classBody.body.push(finishNode(method,"MethodDefinition"));eat(_semi)}node.body=finishNode(classBody,"ClassBody");return finishNode(node,isStatement?"ClassDeclaration":"ClassExpression")}function parseExprList(close,allowTrailingComma,allowEmpty){var elts=[],first=true;while(!eat(close)){if(!first){expect(_comma);if(allowTrailingComma&&options.allowTrailingCommas&&eat(close))break}else first=false;if(allowEmpty&&tokType===_comma)elts.push(null);else elts.push(parseExpression(true))}return elts}function parseIdent(liberal){var node=startNode();if(liberal&&options.forbidReserved=="everywhere")liberal=false;if(tokType===_name){if(!liberal&&(options.forbidReserved&&(options.ecmaVersion===3?isReservedWord3:isReservedWord5)(tokVal)||strict&&isStrictReservedWord(tokVal))&&input.slice(tokStart,tokEnd).indexOf("\\")==-1)raise(tokStart,"The keyword '"+tokVal+"' is reserved");node.name=tokVal}else if(liberal&&tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"Identifier")}function parseExport(node){next();if(tokType===_var||tokType===_const||tokType===_let||tokType===_function||tokType===_class||tokType===_async){node.declaration=parseStatement();node["default"]=false;node.specifiers=null;node.source=null}else if(eat(_default)){node.declaration=parseExpression(true);node["default"]=true;node.specifiers=null;node.source=null;semicolon()}else{var isBatch=tokType===_star;node.declaration=null;node["default"]=false;node.specifiers=parseExportSpecifiers();if(tokType===_name&&tokVal==="from"){next();node.source=tokType===_string?parseExprAtom():unexpected()}else{if(isBatch)unexpected();node.source=null}semicolon()}return finishNode(node,"ExportDeclaration")}function parseExportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();nodes.push(finishNode(node,"ExportBatchSpecifier"))}else{expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(tokType===_default);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent(true)}else{node.name=null}nodes.push(finishNode(node,"ExportSpecifier"))}}return nodes}function parseImport(node){next();if(tokType===_string){node.specifiers=[];node.source=parseExprAtom();node.kind=""}else{node.specifiers=parseImportSpecifiers();if(tokType!==_name||tokVal!=="from")unexpected();next();node.source=tokType===_string?parseExprAtom():unexpected();node.kind=node.specifiers[0]["default"]?"default":"named"}semicolon();return finishNode(node,"ImportDeclaration")}function parseImportSpecifiers(){var nodes=[],first=true;if(tokType===_star){var node=startNode();next();if(tokType!==_name||tokVal!=="as")unexpected();next();node.name=parseIdent();checkLVal(node.name,true);nodes.push(finishNode(node,"ImportBatchSpecifier"));return nodes}if(tokType===_name){var node=startNode();node.id=parseIdent();checkLVal(node.id,true);node.name=null;node["default"]=true;nodes.push(finishNode(node,"ImportSpecifier"));if(!eat(_comma))return nodes}expect(_braceL);while(!eat(_braceR)){if(!first){expect(_comma);if(options.allowTrailingCommas&&eat(_braceR))break}else first=false;var node=startNode();node.id=parseIdent(true);if(tokType===_name&&tokVal==="as"){next();node.name=parseIdent()}else{node.name=null}checkLVal(node.name||node.id,true);node["default"]=false;nodes.push(finishNode(node,"ImportSpecifier"))}return nodes}function parseYield(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){node.delegate=false;node.argument=null}else{node.delegate=eat(_star);node.argument=parseExpression(true)}return finishNode(node,"YieldExpression")}function parseAwait(){var node=startNode();next();if(eat(_semi)||canInsertSemicolon()){unexpected()}node.delegate=eat(_star);node.argument=parseExpression(true);return finishNode(node,"AwaitExpression")}function parseComprehension(node,isGenerator){node.blocks=[];while(tokType===_for){var block=startNode();next();expect(_parenL);block.left=toAssignable(parseExprAtom());checkLVal(block.left,true);if(tokType!==_name||tokVal!=="of")unexpected();next();block.of=true;block.right=parseExpression();expect(_parenR);node.blocks.push(finishNode(block,"ComprehensionBlock"))}node.filter=eat(_if)?parseParenExpression():null;node.body=parseExpression();expect(isGenerator?_parenR:_bracketR);node.generator=isGenerator;return finishNode(node,"ComprehensionExpression")}function getQualifiedXJSName(object){if(object.type==="XJSIdentifier"){return object.name}if(object.type==="XJSNamespacedName"){return object.namespace.name+":"+object.name.name}if(object.type==="XJSMemberExpression"){return getQualifiedXJSName(object.object)+"."+getQualifiedXJSName(object.property)}}function parseXJSIdentifier(){var node=startNode();if(tokType===_xjsName){node.name=tokVal}else if(tokType.keyword){node.name=tokType.keyword}else{unexpected()}tokRegexpAllowed=false;next();return finishNode(node,"XJSIdentifier")}function parseXJSNamespacedName(){var node=startNode();node.namespace=parseXJSIdentifier();expect(_colon);node.name=parseXJSIdentifier();return finishNode(node,"XJSNamespacedName")}function parseXJSMemberExpression(){var start=storeCurrentPos();var node=parseXJSIdentifier();while(eat(_dot)){var newNode=startNodeAt(start);newNode.object=node;newNode.property=parseXJSIdentifier();node=finishNode(newNode,"XJSMemberExpression")}return node}function parseXJSElementName(){switch(nextChar()){case":":return parseXJSNamespacedName();case".":return parseXJSMemberExpression();default:return parseXJSIdentifier()}}function parseXJSAttributeName(){if(nextChar()===":"){return parseXJSNamespacedName()}return parseXJSIdentifier()}function parseXJSAttributeValue(){switch(tokType){case _braceL:var node=parseXJSExpressionContainer();if(node.expression.type==="XJSEmptyExpression"){raise(node.start,"XJS attributes must only be assigned a non-empty "+"expression")}return node;case _lt:return parseXJSElement();case _xjsText:return parseExprAtom();default:raise(tokStart,"XJS value should be either an expression or a quoted XJS text")}}function parseXJSEmptyExpression(){if(tokType!==_braceR){unexpected()}var tmp;tmp=tokStart;tokStart=lastEnd;lastEnd=tmp;tmp=tokStartLoc;tokStartLoc=lastEndLoc;lastEndLoc=tmp;return finishNode(startNode(),"XJSEmptyExpression")}function parseXJSExpressionContainer(){var node=startNode();var origInXJSTag=inXJSTag,origInXJSChild=inXJSChild;inXJSTag=false;inXJSChild=false;next();node.expression=tokType===_braceR?parseXJSEmptyExpression():parseExpression();inXJSTag=origInXJSTag;inXJSChild=origInXJSChild;if(inXJSChild){tokPos=tokEnd}expect(_braceR);return finishNode(node,"XJSExpressionContainer")}function parseXJSAttribute(){if(tokType===_braceL){var tokStart1=tokStart,tokStartLoc1=tokStartLoc;var origInXJSTag=inXJSTag;inXJSTag=false;next();if(tokType!==_ellipsis)unexpected();var node=parseMaybeUnary();inXJSTag=origInXJSTag;expect(_braceR);node.type="XJSSpreadAttribute";node.start=tokStart1;node.end=lastEnd;if(options.locations){node.loc.start=tokStartLoc1;node.loc.end=lastEndLoc}if(options.ranges){node.range=[tokStart1,lastEnd]}return node}var node=startNode();node.name=parseXJSAttributeName();if(tokType===_eq){next();node.value=parseXJSAttributeValue()}else{node.value=null}return finishNode(node,"XJSAttribute")}function parseXJSChild(){switch(tokType){case _braceL:return parseXJSExpressionContainer();case _xjsText:return parseExprAtom();default:return parseXJSElement()}}function parseXJSOpeningElement(){var node=startNode(),attributes=node.attributes=[];var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;next();node.name=parseXJSElementName();while(tokType!==_eof&&tokType!==_slash&&tokType!==_gt){attributes.push(parseXJSAttribute())}inXJSTag=false;if(node.selfClosing=!!eat(_slash)){inXJSTag=origInXJSTag;inXJSChild=origInXJSChild}else{inXJSChild=true}expect(_gt);return finishNode(node,"XJSOpeningElement")}function parseXJSClosingElement(){var node=startNode();var origInXJSChild=inXJSChild;var origInXJSTag=inXJSTag;inXJSChild=false;inXJSTag=true;tokRegexpAllowed=false;expect(_ltSlash);node.name=parseXJSElementName();skipSpace();inXJSChild=origInXJSChild;inXJSTag=origInXJSTag;tokRegexpAllowed=false;if(inXJSChild){tokPos=tokEnd}expect(_gt);return finishNode(node,"XJSClosingElement")}function parseXJSElement(){var node=startNode();var children=[];var origInXJSChild=inXJSChild;var openingElement=parseXJSOpeningElement();var closingElement=null;if(!openingElement.selfClosing){while(tokType!==_eof&&tokType!==_ltSlash){inXJSChild=true;children.push(parseXJSChild())}inXJSChild=origInXJSChild;closingElement=parseXJSClosingElement();if(getQualifiedXJSName(closingElement.name)!==getQualifiedXJSName(openingElement.name)){raise(closingElement.start,"Expected corresponding XJS closing tag for '"+getQualifiedXJSName(openingElement.name)+"'")}}if(!origInXJSChild&&tokType===_lt){raise(tokStart,"Adjacent XJS elements must be wrapped in an enclosing tag")}node.openingElement=openingElement;node.closingElement=closingElement;node.children=children;return finishNode(node,"XJSElement")}})},{}],78:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var def=Type.def;var or=Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isNumber=builtin.number;var isBoolean=builtin.boolean;var isRegExp=builtin.RegExp;var shared=require("../lib/shared");var defaults=shared.defaults;var geq=shared.geq;def("Node").field("type",isString).field("loc",or(def("SourceLocation"),null),defaults["null"],true);def("SourceLocation").build("start","end","source").field("start",def("Position")).field("end",def("Position")).field("source",or(isString,null),defaults["null"]);def("Position").build("line","column").field("line",geq(1)).field("column",geq(0));def("Program").bases("Node").build("body").field("body",[def("Statement")]);def("Function").bases("Node").field("id",or(def("Identifier"),null),defaults["null"]).field("params",[def("Pattern")]).field("body",or(def("BlockStatement"),def("Expression")));def("Statement").bases("Node");def("EmptyStatement").bases("Statement").build();def("BlockStatement").bases("Statement").build("body").field("body",[def("Statement")]);def("ExpressionStatement").bases("Statement").build("expression").field("expression",def("Expression"));def("IfStatement").bases("Statement").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Statement")).field("alternate",or(def("Statement"),null),defaults["null"]);def("LabeledStatement").bases("Statement").build("label","body").field("label",def("Identifier")).field("body",def("Statement"));def("BreakStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("ContinueStatement").bases("Statement").build("label").field("label",or(def("Identifier"),null),defaults["null"]);def("WithStatement").bases("Statement").build("object","body").field("object",def("Expression")).field("body",def("Statement"));def("SwitchStatement").bases("Statement").build("discriminant","cases","lexical").field("discriminant",def("Expression")).field("cases",[def("SwitchCase")]).field("lexical",isBoolean,defaults["false"]);def("ReturnStatement").bases("Statement").build("argument").field("argument",or(def("Expression"),null));def("ThrowStatement").bases("Statement").build("argument").field("argument",def("Expression"));def("TryStatement").bases("Statement").build("block","handler","finalizer").field("block",def("BlockStatement")).field("handler",or(def("CatchClause"),null),function(){return this.handlers&&this.handlers[0]||null}).field("handlers",[def("CatchClause")],function(){return this.handler?[this.handler]:[]},true).field("guardedHandlers",[def("CatchClause")],defaults.emptyArray).field("finalizer",or(def("BlockStatement"),null),defaults["null"]);def("CatchClause").bases("Node").build("param","guard","body").field("param",def("Pattern")).field("guard",or(def("Expression"),null),defaults["null"]).field("body",def("BlockStatement"));def("WhileStatement").bases("Statement").build("test","body").field("test",def("Expression")).field("body",def("Statement"));def("DoWhileStatement").bases("Statement").build("body","test").field("body",def("Statement")).field("test",def("Expression"));def("ForStatement").bases("Statement").build("init","test","update","body").field("init",or(def("VariableDeclaration"),def("Expression"),null)).field("test",or(def("Expression"),null)).field("update",or(def("Expression"),null)).field("body",def("Statement"));def("ForInStatement").bases("Statement").build("left","right","body","each").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement")).field("each",isBoolean);def("DebuggerStatement").bases("Statement").build();def("Declaration").bases("Statement");def("FunctionDeclaration").bases("Function","Declaration").build("id","params","body").field("id",def("Identifier"));def("FunctionExpression").bases("Function","Expression").build("id","params","body");def("VariableDeclaration").bases("Declaration").build("kind","declarations").field("kind",or("var","let","const")).field("declarations",[or(def("VariableDeclarator"),def("Identifier"))]);def("VariableDeclarator").bases("Node").build("id","init").field("id",def("Pattern")).field("init",or(def("Expression"),null));def("Expression").bases("Node","Pattern");def("ThisExpression").bases("Expression").build();def("ArrayExpression").bases("Expression").build("elements").field("elements",[or(def("Expression"),null)]);def("ObjectExpression").bases("Expression").build("properties").field("properties",[def("Property")]);def("Property").bases("Node").build("kind","key","value").field("kind",or("init","get","set")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Expression"));def("SequenceExpression").bases("Expression").build("expressions").field("expressions",[def("Expression")]);var UnaryOperator=or("-","+","!","~","typeof","void","delete");def("UnaryExpression").bases("Expression").build("operator","argument","prefix").field("operator",UnaryOperator).field("argument",def("Expression")).field("prefix",isBoolean,defaults["true"]);var BinaryOperator=or("==","!=","===","!==","<","<=",">",">=","<<",">>",">>>","+","-","*","/","%","&","|","^","in","instanceof","..");def("BinaryExpression").bases("Expression").build("operator","left","right").field("operator",BinaryOperator).field("left",def("Expression")).field("right",def("Expression"));var AssignmentOperator=or("=","+=","-=","*=","/=","%=","<<=",">>=",">>>=","|=","^=","&=");def("AssignmentExpression").bases("Expression").build("operator","left","right").field("operator",AssignmentOperator).field("left",def("Pattern")).field("right",def("Expression"));var UpdateOperator=or("++","--");def("UpdateExpression").bases("Expression").build("operator","argument","prefix").field("operator",UpdateOperator).field("argument",def("Expression")).field("prefix",isBoolean);var LogicalOperator=or("||","&&");def("LogicalExpression").bases("Expression").build("operator","left","right").field("operator",LogicalOperator).field("left",def("Expression")).field("right",def("Expression"));def("ConditionalExpression").bases("Expression").build("test","consequent","alternate").field("test",def("Expression")).field("consequent",def("Expression")).field("alternate",def("Expression"));def("NewExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("CallExpression").bases("Expression").build("callee","arguments").field("callee",def("Expression")).field("arguments",[def("Expression")]);def("MemberExpression").bases("Expression").build("object","property","computed").field("object",def("Expression")).field("property",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("Pattern").bases("Node");def("ObjectPattern").bases("Pattern").build("properties").field("properties",[def("PropertyPattern")]);def("PropertyPattern").bases("Pattern").build("key","pattern").field("key",or(def("Literal"),def("Identifier"))).field("pattern",def("Pattern"));def("ArrayPattern").bases("Pattern").build("elements").field("elements",[or(def("Pattern"),null)]);def("SwitchCase").bases("Node").build("test","consequent").field("test",or(def("Expression"),null)).field("consequent",[def("Statement")]);def("Identifier").bases("Node","Expression","Pattern").build("name").field("name",isString);def("Literal").bases("Node","Expression").build("value").field("value",or(isString,isBoolean,null,isNumber,isRegExp))},{"../lib/shared":89,"../lib/types":90}],79:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;def("XMLDefaultDeclaration").bases("Declaration").field("namespace",def("Expression"));def("XMLAnyName").bases("Expression");def("XMLQualifiedIdentifier").bases("Expression").field("left",or(def("Identifier"),def("XMLAnyName"))).field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLFunctionQualifiedIdentifier").bases("Expression").field("right",or(def("Identifier"),def("Expression"))).field("computed",isBoolean);def("XMLAttributeSelector").bases("Expression").field("attribute",def("Expression"));def("XMLFilterExpression").bases("Expression").field("left",def("Expression")).field("right",def("Expression"));def("XMLElement").bases("XML","Expression").field("contents",[def("XML")]);def("XMLList").bases("XML","Expression").field("contents",[def("XML")]);def("XML").bases("Node");def("XMLEscape").bases("XML").field("expression",def("Expression"));def("XMLText").bases("XML").field("text",isString);def("XMLStartTag").bases("XML").field("contents",[def("XML")]);def("XMLEndTag").bases("XML").field("contents",[def("XML")]);def("XMLPointTag").bases("XML").field("contents",[def("XML")]);def("XMLName").bases("XML").field("contents",or(isString,[def("XML")]));def("XMLAttribute").bases("XML").field("value",isString);def("XMLCdata").bases("XML").field("contents",isString);def("XMLComment").bases("XML").field("contents",isString);def("XMLProcessingInstruction").bases("XML").field("target",isString).field("contents",or(isString,null))},{"../lib/types":90,"./core":78}],80:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var isObject=builtin.object;var isString=builtin.string;var defaults=require("../lib/shared").defaults;def("Function").field("generator",isBoolean,defaults["false"]).field("expression",isBoolean,defaults["false"]).field("defaults",[or(def("Expression"),null)],defaults.emptyArray).field("rest",or(def("Identifier"),null),defaults["null"]);def("FunctionDeclaration").build("id","params","body","generator","expression");def("FunctionExpression").build("id","params","body","generator","expression");def("ArrowFunctionExpression").bases("Function","Expression").build("params","body","expression").field("id",null,defaults["null"]).field("generator",false);def("YieldExpression").bases("Expression").build("argument","delegate").field("argument",or(def("Expression"),null)).field("delegate",isBoolean,defaults["false"]);def("GeneratorExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionExpression").bases("Expression").build("body","blocks","filter").field("body",def("Expression")).field("blocks",[def("ComprehensionBlock")]).field("filter",or(def("Expression"),null));def("ComprehensionBlock").bases("Node").build("left","right","each").field("left",def("Pattern")).field("right",def("Expression")).field("each",isBoolean);def("ModuleSpecifier").bases("Literal").build("value").field("value",isString);def("Property").field("method",isBoolean,defaults["false"]).field("shorthand",isBoolean,defaults["false"]).field("computed",isBoolean,defaults["false"]);def("MethodDefinition").bases("Declaration").build("kind","key","value").field("kind",or("init","get","set","")).field("key",or(def("Literal"),def("Identifier"))).field("value",def("Function"));def("SpreadElement").bases("Node").build("argument").field("argument",def("Expression"));def("ArrayExpression").field("elements",[or(def("Expression"),def("SpreadElement"),null)]);def("NewExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("CallExpression").field("arguments",[or(def("Expression"),def("SpreadElement"))]);def("SpreadElementPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));var ClassBodyElement=or(def("MethodDefinition"),def("VariableDeclarator"),def("ClassPropertyDefinition"),def("ClassProperty"));def("ClassProperty").bases("Declaration").build("id").field("id",def("Identifier"));def("ClassPropertyDefinition").bases("Declaration").build("definition").field("definition",ClassBodyElement);def("ClassBody").bases("Declaration").build("body").field("body",[ClassBodyElement]);def("ClassDeclaration").bases("Declaration").build("id","body","superClass").field("id",def("Identifier")).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("ClassExpression").bases("Expression").build("id","body","superClass").field("id",or(def("Identifier"),null),defaults["null"]).field("body",def("ClassBody")).field("superClass",or(def("Expression"),null),defaults["null"]);def("Specifier").bases("Node");def("NamedSpecifier").bases("Specifier").field("id",def("Identifier")).field("name",or(def("Identifier"),null),defaults["null"]);def("ExportSpecifier").bases("NamedSpecifier").build("id","name");def("ExportBatchSpecifier").bases("Specifier").build();def("ImportSpecifier").bases("NamedSpecifier").build("id","name");def("ImportNamespaceSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ImportDefaultSpecifier").bases("Specifier").build("id").field("id",def("Identifier"));def("ExportDeclaration").bases("Declaration").build("default","declaration","specifiers","source").field("default",isBoolean).field("declaration",or(def("Declaration"),def("Expression"),null)).field("specifiers",[or(def("ExportSpecifier"),def("ExportBatchSpecifier"))],defaults.emptyArray).field("source",or(def("ModuleSpecifier"),null),defaults["null"]);def("ImportDeclaration").bases("Declaration").build("specifiers","source").field("specifiers",[or(def("ImportSpecifier"),def("ImportNamespaceSpecifier"),def("ImportDefaultSpecifier"))],defaults.emptyArray).field("source",def("ModuleSpecifier"));def("TaggedTemplateExpression").bases("Expression").field("tag",def("Expression")).field("quasi",def("TemplateLiteral"));def("TemplateLiteral").bases("Expression").build("quasis","expressions").field("quasis",[def("TemplateElement")]).field("expressions",[def("Expression")]);def("TemplateElement").bases("Node").build("value","tail").field("value",{cooked:isString,raw:isString}).field("tail",isBoolean)},{"../lib/shared":89,"../lib/types":90,"./core":78}],81:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("Function").field("async",isBoolean,defaults["false"]);def("SpreadProperty").bases("Node").build("argument").field("argument",def("Expression"));def("ObjectExpression").field("properties",[or(def("Property"),def("SpreadProperty"))]);def("SpreadPropertyPattern").bases("Pattern").build("argument").field("argument",def("Pattern"));def("ObjectPattern").field("properties",[or(def("PropertyPattern"),def("SpreadPropertyPattern"))]);def("AwaitExpression").bases("Expression").build("argument","all").field("argument",or(def("Expression"),null)).field("all",isBoolean,defaults["false"])},{"../lib/shared":89,"../lib/types":90,"./core":78}],82:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isString=builtin.string;var isBoolean=builtin.boolean;var defaults=require("../lib/shared").defaults;def("XJSAttribute").bases("Node").build("name","value").field("name",or(def("XJSIdentifier"),def("XJSNamespacedName"))).field("value",or(def("Literal"),def("XJSExpressionContainer"),null),defaults["null"]);def("XJSIdentifier").bases("Node").build("name").field("name",isString);def("XJSNamespacedName").bases("Node").build("namespace","name").field("namespace",def("XJSIdentifier")).field("name",def("XJSIdentifier"));def("XJSMemberExpression").bases("MemberExpression").build("object","property").field("object",or(def("XJSIdentifier"),def("XJSMemberExpression"))).field("property",def("XJSIdentifier")).field("computed",isBoolean,defaults.false);var XJSElementName=or(def("XJSIdentifier"),def("XJSNamespacedName"),def("XJSMemberExpression"));def("XJSSpreadAttribute").bases("Node").build("argument").field("argument",def("Expression"));var XJSAttributes=[or(def("XJSAttribute"),def("XJSSpreadAttribute"))];def("XJSExpressionContainer").bases("Expression").build("expression").field("expression",def("Expression"));def("XJSElement").bases("Expression").build("openingElement","closingElement","children").field("openingElement",def("XJSOpeningElement")).field("closingElement",or(def("XJSClosingElement"),null),defaults["null"]).field("children",[or(def("XJSElement"),def("XJSExpressionContainer"),def("XJSText"),def("Literal"))],defaults.emptyArray).field("name",XJSElementName,function(){return this.openingElement.name}).field("selfClosing",isBoolean,function(){return this.openingElement.selfClosing}).field("attributes",XJSAttributes,function(){return this.openingElement.attributes});def("XJSOpeningElement").bases("Node").build("name","attributes","selfClosing").field("name",XJSElementName).field("attributes",XJSAttributes,defaults.emptyArray).field("selfClosing",isBoolean,defaults["false"]); def("XJSClosingElement").bases("Node").build("name").field("name",XJSElementName);def("XJSText").bases("Literal").build("value").field("value",isString);def("XJSEmptyExpression").bases("Expression").build();def("TypeAnnotatedIdentifier").bases("Pattern").build("annotation","identifier").field("annotation",def("TypeAnnotation")).field("identifier",def("Identifier"));def("TypeAnnotation").bases("Pattern").build("annotatedType","templateTypes","paramTypes","returnType","unionType","nullable").field("annotatedType",def("Identifier")).field("templateTypes",or([def("TypeAnnotation")],null)).field("paramTypes",or([def("TypeAnnotation")],null)).field("returnType",or(def("TypeAnnotation"),null)).field("unionType",or(def("TypeAnnotation"),null)).field("nullable",isBoolean);def("ObjectTypeAnnotation").bases("Pattern").build("properties","nullable").field("properties",[def("Property")]).field("nullable",isBoolean);def("VoidTypeAnnotation").bases("Pattern");def("ParametricTypeAnnotation").bases("Pattern").build("params").field("params",[def("Identifier")]);def("OptionalParameter").bases("Pattern").build("identifier").field("identifier",def("Identifier"));def("Identifier").field("annotation",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]);def("Function").field("returnType",or(def("TypeAnnotation"),def("VoidTypeAnnotation"),def("ObjectTypeAnnotation"),null),defaults["null"]).field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"]);def("ClassProperty").field("id",or(def("Identifier"),def("TypeAnnotatedIdentifier")));def("ClassDeclaration").field("parametricType",or(def("ParametricTypeAnnotation"),null),defaults["null"])},{"../lib/shared":89,"../lib/types":90,"./core":78}],83:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var geq=require("../lib/shared").geq;def("ForOfStatement").bases("Statement").build("left","right","body").field("left",or(def("VariableDeclaration"),def("Expression"))).field("right",def("Expression")).field("body",def("Statement"));def("LetStatement").bases("Statement").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Statement"));def("LetExpression").bases("Expression").build("head","body").field("head",[def("VariableDeclarator")]).field("body",def("Expression"));def("GraphExpression").bases("Expression").build("index","expression").field("index",geq(0)).field("expression",def("Literal"));def("GraphIndexExpression").bases("Expression").build("index").field("index",geq(0))},{"../lib/shared":89,"../lib/types":90,"./core":78}],84:[function(require,module,exports){var assert=require("assert");var types=require("../main");var getFieldNames=types.getFieldNames;var getFieldValue=types.getFieldValue;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isDate=types.builtInTypes.Date;var isRegExp=types.builtInTypes.RegExp;var hasOwn=Object.prototype.hasOwnProperty;function astNodesAreEquivalent(a,b,problemPath){if(isArray.check(problemPath)){problemPath.length=0}else{problemPath=null}return areEquivalent(a,b,problemPath)}astNodesAreEquivalent.assert=function(a,b){var problemPath=[];if(!astNodesAreEquivalent(a,b,problemPath)){if(problemPath.length===0){assert.strictEqual(a,b)}else{assert.ok(false,"Nodes differ in the following path: "+problemPath.map(subscriptForProperty).join(""))}}};function subscriptForProperty(property){if(/[_$a-z][_$a-z0-9]*/i.test(property)){return"."+property}return"["+JSON.stringify(property)+"]"}function areEquivalent(a,b,problemPath){if(a===b){return true}if(isArray.check(a)){return arraysAreEquivalent(a,b,problemPath)}if(isObject.check(a)){return objectsAreEquivalent(a,b,problemPath)}if(isDate.check(a)){return isDate.check(b)&&+a===+b}if(isRegExp.check(a)){return isRegExp.check(b)&&(a.source===b.source&&a.global===b.global&&a.multiline===b.multiline&&a.ignoreCase===b.ignoreCase)}return a==b}function arraysAreEquivalent(a,b,problemPath){isArray.assert(a);var aLength=a.length;if(!isArray.check(b)||b.length!==aLength){if(problemPath){problemPath.push("length")}return false}for(var i=0;i<aLength;++i){if(problemPath){problemPath.push(i)}if(i in a!==i in b){return false}if(!areEquivalent(a[i],b[i],problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),i)}}return true}function objectsAreEquivalent(a,b,problemPath){isObject.assert(a);if(!isObject.check(b)){return false}if(a.type!==b.type){if(problemPath){problemPath.push("type")}return false}var aNames=getFieldNames(a);var aNameCount=aNames.length;var bNames=getFieldNames(b);var bNameCount=bNames.length;if(aNameCount===bNameCount){for(var i=0;i<aNameCount;++i){var name=aNames[i];var aChild=getFieldValue(a,name);var bChild=getFieldValue(b,name);if(problemPath){problemPath.push(name)}if(!areEquivalent(aChild,bChild,problemPath)){return false}if(problemPath){assert.strictEqual(problemPath.pop(),name)}}return true}if(!problemPath){return false}var seenNames=Object.create(null);for(i=0;i<aNameCount;++i){seenNames[aNames[i]]=true}for(i=0;i<bNameCount;++i){name=bNames[i];if(!hasOwn.call(seenNames,name)){problemPath.push(name);return false}delete seenNames[name]}for(name in seenNames){problemPath.push(name);break}return false}module.exports=astNodesAreEquivalent},{"../main":91,assert:93}],85:[function(require,module,exports){var assert=require("assert");var types=require("./types");var n=types.namedTypes;var b=types.builders;var isNumber=types.builtInTypes.number;var isArray=types.builtInTypes.array;var Path=require("./path");var Scope=require("./scope");function NodePath(value,parentPath,name){assert.ok(this instanceof NodePath);Path.call(this,value,parentPath,name)}require("util").inherits(NodePath,Path);var NPp=NodePath.prototype;Object.defineProperties(NPp,{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}}});NPp.replace=function(){delete this.node;delete this.parent;delete this.scope;return Path.prototype.replace.apply(this,arguments)};NPp.prune=function(){var remainingNodePath=this.parent;this.replace();return cleanUpNodesAfterPrune(remainingNodePath)};NPp._computeNode=function(){var value=this.value;if(n.Node.check(value)){return value}var pp=this.parentPath;return pp&&pp.node||null};NPp._computeParent=function(){var value=this.value;var pp=this.parentPath;if(!n.Node.check(value)){while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}if(pp){pp=pp.parentPath}}while(pp&&!n.Node.check(pp.value)){pp=pp.parentPath}return pp||null};NPp._computeScope=function(){var value=this.value;var pp=this.parentPath;var scope=pp&&pp.scope;if(n.Node.check(value)&&Scope.isEstablishedBy(value)){scope=new Scope(this,scope)}return scope||null};NPp.getValueProperty=function(name){return types.getFieldValue(this.value,name)};NPp.needsParens=function(assumeExpressionContext){var pp=this.parentPath;if(!pp){return false}var node=this.value;if(!n.Expression.check(node)){return false}if(node.type==="Identifier"){return false}while(!n.Node.check(pp.value)){pp=pp.parentPath;if(!pp){return false}}var parent=pp.value;switch(node.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return parent.type==="MemberExpression"&&this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":switch(parent.type){case"CallExpression":return this.name==="callee"&&parent.callee===node;case"UnaryExpression":case"SpreadElement":case"SpreadProperty":return true;case"MemberExpression":return this.name==="object"&&parent.object===node;case"BinaryExpression":case"LogicalExpression":var po=parent.operator;var pp=PRECEDENCE[po];var no=node.operator;var np=PRECEDENCE[no];if(pp>np){return true}if(pp===np&&this.name==="right"){assert.strictEqual(parent.right,node);return true}default:return false}case"SequenceExpression":switch(parent.type){case"ForStatement":return false;case"ExpressionStatement":return this.name!=="expression";default:return true}case"YieldExpression":switch(parent.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 parent.type==="MemberExpression"&&isNumber.check(node.value)&&this.name==="object"&&parent.object===node;case"AssignmentExpression":case"ConditionalExpression":switch(parent.type){case"UnaryExpression":case"SpreadElement":case"SpreadProperty":case"BinaryExpression":case"LogicalExpression":return true;case"CallExpression":return this.name==="callee"&&parent.callee===node;case"ConditionalExpression":return this.name==="test"&&parent.test===node;case"MemberExpression":return this.name==="object"&&parent.object===node;default:return false}default:if(parent.type==="NewExpression"&&this.name==="callee"&&parent.callee===node){return containsCallExpression(node)}}if(assumeExpressionContext!==true&&!this.canBeFirstInStatement()&&this.firstInStatement())return true;return false};function isBinary(node){return n.BinaryExpression.check(node)||n.LogicalExpression.check(node)}function isUnaryLike(node){return n.UnaryExpression.check(node)||n.SpreadElement&&n.SpreadElement.check(node)||n.SpreadProperty&&n.SpreadProperty.check(node)}var PRECEDENCE={};[["||"],["&&"],["|"],["^"],["&"],["==","===","!=","!=="],["<",">","<=",">=","in","instanceof"],[">>","<<",">>>"],["+","-"],["*","/","%"]].forEach(function(tier,i){tier.forEach(function(op){PRECEDENCE[op]=i})});function containsCallExpression(node){if(n.CallExpression.check(node)){return true}if(isArray.check(node)){return node.some(containsCallExpression)}if(n.Node.check(node)){return types.someField(node,function(name,child){return containsCallExpression(child)})}return false}NPp.canBeFirstInStatement=function(){var node=this.node;return!n.FunctionExpression.check(node)&&!n.ObjectExpression.check(node)};NPp.firstInStatement=function(){return firstInStatement(this)};function firstInStatement(path){for(var node,parent;path.parent;path=path.parent){node=path.node;parent=path.parent.node;if(n.BlockStatement.check(parent)&&path.parent.name==="body"&&path.name===0){assert.strictEqual(parent.body[0],node);return true}if(n.ExpressionStatement.check(parent)&&path.name==="expression"){assert.strictEqual(parent.expression,node);return true}if(n.SequenceExpression.check(parent)&&path.parent.name==="expressions"&&path.name===0){assert.strictEqual(parent.expressions[0],node);continue}if(n.CallExpression.check(parent)&&path.name==="callee"){assert.strictEqual(parent.callee,node);continue}if(n.MemberExpression.check(parent)&&path.name==="object"){assert.strictEqual(parent.object,node);continue}if(n.ConditionalExpression.check(parent)&&path.name==="test"){assert.strictEqual(parent.test,node);continue}if(isBinary(parent)&&path.name==="left"){assert.strictEqual(parent.left,node);continue}if(n.UnaryExpression.check(parent)&&!parent.prefix&&path.name==="argument"){assert.strictEqual(parent.argument,node);continue}return false}return true}function cleanUpNodesAfterPrune(remainingNodePath){if(n.VariableDeclaration.check(remainingNodePath.node)){var declarations=remainingNodePath.get("declarations").value;if(!declarations||declarations.length===0){return remainingNodePath.prune()}}else if(n.ExpressionStatement.check(remainingNodePath.node)){if(!remainingNodePath.get("expression").value){return remainingNodePath.prune()}}else if(n.IfStatement.check(remainingNodePath.node)){cleanUpIfStatementAfterPrune(remainingNodePath)}return remainingNodePath}function cleanUpIfStatementAfterPrune(ifStatement){var testExpression=ifStatement.get("test").value;var alternate=ifStatement.get("alternate").value;var consequent=ifStatement.get("consequent").value;if(!consequent&&!alternate){var testExpressionStatement=b.expressionStatement(testExpression);ifStatement.replace(testExpressionStatement)}else if(!consequent&&alternate){var negatedTestExpression=b.unaryExpression("!",testExpression,true);if(n.UnaryExpression.check(testExpression)&&testExpression.operator==="!"){negatedTestExpression=testExpression.argument}ifStatement.get("test").replace(negatedTestExpression);ifStatement.get("consequent").replace(alternate);ifStatement.get("alternate").replace()}}module.exports=NodePath},{"./path":87,"./scope":88,"./types":90,assert:93,util:102}],86:[function(require,module,exports){var assert=require("assert");var types=require("./types");var NodePath=require("./node-path");var Node=types.namedTypes.Node;var isArray=types.builtInTypes.array;var isObject=types.builtInTypes.object;var isFunction=types.builtInTypes.function;var hasOwn=Object.prototype.hasOwnProperty;var undefined;function PathVisitor(){assert.ok(this instanceof PathVisitor);this._reusableContextStack=[];this._methodNameTable=computeMethodNameTable(this);this.Context=makeContextConstructor(this)}function computeMethodNameTable(visitor){var typeNames=Object.create(null);for(var methodName in visitor){if(/^visit[A-Z]/.test(methodName)){typeNames[methodName.slice("visit".length)]=true}}var supertypeTable=types.computeSupertypeLookupTable(typeNames);var methodNameTable=Object.create(null);var typeNames=Object.keys(supertypeTable);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];methodName="visit"+supertypeTable[typeName];if(isFunction.check(visitor[methodName])){methodNameTable[typeName]=methodName}}return methodNameTable}PathVisitor.fromMethodsObject=function fromMethodsObject(methods){if(methods instanceof PathVisitor){return methods}if(!isObject.check(methods)){return new PathVisitor}function Visitor(){assert.ok(this instanceof Visitor);PathVisitor.call(this)}var Vp=Visitor.prototype=Object.create(PVp);Vp.constructor=Visitor;extend(Vp,methods);extend(Visitor,PathVisitor);isFunction.assert(Visitor.fromMethodsObject);isFunction.assert(Visitor.visit);return new Visitor};function extend(target,source){for(var property in source){if(hasOwn.call(source,property)){target[property]=source[property]}}return target}PathVisitor.visit=function visit(node,methods){var visitor=PathVisitor.fromMethodsObject(methods);if(node instanceof NodePath){visitor.visit(node);return node.value}var rootPath=new NodePath({root:node});visitor.visit(rootPath.get("root"));return rootPath.value.root};var PVp=PathVisitor.prototype;PVp.visit=function(path){if(this instanceof this.Context){return this.visitor.visit(path)}assert.ok(path instanceof NodePath);var value=path.value;var methodName=Node.check(value)&&this._methodNameTable[value.type];if(methodName){var context=this.acquireContext(path);try{context.invokeVisitorMethod(methodName)}finally{this.releaseContext(context)}}else{visitChildren(path,this)}};function visitChildren(path,visitor){assert.ok(path instanceof NodePath);assert.ok(visitor instanceof PathVisitor);var value=path.value;if(isArray.check(value)){path.each(visitor.visit,visitor)}else if(!isObject.check(value)){}else{var childNames=types.getFieldNames(value);var childCount=childNames.length;var childPaths=[];for(var i=0;i<childCount;++i){var childName=childNames[i];if(!hasOwn.call(value,childName)){value[childName]=types.getFieldValue(value,childName)}childPaths.push(path.get(childName))}for(var i=0;i<childCount;++i){visitor.visit(childPaths[i])}}}PVp.acquireContext=function(path){if(this._reusableContextStack.length===0){return new this.Context(path)}return this._reusableContextStack.pop().reset(path)};PVp.releaseContext=function(context){assert.ok(context instanceof this.Context);this._reusableContextStack.push(context);context.currentPath=null};function makeContextConstructor(visitor){function Context(path){assert.ok(this instanceof Context);assert.ok(this instanceof PathVisitor);assert.ok(path instanceof NodePath);Object.defineProperty(this,"visitor",{value:visitor,writable:false,enumerable:true,configurable:false});this.currentPath=path;this.needToCallTraverse=true;Object.seal(this)}assert.ok(visitor instanceof PathVisitor);var Cp=Context.prototype=Object.create(visitor);Cp.constructor=Context;extend(Cp,sharedContextProtoMethods);return Context}var sharedContextProtoMethods=Object.create(null);sharedContextProtoMethods.reset=function reset(path){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);this.currentPath=path;this.needToCallTraverse=true;return this};sharedContextProtoMethods.invokeVisitorMethod=function invokeVisitorMethod(methodName){assert.ok(this instanceof this.Context);assert.ok(this.currentPath instanceof NodePath);var result=this.visitor[methodName].call(this,this.currentPath);if(result===false){this.needToCallTraverse=false}else if(result!==undefined){this.currentPath=this.currentPath.replace(result)[0];if(this.needToCallTraverse){this.traverse(this.currentPath)}}assert.strictEqual(this.needToCallTraverse,false,"Must either call this.traverse or return false in "+methodName)};sharedContextProtoMethods.traverse=function traverse(path,newVisitor){assert.ok(this instanceof this.Context);assert.ok(path instanceof NodePath);assert.ok(this.currentPath instanceof NodePath);this.needToCallTraverse=false;visitChildren(path,PathVisitor.fromMethodsObject(newVisitor||this.visitor))};module.exports=PathVisitor},{"./node-path":85,"./types":90,assert:93}],87:[function(require,module,exports){var assert=require("assert");var Op=Object.prototype;var hasOwn=Op.hasOwnProperty;var types=require("./types");var isArray=types.builtInTypes.array;var isNumber=types.builtInTypes.number;var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;function Path(value,parentPath,name){assert.ok(this instanceof Path);if(parentPath){assert.ok(parentPath instanceof Path)}else{parentPath=null;name=null}this.value=value;this.parentPath=parentPath;this.name=name;this.__childCache=null}var Pp=Path.prototype;function getChildCache(path){return path.__childCache||(path.__childCache=Object.create(null))}function getChildPath(path,name){var cache=getChildCache(path);var actualChildValue=path.getValueProperty(name);var childPath=cache[name];if(!hasOwn.call(cache,name)||childPath.value!==actualChildValue){childPath=cache[name]=new path.constructor(actualChildValue,path,name)}return childPath}Pp.getValueProperty=function getValueProperty(name){return this.value[name]};Pp.get=function get(name){var path=this;var names=arguments;var count=names.length;for(var i=0;i<count;++i){path=getChildPath(path,names[i])}return path};Pp.each=function each(callback,context){var childPaths=[];var len=this.value.length;var i=0;for(var i=0;i<len;++i){if(hasOwn.call(this.value,i)){childPaths[i]=this.get(i)}}context=context||this;for(i=0;i<len;++i){if(hasOwn.call(childPaths,i)){callback.call(context,childPaths[i])}}};Pp.map=function map(callback,context){var result=[];this.each(function(childPath){result.push(callback.call(this,childPath))},context);return result};Pp.filter=function filter(callback,context){var result=[];this.each(function(childPath){if(callback.call(this,childPath)){result.push(childPath)}},context);return result};function emptyMoves(){}function getMoves(path,offset,start,end){isArray.assert(path.value);if(offset===0){return emptyMoves}var length=path.value.length;if(length<1){return emptyMoves}var argc=arguments.length;if(argc===2){start=0;end=length}else if(argc===3){start=Math.max(start,0);end=length}else{start=Math.max(start,0);end=Math.min(end,length)}isNumber.assert(start);isNumber.assert(end);var moves=Object.create(null);var cache=getChildCache(path);for(var i=start;i<end;++i){if(hasOwn.call(path.value,i)){var childPath=path.get(i);assert.strictEqual(childPath.name,i);var newIndex=i+offset;childPath.name=newIndex;moves[newIndex]=childPath;delete cache[i]}}delete cache.length;return function(){for(var newIndex in moves){var childPath=moves[newIndex];assert.strictEqual(childPath.name,+newIndex);cache[newIndex]=childPath;path.value[newIndex]=childPath.value}}}Pp.shift=function shift(){var move=getMoves(this,-1);var result=this.value.shift();move();return result};Pp.unshift=function unshift(node){var move=getMoves(this,arguments.length);var result=this.value.unshift.apply(this.value,arguments);move();return result};Pp.push=function push(node){isArray.assert(this.value);delete getChildCache(this).length;return this.value.push.apply(this.value,arguments)};Pp.pop=function pop(){isArray.assert(this.value);var cache=getChildCache(this);delete cache[this.value.length-1];delete cache.length;return this.value.pop()};Pp.insertAt=function insertAt(index,node){var argc=arguments.length;var move=getMoves(this,argc-1,index);if(move===emptyMoves){return this}index=Math.max(index,0);for(var i=1;i<argc;++i){this.value[index+i-1]=arguments[i]}move();return this};Pp.insertBefore=function insertBefore(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};Pp.insertAfter=function insertAfter(node){var pp=this.parentPath;var argc=arguments.length;var insertAtArgs=[this.name+1];for(var i=0;i<argc;++i){insertAtArgs.push(arguments[i])}return pp.insertAt.apply(pp,insertAtArgs)};function repairRelationshipWithParent(path){assert.ok(path instanceof Path);var pp=path.parentPath;if(!pp){return path}var parentValue=pp.value;var parentCache=getChildCache(pp);if(parentValue[path.name]===path.value){parentCache[path.name]=path}else if(isArray.check(parentValue)){var i=parentValue.indexOf(path.value);if(i>=0){parentCache[path.name=i]=path}}else{parentValue[path.name]=path.value;parentCache[path.name]=path}assert.strictEqual(parentValue[path.name],path.value);assert.strictEqual(path.parentPath.get(path.name),path);return path}Pp.replace=function replace(replacement){var results=[];var parentValue=this.parentPath.value;var parentCache=getChildCache(this.parentPath);var count=arguments.length;repairRelationshipWithParent(this);if(isArray.check(parentValue)){var originalLength=parentValue.length;var move=getMoves(this.parentPath,count-1,this.name+1);var spliceArgs=[this.name,1];for(var i=0;i<count;++i){spliceArgs.push(arguments[i])}var splicedOut=parentValue.splice.apply(parentValue,spliceArgs);assert.strictEqual(splicedOut[0],this.value);assert.strictEqual(parentValue.length,originalLength-1+count);move();if(count===0){delete this.value;delete parentCache[this.name];this.__childCache=null}else{assert.strictEqual(parentValue[this.name],replacement);if(this.value!==replacement){this.value=replacement;this.__childCache=null}for(i=0;i<count;++i){results.push(this.parentPath.get(this.name+i))}assert.strictEqual(results[0],this)}}else if(count===1){if(this.value!==replacement){this.__childCache=null}this.value=parentValue[this.name]=replacement;results.push(this)}else if(count===0){delete parentValue[this.name];delete this.value;this.__childCache=null}else{assert.ok(false,"Could not replace path")}return results};module.exports=Path},{"./types":90,assert:93}],88:[function(require,module,exports){var assert=require("assert");var types=require("./types");var Type=types.Type;var namedTypes=types.namedTypes;var Node=namedTypes.Node;var Expression=namedTypes.Expression;var isArray=types.builtInTypes.array;var hasOwn=Object.prototype.hasOwnProperty;var b=types.builders;function Scope(path,parentScope){assert.ok(this instanceof Scope);assert.ok(path instanceof require("./node-path"));ScopeType.assert(path.value);var depth;if(parentScope){assert.ok(parentScope instanceof Scope);depth=parentScope.depth+1}else{parentScope=null;depth=0}Object.defineProperties(this,{path:{value:path},node:{value:path.value},isGlobal:{value:!parentScope,enumerable:true},depth:{value:depth},parent:{value:parentScope},bindings:{value:{}}})}var scopeTypes=[namedTypes.Program,namedTypes.Function,namedTypes.CatchClause];var ScopeType=Type.or.apply(Type,scopeTypes);Scope.isEstablishedBy=function(node){return ScopeType.check(node)};var Sp=Scope.prototype;Sp.didScan=false;Sp.declares=function(name){this.scan();return hasOwn.call(this.bindings,name)};Sp.declareTemporary=function(prefix){if(prefix){assert.ok(/^[a-z$_]/i.test(prefix),prefix)}else{prefix="t$"}prefix+=this.depth.toString(36)+"$";this.scan();var index=0;while(this.declares(prefix+index)){++index}var name=prefix+index;return this.bindings[name]=types.builders.identifier(name)};Sp.injectTemporary=function(identifier,init){identifier||(identifier=this.declareTemporary());var bodyPath=this.path.get("body");if(namedTypes.BlockStatement.check(bodyPath.value)){bodyPath=bodyPath.get("body")}bodyPath.unshift(b.variableDeclaration("var",[b.variableDeclarator(identifier,init||null)]));return identifier};Sp.scan=function(force){if(force||!this.didScan){for(var name in this.bindings){delete this.bindings[name]}scanScope(this.path,this.bindings);this.didScan=true}};Sp.getBindings=function(){this.scan();return this.bindings};function scanScope(path,bindings){var node=path.value;ScopeType.assert(node);if(namedTypes.CatchClause.check(node)){addPattern(path.get("param"),bindings)}else{recursiveScanScope(path,bindings)}}function recursiveScanScope(path,bindings){var node=path.value;if(path.parent&&namedTypes.FunctionExpression.check(path.parent.node)&&path.parent.node.id){addPattern(path.parent.get("id"),bindings)}if(!node){}else if(isArray.check(node)){path.each(function(childPath){recursiveScanChild(childPath,bindings)})}else if(namedTypes.Function.check(node)){path.get("params").each(function(paramPath){addPattern(paramPath,bindings)});recursiveScanChild(path.get("body"),bindings)}else if(namedTypes.VariableDeclarator.check(node)){addPattern(path.get("id"),bindings);recursiveScanChild(path.get("init"),bindings)}else if(node.type==="ImportSpecifier"||node.type==="ImportNamespaceSpecifier"||node.type==="ImportDefaultSpecifier"){addPattern(node.name?path.get("name"):path.get("id"),bindings)}else if(Node.check(node)&&!Expression.check(node)){types.eachField(node,function(name,child){var childPath=path.get(name);assert.strictEqual(childPath.value,child);recursiveScanChild(childPath,bindings)})}}function recursiveScanChild(path,bindings){var node=path.value;if(!node||Expression.check(node)){}else if(namedTypes.FunctionDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(namedTypes.ClassDeclaration&&namedTypes.ClassDeclaration.check(node)){addPattern(path.get("id"),bindings)}else if(ScopeType.check(node)){if(namedTypes.CatchClause.check(node)){var catchParamName=node.param.name;var hadBinding=hasOwn.call(bindings,catchParamName);recursiveScanScope(path.get("body"),bindings);if(!hadBinding){delete bindings[catchParamName]}}}else{recursiveScanScope(path,bindings)}}function addPattern(patternPath,bindings){var pattern=patternPath.value;namedTypes.Pattern.assert(pattern);if(namedTypes.Identifier.check(pattern)){if(hasOwn.call(bindings,pattern.name)){bindings[pattern.name].push(patternPath)}else{bindings[pattern.name]=[patternPath]}}else if(namedTypes.SpreadElement&&namedTypes.SpreadElement.check(pattern)){addPattern(patternPath.get("argument"),bindings)}}Sp.lookup=function(name){for(var scope=this;scope;scope=scope.parent)if(scope.declares(name))break;return scope};Sp.getGlobalScope=function(){var scope=this;while(!scope.isGlobal)scope=scope.parent;return scope};module.exports=Scope},{"./node-path":85,"./types":90,assert:93}],89:[function(require,module,exports){var types=require("../lib/types");var Type=types.Type;var builtin=types.builtInTypes;var isNumber=builtin.number;exports.geq=function(than){return new Type(function(value){return isNumber.check(value)&&value>=than},isNumber+" >= "+than)};exports.defaults={"null":function(){return null},emptyArray:function(){return[]},"false":function(){return false},"true":function(){return true},undefined:function(){}};var naiveIsPrimitive=Type.or(builtin.string,builtin.number,builtin.boolean,builtin.null,builtin.undefined);exports.isPrimitive=new Type(function(value){if(value===null)return true;var type=typeof value;return!(type==="object"||type==="function")},naiveIsPrimitive.toString())},{"../lib/types":90}],90:[function(require,module,exports){var assert=require("assert");var Ap=Array.prototype;var slice=Ap.slice;var map=Ap.map;var each=Ap.forEach;var Op=Object.prototype;var objToStr=Op.toString;var funObjStr=objToStr.call(function(){});var strObjStr=objToStr.call("");var hasOwn=Op.hasOwnProperty;function Type(check,name){var self=this;assert.ok(self instanceof Type,self);assert.strictEqual(objToStr.call(check),funObjStr,check+" is not a function");var nameObjStr=objToStr.call(name);assert.ok(nameObjStr===funObjStr||nameObjStr===strObjStr,name+" is neither a function nor a string");Object.defineProperties(self,{name:{value:name},check:{value:function(value,deep){var result=check.call(self,value,deep);if(!result&&deep&&objToStr.call(deep)===funObjStr)deep(self,value);return result}}})}var Tp=Type.prototype;exports.Type=Type;Tp.assert=function(value,deep){if(!this.check(value,deep)){var str=shallowStringify(value);assert.ok(false,str+" does not match type "+this);return false}return true};function shallowStringify(value){if(isObject.check(value))return"{"+Object.keys(value).map(function(key){return key+": "+value[key]}).join(", ")+"}";if(isArray.check(value))return"["+value.map(shallowStringify).join(", ")+"]";return JSON.stringify(value)}Tp.toString=function(){var name=this.name;if(isString.check(name))return name;if(isFunction.check(name))return name.call(this)+"";return name+" type"};var builtInTypes={};exports.builtInTypes=builtInTypes;function defBuiltInType(example,name){var objStr=objToStr.call(example);Object.defineProperty(builtInTypes,name,{enumerable:true,value:new Type(function(value){return objToStr.call(value)===objStr},name)});return builtInTypes[name]}var isString=defBuiltInType("","string");var isFunction=defBuiltInType(function(){},"function");var isArray=defBuiltInType([],"array");var isObject=defBuiltInType({},"object");var isRegExp=defBuiltInType(/./,"RegExp");var isDate=defBuiltInType(new Date,"Date");var isNumber=defBuiltInType(3,"number");var isBoolean=defBuiltInType(true,"boolean");var isNull=defBuiltInType(null,"null");var isUndefined=defBuiltInType(void 0,"undefined");function toType(from,name){if(from instanceof Type)return from;if(from instanceof Def)return from.type;if(isArray.check(from))return Type.fromArray(from);if(isObject.check(from))return Type.fromObject(from);if(isFunction.check(from))return new Type(from,name);return new Type(function(value){return value===from},isUndefined.check(name)?function(){return from+""}:name)}Type.or=function(){var types=[];var len=arguments.length;for(var i=0;i<len;++i)types.push(toType(arguments[i]));return new Type(function(value,deep){for(var i=0;i<len;++i)if(types[i].check(value,deep))return true;return false},function(){return types.join(" | ")})};Type.fromArray=function(arr){assert.ok(isArray.check(arr));assert.strictEqual(arr.length,1,"only one element type is permitted for typed arrays");return toType(arr[0]).arrayOf()};Tp.arrayOf=function(){var elemType=this;return new Type(function(value,deep){return isArray.check(value)&&value.every(function(elem){return elemType.check(elem,deep)})},function(){return"["+elemType+"]"})};Type.fromObject=function(obj){var fields=Object.keys(obj).map(function(name){return new Field(name,obj[name])});return new Type(function(value,deep){return isObject.check(value)&&fields.every(function(field){return field.type.check(value[field.name],deep)})},function(){return"{ "+fields.join(", ")+" }"})};function Field(name,type,defaultFn,hidden){var self=this;assert.ok(self instanceof Field);isString.assert(name); type=toType(type);var properties={name:{value:name},type:{value:type},hidden:{value:!!hidden}};if(isFunction.check(defaultFn)){properties.defaultFn={value:defaultFn}}Object.defineProperties(self,properties)}var Fp=Field.prototype;Fp.toString=function(){return JSON.stringify(this.name)+": "+this.type};Fp.getValue=function(obj){var value=obj[this.name];if(!isUndefined.check(value))return value;if(this.defaultFn)value=this.defaultFn.call(obj);return value};Type.def=function(typeName){isString.assert(typeName);return hasOwn.call(defCache,typeName)?defCache[typeName]:defCache[typeName]=new Def(typeName)};var defCache=Object.create(null);function Def(typeName){var self=this;assert.ok(self instanceof Def);Object.defineProperties(self,{typeName:{value:typeName},baseNames:{value:[]},ownFields:{value:Object.create(null)},allSupertypes:{value:Object.create(null)},supertypeList:{value:[]},allFields:{value:Object.create(null)},fieldNames:{value:[]},type:{value:new Type(function(value,deep){return self.check(value,deep)},typeName)}})}Def.fromValue=function(value){if(value&&typeof value==="object"){var type=value.type;if(typeof type==="string"&&hasOwn.call(defCache,type)){var d=defCache[type];if(d.finalized){return d}}}return null};var Dp=Def.prototype;Dp.isSupertypeOf=function(that){if(that instanceof Def){assert.strictEqual(this.finalized,true);assert.strictEqual(that.finalized,true);return hasOwn.call(that.allSupertypes,this.typeName)}else{assert.ok(false,that+" is not a Def")}};exports.getSupertypeNames=function(typeName){assert.ok(hasOwn.call(defCache,typeName));var d=defCache[typeName];assert.strictEqual(d.finalized,true);return d.supertypeList.slice(1)};exports.computeSupertypeLookupTable=function(candidates){var table={};var typeNames=Object.keys(defCache);var typeNameCount=typeNames.length;for(var i=0;i<typeNameCount;++i){var typeName=typeNames[i];var d=defCache[typeName];assert.strictEqual(d.finalized,true);for(var j=0;j<d.supertypeList.length;++j){var superTypeName=d.supertypeList[j];if(hasOwn.call(candidates,superTypeName)){table[typeName]=superTypeName;break}}}return table};Dp.checkAllFields=function(value,deep){var allFields=this.allFields;assert.strictEqual(this.finalized,true);function checkFieldByName(name){var field=allFields[name];var type=field.type;var child=field.getValue(value);return type.check(child,deep)}return isObject.check(value)&&Object.keys(allFields).every(checkFieldByName)};Dp.check=function(value,deep){assert.strictEqual(this.finalized,true,"prematurely checking unfinalized type "+this.typeName);if(!isObject.check(value))return false;var vDef=Def.fromValue(value);if(!vDef){if(this.typeName==="SourceLocation"||this.typeName==="Position"){return this.checkAllFields(value,deep)}return false}if(deep&&vDef===this)return this.checkAllFields(value,deep);if(!this.isSupertypeOf(vDef))return false;if(!deep)return true;return vDef.checkAllFields(value,deep)&&this.checkAllFields(value,false)};Dp.bases=function(){var bases=this.baseNames;assert.strictEqual(this.finalized,false);each.call(arguments,function(baseName){isString.assert(baseName);if(bases.indexOf(baseName)<0)bases.push(baseName)});return this};Object.defineProperty(Dp,"buildable",{value:false});var builders={};exports.builders=builders;var nodePrototype={};exports.defineMethod=function(name,func){var old=nodePrototype[name];if(isUndefined.check(func)){delete nodePrototype[name]}else{isFunction.assert(func);Object.defineProperty(nodePrototype,name,{enumerable:true,configurable:true,value:func})}return old};Dp.build=function(){var self=this;Object.defineProperty(self,"buildParams",{value:slice.call(arguments),writable:false,enumerable:false,configurable:true});assert.strictEqual(self.finalized,false);isString.arrayOf().assert(self.buildParams);if(self.buildable){return self}self.field("type",self.typeName,function(){return self.typeName});Object.defineProperty(self,"buildable",{value:true});Object.defineProperty(builders,getBuilderName(self.typeName),{enumerable:true,value:function(){var args=arguments;var argc=args.length;var built=Object.create(nodePrototype);assert.ok(self.finalized,"attempting to instantiate unfinalized type "+self.typeName);function add(param,i){if(hasOwn.call(built,param))return;var all=self.allFields;assert.ok(hasOwn.call(all,param),param);var field=all[param];var type=field.type;var value;if(isNumber.check(i)&&i<argc){value=args[i]}else if(field.defaultFn){value=field.defaultFn.call(built)}else{var message="no value or default function given for field "+JSON.stringify(param)+" of "+self.typeName+"("+self.buildParams.map(function(name){return all[name]}).join(", ")+")";assert.ok(false,message)}if(!type.check(value)){assert.ok(false,shallowStringify(value)+" does not match field "+field+" of type "+self.typeName)}built[param]=value}self.buildParams.forEach(function(param,i){add(param,i)});Object.keys(self.allFields).forEach(function(param){add(param)});assert.strictEqual(built.type,self.typeName);return built}});return self};function getBuilderName(typeName){return typeName.replace(/^[A-Z]+/,function(upperCasePrefix){var len=upperCasePrefix.length;switch(len){case 0:return"";case 1:return upperCasePrefix.toLowerCase();default:return upperCasePrefix.slice(0,len-1).toLowerCase()+upperCasePrefix.charAt(len-1)}})}Dp.field=function(name,type,defaultFn,hidden){assert.strictEqual(this.finalized,false);this.ownFields[name]=new Field(name,type,defaultFn,hidden);return this};var namedTypes={};exports.namedTypes=namedTypes;function getFieldNames(object){var d=Def.fromValue(object);if(d){return d.fieldNames.slice(0)}if("type"in object){assert.ok(false,"did not recognize object of type "+JSON.stringify(object.type))}return Object.keys(object)}exports.getFieldNames=getFieldNames;function getFieldValue(object,fieldName){var d=Def.fromValue(object);if(d){var field=d.allFields[fieldName];if(field){return field.getValue(object)}}return object[fieldName]}exports.getFieldValue=getFieldValue;exports.eachField=function(object,callback,context){getFieldNames(object).forEach(function(name){callback.call(this,name,getFieldValue(object,name))},context)};exports.someField=function(object,callback,context){return getFieldNames(object).some(function(name){return callback.call(this,name,getFieldValue(object,name))},context)};Object.defineProperty(Dp,"finalized",{value:false});Dp.finalize=function(){if(!this.finalized){var allFields=this.allFields;var allSupertypes=this.allSupertypes;this.baseNames.forEach(function(name){var def=defCache[name];def.finalize();extend(allFields,def.allFields);extend(allSupertypes,def.allSupertypes)});extend(allFields,this.ownFields);allSupertypes[this.typeName]=this;this.fieldNames.length=0;for(var fieldName in allFields){if(hasOwn.call(allFields,fieldName)&&!allFields[fieldName].hidden){this.fieldNames.push(fieldName)}}Object.defineProperty(namedTypes,this.typeName,{enumerable:true,value:this.type});Object.defineProperty(this,"finalized",{value:true});populateSupertypeList(this.typeName,this.supertypeList)}};function populateSupertypeList(typeName,list){list.length=0;list.push(typeName);var lastSeen=Object.create(null);for(var pos=0;pos<list.length;++pos){typeName=list[pos];var d=defCache[typeName];assert.strictEqual(d.finalized,true);if(hasOwn.call(lastSeen,typeName)){delete list[lastSeen[typeName]]}lastSeen[typeName]=pos;list.push.apply(list,d.baseNames)}for(var to=0,from=to,len=list.length;from<len;++from){if(hasOwn.call(list,from)){list[to++]=list[from]}}list.length=to}function extend(into,from){Object.keys(from).forEach(function(name){into[name]=from[name]});return into}exports.finalize=function(){Object.keys(defCache).forEach(function(name){defCache[name].finalize()})}},{assert:93}],91:[function(require,module,exports){var types=require("./lib/types");require("./def/core");require("./def/es6");require("./def/es7");require("./def/mozilla");require("./def/e4x");require("./def/fb-harmony");types.finalize();exports.Type=types.Type;exports.builtInTypes=types.builtInTypes;exports.namedTypes=types.namedTypes;exports.builders=types.builders;exports.defineMethod=types.defineMethod;exports.getFieldNames=types.getFieldNames;exports.getFieldValue=types.getFieldValue;exports.eachField=types.eachField;exports.someField=types.someField;exports.getSupertypeNames=types.getSupertypeNames;exports.astNodesAreEquivalent=require("./lib/equiv");exports.finalize=types.finalize;exports.NodePath=require("./lib/node-path");exports.PathVisitor=require("./lib/path-visitor");exports.visit=exports.PathVisitor.visit},{"./def/core":78,"./def/e4x":79,"./def/es6":80,"./def/es7":81,"./def/fb-harmony":82,"./def/mozilla":83,"./lib/equiv":84,"./lib/node-path":85,"./lib/path-visitor":86,"./lib/types":90}],92:[function(require,module,exports){},{}],93:[function(require,module,exports){var util=require("util/");var pSlice=Array.prototype.slice;var hasOwn=Object.prototype.hasOwnProperty;var assert=module.exports=ok;assert.AssertionError=function AssertionError(options){this.name="AssertionError";this.actual=options.actual;this.expected=options.expected;this.operator=options.operator;if(options.message){this.message=options.message;this.generatedMessage=false}else{this.message=getMessage(this);this.generatedMessage=true}var stackStartFunction=options.stackStartFunction||fail;if(Error.captureStackTrace){Error.captureStackTrace(this,stackStartFunction)}else{var err=new Error;if(err.stack){var out=err.stack;var fn_name=stackStartFunction.name;var idx=out.indexOf("\n"+fn_name);if(idx>=0){var next_line=out.indexOf("\n",idx+1);out=out.substring(next_line+1)}this.stack=out}}};util.inherits(assert.AssertionError,Error);function replacer(key,value){if(util.isUndefined(value)){return""+value}if(util.isNumber(value)&&(isNaN(value)||!isFinite(value))){return value.toString()}if(util.isFunction(value)||util.isRegExp(value)){return value.toString()}return value}function truncate(s,n){if(util.isString(s)){return s.length<n?s:s.slice(0,n)}else{return s}}function getMessage(self){return truncate(JSON.stringify(self.actual,replacer),128)+" "+self.operator+" "+truncate(JSON.stringify(self.expected,replacer),128)}function fail(actual,expected,message,operator,stackStartFunction){throw new assert.AssertionError({message:message,actual:actual,expected:expected,operator:operator,stackStartFunction:stackStartFunction})}assert.fail=fail;function ok(value,message){if(!value)fail(value,true,message,"==",assert.ok)}assert.ok=ok;assert.equal=function equal(actual,expected,message){if(actual!=expected)fail(actual,expected,message,"==",assert.equal)};assert.notEqual=function notEqual(actual,expected,message){if(actual==expected){fail(actual,expected,message,"!=",assert.notEqual)}};assert.deepEqual=function deepEqual(actual,expected,message){if(!_deepEqual(actual,expected)){fail(actual,expected,message,"deepEqual",assert.deepEqual)}};function _deepEqual(actual,expected){if(actual===expected){return true}else if(util.isBuffer(actual)&&util.isBuffer(expected)){if(actual.length!=expected.length)return false;for(var i=0;i<actual.length;i++){if(actual[i]!==expected[i])return false}return true}else if(util.isDate(actual)&&util.isDate(expected)){return actual.getTime()===expected.getTime()}else if(util.isRegExp(actual)&&util.isRegExp(expected)){return actual.source===expected.source&&actual.global===expected.global&&actual.multiline===expected.multiline&&actual.lastIndex===expected.lastIndex&&actual.ignoreCase===expected.ignoreCase}else if(!util.isObject(actual)&&!util.isObject(expected)){return actual==expected}else{return objEquiv(actual,expected)}}function isArguments(object){return Object.prototype.toString.call(object)=="[object Arguments]"}function objEquiv(a,b){if(util.isNullOrUndefined(a)||util.isNullOrUndefined(b))return false;if(a.prototype!==b.prototype)return false;if(isArguments(a)){if(!isArguments(b)){return false}a=pSlice.call(a);b=pSlice.call(b);return _deepEqual(a,b)}try{var ka=objectKeys(a),kb=objectKeys(b),key,i}catch(e){return false}if(ka.length!=kb.length)return false;ka.sort();kb.sort();for(i=ka.length-1;i>=0;i--){if(ka[i]!=kb[i])return false}for(i=ka.length-1;i>=0;i--){key=ka[i];if(!_deepEqual(a[key],b[key]))return false}return true}assert.notDeepEqual=function notDeepEqual(actual,expected,message){if(_deepEqual(actual,expected)){fail(actual,expected,message,"notDeepEqual",assert.notDeepEqual)}};assert.strictEqual=function strictEqual(actual,expected,message){if(actual!==expected){fail(actual,expected,message,"===",assert.strictEqual)}};assert.notStrictEqual=function notStrictEqual(actual,expected,message){if(actual===expected){fail(actual,expected,message,"!==",assert.notStrictEqual)}};function expectedException(actual,expected){if(!actual||!expected){return false}if(Object.prototype.toString.call(expected)=="[object RegExp]"){return expected.test(actual)}else if(actual instanceof expected){return true}else if(expected.call({},actual)===true){return true}return false}function _throws(shouldThrow,block,expected,message){var actual;if(util.isString(expected)){message=expected;expected=null}try{block()}catch(e){actual=e}message=(expected&&expected.name?" ("+expected.name+").":".")+(message?" "+message:".");if(shouldThrow&&!actual){fail(actual,expected,"Missing expected exception"+message)}if(!shouldThrow&&expectedException(actual,expected)){fail(actual,expected,"Got unwanted exception"+message)}if(shouldThrow&&actual&&expected&&!expectedException(actual,expected)||!shouldThrow&&actual){throw actual}}assert.throws=function(block,error,message){_throws.apply(this,[true].concat(pSlice.call(arguments)))};assert.doesNotThrow=function(block,message){_throws.apply(this,[false].concat(pSlice.call(arguments)))};assert.ifError=function(err){if(err){throw err}};var objectKeys=Object.keys||function(obj){var keys=[];for(var key in obj){if(hasOwn.call(obj,key))keys.push(key)}return keys}},{"util/":102}],94:[function(require,module,exports){var base64=require("base64-js");var ieee754=require("ieee754");var isArray=require("is-array");exports.Buffer=Buffer;exports.SlowBuffer=Buffer;exports.INSPECT_MAX_BYTES=50;Buffer.poolSize=8192;var kMaxLength=1073741823;Buffer.TYPED_ARRAY_SUPPORT=function(){try{var buf=new ArrayBuffer(0);var arr=new Uint8Array(buf);arr.foo=function(){return 42};return 42===arr.foo()&&typeof arr.subarray==="function"&&new Uint8Array(1).subarray(1,1).byteLength===0}catch(e){return false}}();function Buffer(subject,encoding,noZero){if(!(this instanceof Buffer))return new Buffer(subject,encoding,noZero);var type=typeof subject;var length;if(type==="number")length=subject>0?subject>>>0:0;else if(type==="string"){if(encoding==="base64")subject=base64clean(subject);length=Buffer.byteLength(subject,encoding)}else if(type==="object"&&subject!==null){if(subject.type==="Buffer"&&isArray(subject.data))subject=subject.data;length=+subject.length>0?Math.floor(+subject.length):0}else throw new TypeError("must start with number, buffer, array or string");if(this.length>kMaxLength)throw new RangeError("Attempt to allocate Buffer larger than maximum "+"size: 0x"+kMaxLength.toString(16)+" bytes");var buf;if(Buffer.TYPED_ARRAY_SUPPORT){buf=Buffer._augment(new Uint8Array(length))}else{buf=this;buf.length=length;buf._isBuffer=true}var i;if(Buffer.TYPED_ARRAY_SUPPORT&&typeof subject.byteLength==="number"){buf._set(subject)}else if(isArrayish(subject)){if(Buffer.isBuffer(subject)){for(i=0;i<length;i++)buf[i]=subject.readUInt8(i)}else{for(i=0;i<length;i++)buf[i]=(subject[i]%256+256)%256}}else if(type==="string"){buf.write(subject,0,encoding)}else if(type==="number"&&!Buffer.TYPED_ARRAY_SUPPORT&&!noZero){for(i=0;i<length;i++){buf[i]=0}}return buf}Buffer.isBuffer=function(b){return!!(b!=null&&b._isBuffer)};Buffer.compare=function(a,b){if(!Buffer.isBuffer(a)||!Buffer.isBuffer(b))throw new TypeError("Arguments must be Buffers");var x=a.length;var y=b.length;for(var i=0,len=Math.min(x,y);i<len&&a[i]===b[i];i++){}if(i!==len){x=a[i];y=b[i]}if(x<y)return-1;if(y<x)return 1;return 0};Buffer.isEncoding=function(encoding){switch(String(encoding).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}};Buffer.concat=function(list,totalLength){if(!isArray(list))throw new TypeError("Usage: Buffer.concat(list[, length])");if(list.length===0){return new Buffer(0)}else if(list.length===1){return list[0]}var i;if(totalLength===undefined){totalLength=0;for(i=0;i<list.length;i++){totalLength+=list[i].length}}var buf=new Buffer(totalLength);var pos=0;for(i=0;i<list.length;i++){var item=list[i];item.copy(buf,pos);pos+=item.length}return buf};Buffer.byteLength=function(str,encoding){var ret;str=str+"";switch(encoding||"utf8"){case"ascii":case"binary":case"raw":ret=str.length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=str.length*2;break;case"hex":ret=str.length>>>1;break;case"utf8":case"utf-8":ret=utf8ToBytes(str).length;break;case"base64":ret=base64ToBytes(str).length;break;default:ret=str.length}return ret};Buffer.prototype.length=undefined;Buffer.prototype.parent=undefined;Buffer.prototype.toString=function(encoding,start,end){var loweredCase=false;start=start>>>0;end=end===undefined||end===Infinity?this.length:end>>>0;if(!encoding)encoding="utf8";if(start<0)start=0;if(end>this.length)end=this.length;if(end<=start)return"";while(true){switch(encoding){case"hex":return hexSlice(this,start,end);case"utf8":case"utf-8":return utf8Slice(this,start,end);case"ascii":return asciiSlice(this,start,end);case"binary":return binarySlice(this,start,end);case"base64":return base64Slice(this,start,end);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return utf16leSlice(this,start,end);default:if(loweredCase)throw new TypeError("Unknown encoding: "+encoding);encoding=(encoding+"").toLowerCase();loweredCase=true}}};Buffer.prototype.equals=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)===0};Buffer.prototype.inspect=function(){var str="";var max=exports.INSPECT_MAX_BYTES;if(this.length>0){str=this.toString("hex",0,max).match(/.{2}/g).join(" ");if(this.length>max)str+=" ... "}return"<Buffer "+str+">"};Buffer.prototype.compare=function(b){if(!Buffer.isBuffer(b))throw new TypeError("Argument must be a Buffer");return Buffer.compare(this,b)};Buffer.prototype.get=function(offset){console.log(".get() is deprecated. Access using array indexes instead.");return this.readUInt8(offset)};Buffer.prototype.set=function(v,offset){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(v,offset)};function hexWrite(buf,string,offset,length){offset=Number(offset)||0;var remaining=buf.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}var strLen=string.length;if(strLen%2!==0)throw new Error("Invalid hex string");if(length>strLen/2){length=strLen/2}for(var i=0;i<length;i++){var byte=parseInt(string.substr(i*2,2),16);if(isNaN(byte))throw new Error("Invalid hex string");buf[offset+i]=byte}return i}function utf8Write(buf,string,offset,length){var charsWritten=blitBuffer(utf8ToBytes(string),buf,offset,length);return charsWritten}function asciiWrite(buf,string,offset,length){var charsWritten=blitBuffer(asciiToBytes(string),buf,offset,length);return charsWritten}function binaryWrite(buf,string,offset,length){return asciiWrite(buf,string,offset,length)}function base64Write(buf,string,offset,length){var charsWritten=blitBuffer(base64ToBytes(string),buf,offset,length);return charsWritten}function utf16leWrite(buf,string,offset,length){var charsWritten=blitBuffer(utf16leToBytes(string),buf,offset,length);return charsWritten}Buffer.prototype.write=function(string,offset,length,encoding){if(isFinite(offset)){if(!isFinite(length)){encoding=length;length=undefined}}else{var swap=encoding;encoding=offset;offset=length;length=swap}offset=Number(offset)||0;var remaining=this.length-offset;if(!length){length=remaining}else{length=Number(length);if(length>remaining){length=remaining}}encoding=String(encoding||"utf8").toLowerCase();var ret;switch(encoding){case"hex":ret=hexWrite(this,string,offset,length);break;case"utf8":case"utf-8":ret=utf8Write(this,string,offset,length);break;case"ascii":ret=asciiWrite(this,string,offset,length);break;case"binary":ret=binaryWrite(this,string,offset,length);break;case"base64":ret=base64Write(this,string,offset,length);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":ret=utf16leWrite(this,string,offset,length);break;default:throw new TypeError("Unknown encoding: "+encoding)}return ret};Buffer.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function base64Slice(buf,start,end){if(start===0&&end===buf.length){return base64.fromByteArray(buf)}else{return base64.fromByteArray(buf.slice(start,end))}}function utf8Slice(buf,start,end){var res="";var tmp="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){if(buf[i]<=127){res+=decodeUtf8Char(tmp)+String.fromCharCode(buf[i]);tmp=""}else{tmp+="%"+buf[i].toString(16)}}return res+decodeUtf8Char(tmp)}function asciiSlice(buf,start,end){var ret="";end=Math.min(buf.length,end);for(var i=start;i<end;i++){ret+=String.fromCharCode(buf[i])}return ret}function binarySlice(buf,start,end){return asciiSlice(buf,start,end)}function hexSlice(buf,start,end){var len=buf.length;if(!start||start<0)start=0;if(!end||end<0||end>len)end=len;var out="";for(var i=start;i<end;i++){out+=toHex(buf[i])}return out}function utf16leSlice(buf,start,end){var bytes=buf.slice(start,end);var res="";for(var i=0;i<bytes.length;i+=2){res+=String.fromCharCode(bytes[i]+bytes[i+1]*256)}return res}Buffer.prototype.slice=function(start,end){var len=this.length;start=~~start;end=end===undefined?len:~~end;if(start<0){start+=len;if(start<0)start=0}else if(start>len){start=len}if(end<0){end+=len;if(end<0)end=0}else if(end>len){end=len}if(end<start)end=start;if(Buffer.TYPED_ARRAY_SUPPORT){return Buffer._augment(this.subarray(start,end))}else{var sliceLen=end-start;var newBuf=new Buffer(sliceLen,undefined,true);for(var i=0;i<sliceLen;i++){newBuf[i]=this[i+start]}return newBuf}};function checkOffset(offset,ext,length){if(offset%1!==0||offset<0)throw new RangeError("offset is not uint");if(offset+ext>length)throw new RangeError("Trying to access beyond buffer length")}Buffer.prototype.readUInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);return this[offset]};Buffer.prototype.readUInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]|this[offset+1]<<8};Buffer.prototype.readUInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);return this[offset]<<8|this[offset+1]};Buffer.prototype.readUInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return(this[offset]|this[offset+1]<<8|this[offset+2]<<16)+this[offset+3]*16777216};Buffer.prototype.readUInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]*16777216+(this[offset+1]<<16|this[offset+2]<<8|this[offset+3])};Buffer.prototype.readInt8=function(offset,noAssert){if(!noAssert)checkOffset(offset,1,this.length);if(!(this[offset]&128))return this[offset];return(255-this[offset]+1)*-1};Buffer.prototype.readInt16LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset]|this[offset+1]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt16BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,2,this.length);var val=this[offset+1]|this[offset]<<8;return val&32768?val|4294901760:val};Buffer.prototype.readInt32LE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]|this[offset+1]<<8|this[offset+2]<<16|this[offset+3]<<24};Buffer.prototype.readInt32BE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return this[offset]<<24|this[offset+1]<<16|this[offset+2]<<8|this[offset+3]};Buffer.prototype.readFloatLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,true,23,4)};Buffer.prototype.readFloatBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,4,this.length);return ieee754.read(this,offset,false,23,4)};Buffer.prototype.readDoubleLE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,true,52,8)};Buffer.prototype.readDoubleBE=function(offset,noAssert){if(!noAssert)checkOffset(offset,8,this.length);return ieee754.read(this,offset,false,52,8)};function checkInt(buf,value,offset,ext,max,min){if(!Buffer.isBuffer(buf))throw new TypeError("buffer must be a Buffer instance");if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}Buffer.prototype.writeUInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,255,0);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);this[offset]=value;return offset+1};function objectWriteUInt16(buf,value,offset,littleEndian){if(value<0)value=65535+value+1;for(var i=0,j=Math.min(buf.length-offset,2);i<j;i++){buf[offset+i]=(value&255<<8*(littleEndian?i:1-i))>>>(littleEndian?i:1-i)*8}}Buffer.prototype.writeUInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeUInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,65535,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};function objectWriteUInt32(buf,value,offset,littleEndian){if(value<0)value=4294967295+value+1;for(var i=0,j=Math.min(buf.length-offset,4);i<j;i++){buf[offset+i]=value>>>(littleEndian?i:3-i)*8&255}}Buffer.prototype.writeUInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset+3]=value>>>24;this[offset+2]=value>>>16;this[offset+1]=value>>>8;this[offset]=value}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeUInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,4294967295,0);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};Buffer.prototype.writeInt8=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,1,127,-128);if(!Buffer.TYPED_ARRAY_SUPPORT)value=Math.floor(value);if(value<0)value=255+value+1;this[offset]=value;return offset+1};Buffer.prototype.writeInt16LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8}else objectWriteUInt16(this,value,offset,true);return offset+2};Buffer.prototype.writeInt16BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,2,32767,-32768);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>8;this[offset+1]=value}else objectWriteUInt16(this,value,offset,false);return offset+2};Buffer.prototype.writeInt32LE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value;this[offset+1]=value>>>8;this[offset+2]=value>>>16;this[offset+3]=value>>>24}else objectWriteUInt32(this,value,offset,true);return offset+4};Buffer.prototype.writeInt32BE=function(value,offset,noAssert){value=+value;offset=offset>>>0;if(!noAssert)checkInt(this,value,offset,4,2147483647,-2147483648);if(value<0)value=4294967295+value+1;if(Buffer.TYPED_ARRAY_SUPPORT){this[offset]=value>>>24;this[offset+1]=value>>>16;this[offset+2]=value>>>8;this[offset+3]=value}else objectWriteUInt32(this,value,offset,false);return offset+4};function checkIEEE754(buf,value,offset,ext,max,min){if(value>max||value<min)throw new TypeError("value is out of bounds");if(offset+ext>buf.length)throw new TypeError("index out of range")}function writeFloat(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,4,3.4028234663852886e38,-3.4028234663852886e38);ieee754.write(buf,value,offset,littleEndian,23,4);return offset+4}Buffer.prototype.writeFloatLE=function(value,offset,noAssert){return writeFloat(this,value,offset,true,noAssert)};Buffer.prototype.writeFloatBE=function(value,offset,noAssert){return writeFloat(this,value,offset,false,noAssert)};function writeDouble(buf,value,offset,littleEndian,noAssert){if(!noAssert)checkIEEE754(buf,value,offset,8,1.7976931348623157e308,-1.7976931348623157e308);ieee754.write(buf,value,offset,littleEndian,52,8);return offset+8}Buffer.prototype.writeDoubleLE=function(value,offset,noAssert){return writeDouble(this,value,offset,true,noAssert)};Buffer.prototype.writeDoubleBE=function(value,offset,noAssert){return writeDouble(this,value,offset,false,noAssert)};Buffer.prototype.copy=function(target,target_start,start,end){var source=this;if(!start)start=0;if(!end&&end!==0)end=this.length;if(!target_start)target_start=0;if(end===start)return;if(target.length===0||source.length===0)return;if(end<start)throw new TypeError("sourceEnd < sourceStart");if(target_start<0||target_start>=target.length)throw new TypeError("targetStart out of bounds");if(start<0||start>=source.length)throw new TypeError("sourceStart out of bounds");if(end<0||end>source.length)throw new TypeError("sourceEnd out of bounds");if(end>this.length)end=this.length;if(target.length-target_start<end-start)end=target.length-target_start+start;var len=end-start;if(len<1e3||!Buffer.TYPED_ARRAY_SUPPORT){for(var i=0;i<len;i++){target[i+target_start]=this[i+start]}}else{target._set(this.subarray(start,start+len),target_start)}};Buffer.prototype.fill=function(value,start,end){if(!value)value=0;if(!start)start=0;if(!end)end=this.length;if(end<start)throw new TypeError("end < start");if(end===start)return;if(this.length===0)return;if(start<0||start>=this.length)throw new TypeError("start out of bounds");if(end<0||end>this.length)throw new TypeError("end out of bounds");var i;if(typeof value==="number"){for(i=start;i<end;i++){this[i]=value}}else{var bytes=utf8ToBytes(value.toString());var len=bytes.length;for(i=start;i<end;i++){this[i]=bytes[i%len]}}return this};Buffer.prototype.toArrayBuffer=function(){if(typeof Uint8Array!=="undefined"){if(Buffer.TYPED_ARRAY_SUPPORT){return new Buffer(this).buffer}else{var buf=new Uint8Array(this.length);for(var i=0,len=buf.length;i<len;i+=1){buf[i]=this[i]}return buf.buffer}}else{throw new TypeError("Buffer.toArrayBuffer not supported in this browser")}};var BP=Buffer.prototype;Buffer._augment=function(arr){arr.constructor=Buffer;arr._isBuffer=true;arr._get=arr.get;arr._set=arr.set;arr.get=BP.get;arr.set=BP.set;arr.write=BP.write;arr.toString=BP.toString;arr.toLocaleString=BP.toString;arr.toJSON=BP.toJSON;arr.equals=BP.equals;arr.compare=BP.compare;arr.copy=BP.copy;arr.slice=BP.slice;arr.readUInt8=BP.readUInt8;arr.readUInt16LE=BP.readUInt16LE;arr.readUInt16BE=BP.readUInt16BE;arr.readUInt32LE=BP.readUInt32LE;arr.readUInt32BE=BP.readUInt32BE;arr.readInt8=BP.readInt8;arr.readInt16LE=BP.readInt16LE;arr.readInt16BE=BP.readInt16BE;arr.readInt32LE=BP.readInt32LE;arr.readInt32BE=BP.readInt32BE;arr.readFloatLE=BP.readFloatLE;arr.readFloatBE=BP.readFloatBE;arr.readDoubleLE=BP.readDoubleLE;arr.readDoubleBE=BP.readDoubleBE; arr.writeUInt8=BP.writeUInt8;arr.writeUInt16LE=BP.writeUInt16LE;arr.writeUInt16BE=BP.writeUInt16BE;arr.writeUInt32LE=BP.writeUInt32LE;arr.writeUInt32BE=BP.writeUInt32BE;arr.writeInt8=BP.writeInt8;arr.writeInt16LE=BP.writeInt16LE;arr.writeInt16BE=BP.writeInt16BE;arr.writeInt32LE=BP.writeInt32LE;arr.writeInt32BE=BP.writeInt32BE;arr.writeFloatLE=BP.writeFloatLE;arr.writeFloatBE=BP.writeFloatBE;arr.writeDoubleLE=BP.writeDoubleLE;arr.writeDoubleBE=BP.writeDoubleBE;arr.fill=BP.fill;arr.inspect=BP.inspect;arr.toArrayBuffer=BP.toArrayBuffer;return arr};var INVALID_BASE64_RE=/[^+\/0-9A-z]/g;function base64clean(str){str=stringtrim(str).replace(INVALID_BASE64_RE,"");while(str.length%4!==0){str=str+"="}return str}function stringtrim(str){if(str.trim)return str.trim();return str.replace(/^\s+|\s+$/g,"")}function isArrayish(subject){return isArray(subject)||Buffer.isBuffer(subject)||subject&&typeof subject==="object"&&typeof subject.length==="number"}function toHex(n){if(n<16)return"0"+n.toString(16);return n.toString(16)}function utf8ToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){var b=str.charCodeAt(i);if(b<=127){byteArray.push(b)}else{var start=i;if(b>=55296&&b<=57343)i++;var h=encodeURIComponent(str.slice(start,i+1)).substr(1).split("%");for(var j=0;j<h.length;j++){byteArray.push(parseInt(h[j],16))}}}return byteArray}function asciiToBytes(str){var byteArray=[];for(var i=0;i<str.length;i++){byteArray.push(str.charCodeAt(i)&255)}return byteArray}function utf16leToBytes(str){var c,hi,lo;var byteArray=[];for(var i=0;i<str.length;i++){c=str.charCodeAt(i);hi=c>>8;lo=c%256;byteArray.push(lo);byteArray.push(hi)}return byteArray}function base64ToBytes(str){return base64.toByteArray(str)}function blitBuffer(src,dst,offset,length){for(var i=0;i<length;i++){if(i+offset>=dst.length||i>=src.length)break;dst[i+offset]=src[i]}return i}function decodeUtf8Char(str){try{return decodeURIComponent(str)}catch(err){return String.fromCharCode(65533)}}},{"base64-js":95,ieee754:96,"is-array":97}],95:[function(require,module,exports){var lookup="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";(function(exports){"use strict";var Arr=typeof Uint8Array!=="undefined"?Uint8Array:Array;var PLUS="+".charCodeAt(0);var SLASH="/".charCodeAt(0);var NUMBER="0".charCodeAt(0);var LOWER="a".charCodeAt(0);var UPPER="A".charCodeAt(0);function decode(elt){var code=elt.charCodeAt(0);if(code===PLUS)return 62;if(code===SLASH)return 63;if(code<NUMBER)return-1;if(code<NUMBER+10)return code-NUMBER+26+26;if(code<UPPER+26)return code-UPPER;if(code<LOWER+26)return code-LOWER+26}function b64ToByteArray(b64){var i,j,l,tmp,placeHolders,arr;if(b64.length%4>0){throw new Error("Invalid string. Length must be a multiple of 4")}var len=b64.length;placeHolders="="===b64.charAt(len-2)?2:"="===b64.charAt(len-1)?1:0;arr=new Arr(b64.length*3/4-placeHolders);l=placeHolders>0?b64.length-4:b64.length;var L=0;function push(v){arr[L++]=v}for(i=0,j=0;i<l;i+=4,j+=3){tmp=decode(b64.charAt(i))<<18|decode(b64.charAt(i+1))<<12|decode(b64.charAt(i+2))<<6|decode(b64.charAt(i+3));push((tmp&16711680)>>16);push((tmp&65280)>>8);push(tmp&255)}if(placeHolders===2){tmp=decode(b64.charAt(i))<<2|decode(b64.charAt(i+1))>>4;push(tmp&255)}else if(placeHolders===1){tmp=decode(b64.charAt(i))<<10|decode(b64.charAt(i+1))<<4|decode(b64.charAt(i+2))>>2;push(tmp>>8&255);push(tmp&255)}return arr}function uint8ToBase64(uint8){var i,extraBytes=uint8.length%3,output="",temp,length;function encode(num){return lookup.charAt(num)}function tripletToBase64(num){return encode(num>>18&63)+encode(num>>12&63)+encode(num>>6&63)+encode(num&63)}for(i=0,length=uint8.length-extraBytes;i<length;i+=3){temp=(uint8[i]<<16)+(uint8[i+1]<<8)+uint8[i+2];output+=tripletToBase64(temp)}switch(extraBytes){case 1:temp=uint8[uint8.length-1];output+=encode(temp>>2);output+=encode(temp<<4&63);output+="==";break;case 2:temp=(uint8[uint8.length-2]<<8)+uint8[uint8.length-1];output+=encode(temp>>10);output+=encode(temp>>4&63);output+=encode(temp<<2&63);output+="=";break}return output}exports.toByteArray=b64ToByteArray;exports.fromByteArray=uint8ToBase64})(typeof exports==="undefined"?this.base64js={}:exports)},{}],96:[function(require,module,exports){exports.read=function(buffer,offset,isLE,mLen,nBytes){var e,m,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,nBits=-7,i=isLE?nBytes-1:0,d=isLE?-1:1,s=buffer[offset+i];i+=d;e=s&(1<<-nBits)-1;s>>=-nBits;nBits+=eLen;for(;nBits>0;e=e*256+buffer[offset+i],i+=d,nBits-=8);m=e&(1<<-nBits)-1;e>>=-nBits;nBits+=mLen;for(;nBits>0;m=m*256+buffer[offset+i],i+=d,nBits-=8);if(e===0){e=1-eBias}else if(e===eMax){return m?NaN:(s?-1:1)*Infinity}else{m=m+Math.pow(2,mLen);e=e-eBias}return(s?-1:1)*m*Math.pow(2,e-mLen)};exports.write=function(buffer,value,offset,isLE,mLen,nBytes){var e,m,c,eLen=nBytes*8-mLen-1,eMax=(1<<eLen)-1,eBias=eMax>>1,rt=mLen===23?Math.pow(2,-24)-Math.pow(2,-77):0,i=isLE?0:nBytes-1,d=isLE?1:-1,s=value<0||value===0&&1/value<0?1:0;value=Math.abs(value);if(isNaN(value)||value===Infinity){m=isNaN(value)?1:0;e=eMax}else{e=Math.floor(Math.log(value)/Math.LN2);if(value*(c=Math.pow(2,-e))<1){e--;c*=2}if(e+eBias>=1){value+=rt/c}else{value+=rt*Math.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)*Math.pow(2,mLen);e=e+eBias}else{m=value*Math.pow(2,eBias-1)*Math.pow(2,mLen);e=0}}for(;mLen>=8;buffer[offset+i]=m&255,i+=d,m/=256,mLen-=8);e=e<<mLen|m;eLen+=mLen;for(;eLen>0;buffer[offset+i]=e&255,i+=d,e/=256,eLen-=8);buffer[offset+i-d]|=s*128}},{}],97:[function(require,module,exports){var isArray=Array.isArray;var str=Object.prototype.toString;module.exports=isArray||function(val){return!!val&&"[object Array]"==str.call(val)}},{}],98:[function(require,module,exports){if(typeof Object.create==="function"){module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;ctor.prototype=Object.create(superCtor.prototype,{constructor:{value:ctor,enumerable:false,writable:true,configurable:true}})}}else{module.exports=function inherits(ctor,superCtor){ctor.super_=superCtor;var TempCtor=function(){};TempCtor.prototype=superCtor.prototype;ctor.prototype=new TempCtor;ctor.prototype.constructor=ctor}}},{}],99:[function(require,module,exports){(function(process){function normalizeArray(parts,allowAboveRoot){var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==="."){parts.splice(i,1)}else if(last===".."){parts.splice(i,1);up++}else if(up){parts.splice(i,1);up--}}if(allowAboveRoot){for(;up--;up){parts.unshift("..")}}return parts}var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function(filename){return splitPathRe.exec(filename).slice(1)};exports.resolve=function(){var resolvedPath="",resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();if(typeof path!=="string"){throw new TypeError("Arguments to path.resolve must be strings")}else if(!path){continue}resolvedPath=path+"/"+resolvedPath;resolvedAbsolute=path.charAt(0)==="/"}resolvedPath=normalizeArray(filter(resolvedPath.split("/"),function(p){return!!p}),!resolvedAbsolute).join("/");return(resolvedAbsolute?"/":"")+resolvedPath||"."};exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==="/";path=normalizeArray(filter(path.split("/"),function(p){return!!p}),!isAbsolute).join("/");if(!path&&!isAbsolute){path="."}if(path&&trailingSlash){path+="/"}return(isAbsolute?"/":"")+path};exports.isAbsolute=function(path){return path.charAt(0)==="/"};exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=="string"){throw new TypeError("Arguments to path.join must be strings")}return p}).join("/"))};exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start<arr.length;start++){if(arr[start]!=="")break}var end=arr.length-1;for(;end>=0;end--){if(arr[end]!=="")break}if(start>end)return[];return arr.slice(start,end-start+1)}var fromParts=trim(from.split("/"));var toParts=trim(to.split("/"));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i<length;i++){if(fromParts[i]!==toParts[i]){samePartsLength=i;break}}var outputParts=[];for(var i=samePartsLength;i<fromParts.length;i++){outputParts.push("..")}outputParts=outputParts.concat(toParts.slice(samePartsLength));return outputParts.join("/")};exports.sep="/";exports.delimiter=":";exports.dirname=function(path){var result=splitPath(path),root=result[0],dir=result[1];if(!root&&!dir){return"."}if(dir){dir=dir.substr(0,dir.length-1)}return root+dir};exports.basename=function(path,ext){var f=splitPath(path)[2];if(ext&&f.substr(-1*ext.length)===ext){f=f.substr(0,f.length-ext.length)}return f};exports.extname=function(path){return splitPath(path)[3]};function filter(xs,f){if(xs.filter)return xs.filter(f);var res=[];for(var i=0;i<xs.length;i++){if(f(xs[i],i,xs))res.push(xs[i])}return res}var substr="ab".substr(-1)==="b"?function(str,start,len){return str.substr(start,len)}:function(str,start,len){if(start<0)start=str.length+start;return str.substr(start,len)}}).call(this,require("_process"))},{_process:100}],100:[function(require,module,exports){var process=module.exports={};process.nextTick=function(){var canSetImmediate=typeof window!=="undefined"&&window.setImmediate;var canMutationObserver=typeof window!=="undefined"&&window.MutationObserver;var canPost=typeof window!=="undefined"&&window.postMessage&&window.addEventListener;if(canSetImmediate){return function(f){return window.setImmediate(f)}}var queue=[];if(canMutationObserver){var hiddenDiv=document.createElement("div");var observer=new MutationObserver(function(){var queueList=queue.slice();queue.length=0;queueList.forEach(function(fn){fn()})});observer.observe(hiddenDiv,{attributes:true});return function nextTick(fn){if(!queue.length){hiddenDiv.setAttribute("yes","no")}queue.push(fn)}}if(canPost){window.addEventListener("message",function(ev){var source=ev.source;if((source===window||source===null)&&ev.data==="process-tick"){ev.stopPropagation();if(queue.length>0){var fn=queue.shift();fn()}}},true);return function nextTick(fn){queue.push(fn);window.postMessage("process-tick","*")}}return function nextTick(fn){setTimeout(fn,0)}}();process.title="browser";process.browser=true;process.env={};process.argv=[];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")}},{}],101:[function(require,module,exports){module.exports=function isBuffer(arg){return arg&&typeof arg==="object"&&typeof arg.copy==="function"&&typeof arg.fill==="function"&&typeof arg.readUInt8==="function"}},{}],102:[function(require,module,exports){(function(process,global){var formatRegExp=/%[sdj%]/g;exports.format=function(f){if(!isString(f)){var objects=[];for(var i=0;i<arguments.length;i++){objects.push(inspect(arguments[i]))}return objects.join(" ")}var i=1;var args=arguments;var len=args.length;var str=String(f).replace(formatRegExp,function(x){if(x==="%%")return"%";if(i>=len)return x;switch(x){case"%s":return String(args[i++]);case"%d":return Number(args[i++]);case"%j":try{return JSON.stringify(args[i++])}catch(_){return"[Circular]"}default:return x}});for(var x=args[i];i<len;x=args[++i]){if(isNull(x)||!isObject(x)){str+=" "+x}else{str+=" "+inspect(x)}}return str};exports.deprecate=function(fn,msg){if(isUndefined(global.process)){return function(){return exports.deprecate(fn,msg).apply(this,arguments)}}if(process.noDeprecation===true){return fn}var warned=false;function deprecated(){if(!warned){if(process.throwDeprecation){throw new Error(msg)}else if(process.traceDeprecation){console.trace(msg)}else{console.error(msg)}warned=true}return fn.apply(this,arguments)}return deprecated};var debugs={};var debugEnviron;exports.debuglog=function(set){if(isUndefined(debugEnviron))debugEnviron=process.env.NODE_DEBUG||"";set=set.toUpperCase();if(!debugs[set]){if(new RegExp("\\b"+set+"\\b","i").test(debugEnviron)){var pid=process.pid;debugs[set]=function(){var msg=exports.format.apply(exports,arguments);console.error("%s %d: %s",set,pid,msg)}}else{debugs[set]=function(){}}}return debugs[set]};function inspect(obj,opts){var ctx={seen:[],stylize:stylizeNoColor};if(arguments.length>=3)ctx.depth=arguments[2];if(arguments.length>=4)ctx.colors=arguments[3];if(isBoolean(opts)){ctx.showHidden=opts}else if(opts){exports._extend(ctx,opts)}if(isUndefined(ctx.showHidden))ctx.showHidden=false;if(isUndefined(ctx.depth))ctx.depth=2;if(isUndefined(ctx.colors))ctx.colors=false;if(isUndefined(ctx.customInspect))ctx.customInspect=true;if(ctx.colors)ctx.stylize=stylizeWithColor;return formatValue(ctx,obj,ctx.depth)}exports.inspect=inspect;inspect.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]};inspect.styles={special:"cyan",number:"yellow","boolean":"yellow",undefined:"grey","null":"bold",string:"green",date:"magenta",regexp:"red"};function stylizeWithColor(str,styleType){var style=inspect.styles[styleType];if(style){return"["+inspect.colors[style][0]+"m"+str+"["+inspect.colors[style][1]+"m"}else{return str}}function stylizeNoColor(str,styleType){return str}function arrayToHash(array){var hash={};array.forEach(function(val,idx){hash[val]=true});return hash}function formatValue(ctx,value,recurseTimes){if(ctx.customInspect&&value&&isFunction(value.inspect)&&value.inspect!==exports.inspect&&!(value.constructor&&value.constructor.prototype===value)){var ret=value.inspect(recurseTimes,ctx);if(!isString(ret)){ret=formatValue(ctx,ret,recurseTimes)}return ret}var primitive=formatPrimitive(ctx,value);if(primitive){return primitive}var keys=Object.keys(value);var visibleKeys=arrayToHash(keys);if(ctx.showHidden){keys=Object.getOwnPropertyNames(value)}if(isError(value)&&(keys.indexOf("message")>=0||keys.indexOf("description")>=0)){return formatError(value)}if(keys.length===0){if(isFunction(value)){var name=value.name?": "+value.name:"";return ctx.stylize("[Function"+name+"]","special")}if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}if(isDate(value)){return ctx.stylize(Date.prototype.toString.call(value),"date")}if(isError(value)){return formatError(value)}}var base="",array=false,braces=["{","}"];if(isArray(value)){array=true;braces=["[","]"]}if(isFunction(value)){var n=value.name?": "+value.name:"";base=" [Function"+n+"]"}if(isRegExp(value)){base=" "+RegExp.prototype.toString.call(value)}if(isDate(value)){base=" "+Date.prototype.toUTCString.call(value)}if(isError(value)){base=" "+formatError(value)}if(keys.length===0&&(!array||value.length==0)){return braces[0]+base+braces[1]}if(recurseTimes<0){if(isRegExp(value)){return ctx.stylize(RegExp.prototype.toString.call(value),"regexp")}else{return ctx.stylize("[Object]","special")}}ctx.seen.push(value);var output;if(array){output=formatArray(ctx,value,recurseTimes,visibleKeys,keys)}else{output=keys.map(function(key){return formatProperty(ctx,value,recurseTimes,visibleKeys,key,array)})}ctx.seen.pop();return reduceToSingleString(output,base,braces)}function formatPrimitive(ctx,value){if(isUndefined(value))return ctx.stylize("undefined","undefined");if(isString(value)){var simple="'"+JSON.stringify(value).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return ctx.stylize(simple,"string")}if(isNumber(value))return ctx.stylize(""+value,"number");if(isBoolean(value))return ctx.stylize(""+value,"boolean");if(isNull(value))return ctx.stylize("null","null")}function formatError(value){return"["+Error.prototype.toString.call(value)+"]"}function formatArray(ctx,value,recurseTimes,visibleKeys,keys){var output=[];for(var i=0,l=value.length;i<l;++i){if(hasOwnProperty(value,String(i))){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,String(i),true))}else{output.push("")}}keys.forEach(function(key){if(!key.match(/^\d+$/)){output.push(formatProperty(ctx,value,recurseTimes,visibleKeys,key,true))}});return output}function formatProperty(ctx,value,recurseTimes,visibleKeys,key,array){var name,str,desc;desc=Object.getOwnPropertyDescriptor(value,key)||{value:value[key]};if(desc.get){if(desc.set){str=ctx.stylize("[Getter/Setter]","special")}else{str=ctx.stylize("[Getter]","special")}}else{if(desc.set){str=ctx.stylize("[Setter]","special")}}if(!hasOwnProperty(visibleKeys,key)){name="["+key+"]"}if(!str){if(ctx.seen.indexOf(desc.value)<0){if(isNull(recurseTimes)){str=formatValue(ctx,desc.value,null)}else{str=formatValue(ctx,desc.value,recurseTimes-1)}if(str.indexOf("\n")>-1){if(array){str=str.split("\n").map(function(line){return" "+line}).join("\n").substr(2)}else{str="\n"+str.split("\n").map(function(line){return" "+line}).join("\n")}}}else{str=ctx.stylize("[Circular]","special")}}if(isUndefined(name)){if(array&&key.match(/^\d+$/)){return str}name=JSON.stringify(""+key);if(name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)){name=name.substr(1,name.length-2);name=ctx.stylize(name,"name")}else{name=name.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'");name=ctx.stylize(name,"string")}}return name+": "+str}function reduceToSingleString(output,base,braces){var numLinesEst=0;var length=output.reduce(function(prev,cur){numLinesEst++;if(cur.indexOf("\n")>=0)numLinesEst++;return prev+cur.replace(/\u001b\[\d\d?m/g,"").length+1},0);if(length>60){return braces[0]+(base===""?"":base+"\n ")+" "+output.join(",\n ")+" "+braces[1]}return braces[0]+base+" "+output.join(", ")+" "+braces[1]}function isArray(ar){return Array.isArray(ar)}exports.isArray=isArray;function isBoolean(arg){return typeof arg==="boolean"}exports.isBoolean=isBoolean;function isNull(arg){return arg===null}exports.isNull=isNull;function isNullOrUndefined(arg){return arg==null}exports.isNullOrUndefined=isNullOrUndefined;function isNumber(arg){return typeof arg==="number"}exports.isNumber=isNumber;function isString(arg){return typeof arg==="string"}exports.isString=isString;function isSymbol(arg){return typeof arg==="symbol"}exports.isSymbol=isSymbol;function isUndefined(arg){return arg===void 0}exports.isUndefined=isUndefined;function isRegExp(re){return isObject(re)&&objectToString(re)==="[object RegExp]"}exports.isRegExp=isRegExp;function isObject(arg){return typeof arg==="object"&&arg!==null}exports.isObject=isObject;function isDate(d){return isObject(d)&&objectToString(d)==="[object Date]"}exports.isDate=isDate;function isError(e){return isObject(e)&&(objectToString(e)==="[object Error]"||e instanceof Error)}exports.isError=isError;function isFunction(arg){return typeof arg==="function"}exports.isFunction=isFunction;function isPrimitive(arg){return arg===null||typeof arg==="boolean"||typeof arg==="number"||typeof arg==="string"||typeof arg==="symbol"||typeof arg==="undefined"}exports.isPrimitive=isPrimitive;exports.isBuffer=require("./support/isBuffer");function objectToString(o){return Object.prototype.toString.call(o)}function pad(n){return n<10?"0"+n.toString(10):n.toString(10)}var months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function timestamp(){var d=new Date;var time=[pad(d.getHours()),pad(d.getMinutes()),pad(d.getSeconds())].join(":");return[d.getDate(),months[d.getMonth()],time].join(" ")}exports.log=function(){console.log("%s - %s",timestamp(),exports.format.apply(exports,arguments))};exports.inherits=require("inherits");exports._extend=function(origin,add){if(!add||!isObject(add))return origin;var keys=Object.keys(add);var i=keys.length;while(i--){origin[keys[i]]=add[keys[i]]}return origin};function hasOwnProperty(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}}).call(this,require("_process"),typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./support/isBuffer":101,_process:100,inherits:98}],103:[function(require,module,exports){(function(root,factory){"use strict";if(typeof define==="function"&&define.amd){define(["exports"],factory)}else if(typeof exports!=="undefined"){factory(exports)}else{factory(root.estraverse={})}})(this,function(exports){"use strict";var Syntax,isArray,VisitorOption,VisitorKeys,objectCreate,objectKeys,BREAK,SKIP,REMOVE;function ignoreJSHintError(){}isArray=Array.isArray;if(!isArray){isArray=function isArray(array){return Object.prototype.toString.call(array)==="[object Array]"}}function deepCopy(obj){var ret={},key,val;for(key in obj){if(obj.hasOwnProperty(key)){val=obj[key];if(typeof val==="object"&&val!==null){ret[key]=deepCopy(val)}else{ret[key]=val}}}return ret}function shallowCopy(obj){var ret={},key;for(key in obj){if(obj.hasOwnProperty(key)){ret[key]=obj[key]}}return ret}ignoreJSHintError(shallowCopy);function upperBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){len=diff}else{i=current+1;len-=diff+1}}return i}function lowerBound(array,func){var diff,len,i,current;len=array.length;i=0;while(len){diff=len>>>1;current=i+diff;if(func(array[current])){i=current+1;len-=diff+1}else{len=diff}}return i}ignoreJSHintError(lowerBound);objectCreate=Object.create||function(){function F(){}return function(o){F.prototype=o;return new F}}();objectKeys=Object.keys||function(o){var keys=[],key;for(key in o){keys.push(key)}return keys};function extend(to,from){objectKeys(from).forEach(function(key){to[key]=from[key]});return to}Syntax={AssignmentExpression:"AssignmentExpression",ArrayExpression:"ArrayExpression",ArrayPattern:"ArrayPattern",ArrowFunctionExpression:"ArrowFunctionExpression",BlockStatement:"BlockStatement",BinaryExpression:"BinaryExpression",BreakStatement:"BreakStatement",CallExpression:"CallExpression",CatchClause:"CatchClause",ClassBody:"ClassBody",ClassDeclaration:"ClassDeclaration",ClassExpression:"ClassExpression",ComprehensionBlock:"ComprehensionBlock",ComprehensionExpression:"ComprehensionExpression",ConditionalExpression:"ConditionalExpression",ContinueStatement:"ContinueStatement",DebuggerStatement:"DebuggerStatement",DirectiveStatement:"DirectiveStatement",DoWhileStatement:"DoWhileStatement",EmptyStatement:"EmptyStatement",ExportBatchSpecifier:"ExportBatchSpecifier",ExportDeclaration:"ExportDeclaration",ExportSpecifier:"ExportSpecifier",ExpressionStatement:"ExpressionStatement",ForStatement:"ForStatement",ForInStatement:"ForInStatement",ForOfStatement:"ForOfStatement",FunctionDeclaration:"FunctionDeclaration",FunctionExpression:"FunctionExpression",GeneratorExpression:"GeneratorExpression",Identifier:"Identifier",IfStatement:"IfStatement",ImportDeclaration:"ImportDeclaration",ImportDefaultSpecifier:"ImportDefaultSpecifier",ImportNamespaceSpecifier:"ImportNamespaceSpecifier",ImportSpecifier:"ImportSpecifier",Literal:"Literal",LabeledStatement:"LabeledStatement",LogicalExpression:"LogicalExpression",MemberExpression:"MemberExpression",MethodDefinition:"MethodDefinition",ModuleSpecifier:"ModuleSpecifier",NewExpression:"NewExpression",ObjectExpression:"ObjectExpression",ObjectPattern:"ObjectPattern",Program:"Program",Property:"Property",ReturnStatement:"ReturnStatement",SequenceExpression:"SequenceExpression",SpreadElement:"SpreadElement",SwitchStatement:"SwitchStatement",SwitchCase:"SwitchCase",TaggedTemplateExpression:"TaggedTemplateExpression",TemplateElement:"TemplateElement",TemplateLiteral:"TemplateLiteral",ThisExpression:"ThisExpression",ThrowStatement:"ThrowStatement",TryStatement:"TryStatement",UnaryExpression:"UnaryExpression",UpdateExpression:"UpdateExpression",VariableDeclaration:"VariableDeclaration",VariableDeclarator:"VariableDeclarator",WhileStatement:"WhileStatement",WithStatement:"WithStatement",YieldExpression:"YieldExpression"};VisitorKeys={AssignmentExpression:["left","right"],ArrayExpression:["elements"],ArrayPattern:["elements"],ArrowFunctionExpression:["params","defaults","rest","body"],BlockStatement:["body"],BinaryExpression:["left","right"],BreakStatement:["label"],CallExpression:["callee","arguments"],CatchClause:["param","body"],ClassBody:["body"],ClassDeclaration:["id","body","superClass"],ClassExpression:["id","body","superClass"],ComprehensionBlock:["left","right"],ComprehensionExpression:["blocks","filter","body"],ConditionalExpression:["test","consequent","alternate"],ContinueStatement:["label"],DebuggerStatement:[],DirectiveStatement:[],DoWhileStatement:["body","test"],EmptyStatement:[],ExportBatchSpecifier:[],ExportDeclaration:["declaration","specifiers","source"],ExportSpecifier:["id","name"],ExpressionStatement:["expression"],ForStatement:["init","test","update","body"],ForInStatement:["left","right","body"],ForOfStatement:["left","right","body"],FunctionDeclaration:["id","params","defaults","rest","body"],FunctionExpression:["id","params","defaults","rest","body"],GeneratorExpression:["blocks","filter","body"],Identifier:[],IfStatement:["test","consequent","alternate"],ImportDeclaration:["specifiers","source"],ImportDefaultSpecifier:["id"],ImportNamespaceSpecifier:["id"],ImportSpecifier:["id","name"],Literal:[],LabeledStatement:["label","body"],LogicalExpression:["left","right"],MemberExpression:["object","property"],MethodDefinition:["key","value"],ModuleSpecifier:[],NewExpression:["callee","arguments"],ObjectExpression:["properties"],ObjectPattern:["properties"],Program:["body"],Property:["key","value"],ReturnStatement:["argument"],SequenceExpression:["expressions"],SpreadElement:["argument"],SwitchStatement:["discriminant","cases"],SwitchCase:["test","consequent"],TaggedTemplateExpression:["tag","quasi"],TemplateElement:[],TemplateLiteral:["quasis","expressions"],ThisExpression:[],ThrowStatement:["argument"],TryStatement:["block","handlers","handler","guardedHandlers","finalizer"],UnaryExpression:["argument"],UpdateExpression:["argument"],VariableDeclaration:["declarations"],VariableDeclarator:["id","init"],WhileStatement:["test","body"],WithStatement:["object","body"],YieldExpression:["argument"]};BREAK={};SKIP={};REMOVE={};VisitorOption={Break:BREAK,Skip:SKIP,Remove:REMOVE};function Reference(parent,key){this.parent=parent;this.key=key}Reference.prototype.replace=function replace(node){this.parent[this.key]=node};Reference.prototype.remove=function remove(){if(isArray(this.parent)){this.parent.splice(this.key,1);return true}else{this.replace(null);return false}};function Element(node,path,wrap,ref){this.node=node;this.path=path;this.wrap=wrap;this.ref=ref}function Controller(){}Controller.prototype.path=function path(){var i,iz,j,jz,result,element;function addToPath(result,path){if(isArray(path)){for(j=0,jz=path.length;j<jz;++j){result.push(path[j])}}else{result.push(path)}}if(!this.__current.path){return null}result=[];for(i=2,iz=this.__leavelist.length;i<iz;++i){element=this.__leavelist[i];addToPath(result,element.path)}addToPath(result,this.__current.path);return result};Controller.prototype.type=function(){var node=this.current();return node.type||this.__current.wrap};Controller.prototype.parents=function parents(){var i,iz,result;result=[];for(i=1,iz=this.__leavelist.length;i<iz;++i){result.push(this.__leavelist[i].node)}return result};Controller.prototype.current=function current(){return this.__current.node};Controller.prototype.__execute=function __execute(callback,element){var previous,result;result=undefined;previous=this.__current;this.__current=element;this.__state=null;if(callback){result=callback.call(this,element.node,this.__leavelist[this.__leavelist.length-1].node)}this.__current=previous;return result};Controller.prototype.notify=function notify(flag){this.__state=flag};Controller.prototype.skip=function(){this.notify(SKIP)};Controller.prototype["break"]=function(){this.notify(BREAK)};Controller.prototype.remove=function(){this.notify(REMOVE)};Controller.prototype.__initialize=function(root,visitor){this.visitor=visitor;this.root=root;this.__worklist=[];this.__leavelist=[];this.__current=null;this.__state=null;this.__fallback=visitor.fallback==="iteration";this.__keys=VisitorKeys;if(visitor.keys){this.__keys=extend(objectCreate(this.__keys),visitor.keys)}};function isNode(node){if(node==null){return false}return typeof node==="object"&&typeof node.type==="string"}function isProperty(nodeType,key){return(nodeType===Syntax.ObjectExpression||nodeType===Syntax.ObjectPattern)&&"properties"===key}Controller.prototype.traverse=function traverse(root,visitor){var worklist,leavelist,element,node,nodeType,ret,key,current,current2,candidates,candidate,sentinel;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;worklist.push(new Element(root,null,null,null));leavelist.push(new Element(null,null,null,null));while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();ret=this.__execute(visitor.leave,element);if(this.__state===BREAK||ret===BREAK){return}continue}if(element.node){ret=this.__execute(visitor.enter,element);if(this.__state===BREAK||ret===BREAK){return}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||ret===SKIP){continue}node=element.node;nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key];if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",null)}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,null)}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,null))}}}}};Controller.prototype.replace=function replace(root,visitor){function removeElem(element){var i,key,nextElem,parent;if(element.ref.remove()){key=element.ref.key;parent=element.ref.parent;i=worklist.length;while(i--){nextElem=worklist[i];if(nextElem.ref&&nextElem.ref.parent===parent){if(nextElem.ref.key<key){break}--nextElem.ref.key}}}}var worklist,leavelist,node,nodeType,target,element,current,current2,candidates,candidate,sentinel,outer,key;this.__initialize(root,visitor);sentinel={};worklist=this.__worklist;leavelist=this.__leavelist;outer={root:root};element=new Element(root,null,null,new Reference(outer,"root"));worklist.push(element);leavelist.push(element);while(worklist.length){element=worklist.pop();if(element===sentinel){element=leavelist.pop();target=this.__execute(visitor.leave,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target)}if(this.__state===REMOVE||target===REMOVE){removeElem(element)}if(this.__state===BREAK||target===BREAK){return outer.root}continue}target=this.__execute(visitor.enter,element);if(target!==undefined&&target!==BREAK&&target!==SKIP&&target!==REMOVE){element.ref.replace(target);element.node=target}if(this.__state===REMOVE||target===REMOVE){removeElem(element);element.node=null}if(this.__state===BREAK||target===BREAK){return outer.root}node=element.node;if(!node){continue}worklist.push(sentinel);leavelist.push(element);if(this.__state===SKIP||target===SKIP){continue}nodeType=element.wrap||node.type;candidates=this.__keys[nodeType];if(!candidates){if(this.__fallback){candidates=objectKeys(node)}else{throw new Error("Unknown node type "+nodeType+".")}}current=candidates.length;while((current-=1)>=0){key=candidates[current];candidate=node[key]; if(!candidate){continue}if(isArray(candidate)){current2=candidate.length;while((current2-=1)>=0){if(!candidate[current2]){continue}if(isProperty(nodeType,candidates[current])){element=new Element(candidate[current2],[key,current2],"Property",new Reference(candidate,current2))}else if(isNode(candidate[current2])){element=new Element(candidate[current2],[key,current2],null,new Reference(candidate,current2))}else{continue}worklist.push(element)}}else if(isNode(candidate)){worklist.push(new Element(candidate,key,null,new Reference(node,key)))}}}return outer.root};function traverse(root,visitor){var controller=new Controller;return controller.traverse(root,visitor)}function replace(root,visitor){var controller=new Controller;return controller.replace(root,visitor)}function extendCommentRange(comment,tokens){var target;target=upperBound(tokens,function search(token){return token.range[0]>comment.range[0]});comment.extendedRange=[comment.range[0],comment.range[1]];if(target!==tokens.length){comment.extendedRange[1]=tokens[target].range[0]}target-=1;if(target>=0){comment.extendedRange[0]=tokens[target].range[1]}return comment}function attachComments(tree,providedComments,tokens){var comments=[],comment,len,i,cursor;if(!tree.range){throw new Error("attachComments needs range information")}if(!tokens.length){if(providedComments.length){for(i=0,len=providedComments.length;i<len;i+=1){comment=deepCopy(providedComments[i]);comment.extendedRange=[0,tree.range[0]];comments.push(comment)}tree.leadingComments=comments}return tree}for(i=0,len=providedComments.length;i<len;i+=1){comments.push(extendCommentRange(deepCopy(providedComments[i]),tokens))}cursor=0;traverse(tree,{enter:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(comment.extendedRange[1]>node.range[0]){break}if(comment.extendedRange[1]===node.range[0]){if(!node.leadingComments){node.leadingComments=[]}node.leadingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});cursor=0;traverse(tree,{leave:function(node){var comment;while(cursor<comments.length){comment=comments[cursor];if(node.range[1]<comment.extendedRange[0]){break}if(node.range[1]===comment.extendedRange[0]){if(!node.trailingComments){node.trailingComments=[]}node.trailingComments.push(comment);comments.splice(cursor,1)}else{cursor+=1}}if(cursor===comments.length){return VisitorOption.Break}if(comments[cursor].extendedRange[0]>node.range[1]){return VisitorOption.Skip}}});return tree}exports.version="1.8.0";exports.Syntax=Syntax;exports.traverse=traverse;exports.replace=replace;exports.attachComments=attachComments;exports.VisitorKeys=VisitorKeys;exports.VisitorOption=VisitorOption;exports.Controller=Controller})},{}],104:[function(require,module,exports){(function(){"use strict";function isExpression(node){if(node==null){return false}switch(node.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 isIterationStatement(node){if(node==null){return false}switch(node.type){case"DoWhileStatement":case"ForInStatement":case"ForStatement":case"WhileStatement":return true}return false}function isStatement(node){if(node==null){return false}switch(node.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 isSourceElement(node){return isStatement(node)||node!=null&&node.type==="FunctionDeclaration"}function trailingStatement(node){switch(node.type){case"IfStatement":if(node.alternate!=null){return node.alternate}return node.consequent;case"LabeledStatement":case"ForStatement":case"ForInStatement":case"WhileStatement":case"WithStatement":return node.body}return null}function isProblematicIfStatement(node){var current;if(node.type!=="IfStatement"){return false}if(node.alternate==null){return false}current=node.consequent;do{if(current.type==="IfStatement"){if(current.alternate==null){return true}}current=trailingStatement(current)}while(current);return false}module.exports={isExpression:isExpression,isStatement:isStatement,isIterationStatement:isIterationStatement,isSourceElement:isSourceElement,isProblematicIfStatement:isProblematicIfStatement,trailingStatement:trailingStatement}})()},{}],105:[function(require,module,exports){(function(){"use strict";var Regex,NON_ASCII_WHITESPACES;Regex={NonAsciiIdentifierStart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮͰ-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁҊ-ԧԱ-Ֆՙա-ևא-תװ-ײؠ-يٮٯٱ-ۓەۥۦۮۯۺ-ۼۿܐܒ-ܯݍ-ޥޱߊ-ߪߴߵߺࠀ-ࠕࠚࠤࠨࡀ-ࡘࢠࢢ-ࢬऄ-हऽॐक़-ॡॱ-ॷॹ-ॿঅ-ঌএঐও-নপ-রলশ-হঽৎড়ঢ়য়-ৡৰৱਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹਖ਼-ੜਫ਼ੲ-ੴઅ-ઍએ-ઑઓ-નપ-રલળવ-હઽૐૠૡଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହଽଡ଼ଢ଼ୟ-ୡୱஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹௐఅ-ఌఎ-ఐఒ-నప-ళవ-హఽౘౙౠౡಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹಽೞೠೡೱೲഅ-ഌഎ-ഐഒ-ഺഽൎൠൡൺ-ൿඅ-ඖක-නඳ-රලව-ෆก-ะาำเ-ๆກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ະາຳຽເ-ໄໆໜ-ໟༀཀ-ཇཉ-ཬྈ-ྌက-ဪဿၐ-ၕၚ-ၝၡၥၦၮ-ၰၵ-ႁႎႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-ᜑᜠ-ᜱᝀ-ᝑᝠ-ᝬᝮ-ᝰក-ឳៗៜᠠ-ᡷᢀ-ᢨᢪᢰ-ᣵᤀ-ᤜᥐ-ᥭᥰ-ᥴᦀ-ᦫᧁ-ᧇᨀ-ᨖᨠ-ᩔᪧᬅ-ᬳᭅ-ᭋᮃ-ᮠᮮᮯᮺ-ᯥᰀ-ᰣᱍ-ᱏᱚ-ᱽᳩ-ᳬᳮ-ᳱᳵᳶᴀ-ᶿḀ-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼⁱⁿₐ-ₜℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳮⳲⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯⶀ-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⸯ々-〇〡-〩〱-〵〸-〼ぁ-ゖゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘟꘪꘫꙀ-ꙮꙿ-ꚗꚠ-ꛯꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠁꠃ-ꠅꠇ-ꠊꠌ-ꠢꡀ-ꡳꢂ-ꢳꣲ-ꣷꣻꤊ-ꤥꤰ-ꥆꥠ-ꥼꦄ-ꦲꧏꨀ-ꨨꩀ-ꩂꩄ-ꩋꩠ-ꩶꩺꪀ-ꪯꪱꪵꪶꪹ-ꪽꫀꫂꫛ-ꫝꫠ-ꫪꫲ-ꫴꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯢ가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִײַ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻﹰ-ﹴﹶ-ﻼA-Za-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]"),NonAsciiIdentifierPart:new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԧԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠࢢ-ࢬࣤ-ࣾऀ-ॣ०-९ॱ-ॷॹ-ॿঁ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఁ-ఃఅ-ఌఎ-ఐఒ-నప-ళవ-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಂಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲംഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛰᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤜᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶᴀ-ᷦ᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚗꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞓꞠ-Ɦꟸ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺꩻꪀ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︦︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]")};function isDecimalDigit(ch){return ch>=48&&ch<=57}function isHexDigit(ch){return isDecimalDigit(ch)||97<=ch&&ch<=102||65<=ch&&ch<=70}function isOctalDigit(ch){return ch>=48&&ch<=55}NON_ASCII_WHITESPACES=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279];function isWhiteSpace(ch){return ch===32||ch===9||ch===11||ch===12||ch===160||ch>=5760&&NON_ASCII_WHITESPACES.indexOf(ch)>=0}function isLineTerminator(ch){return ch===10||ch===13||ch===8232||ch===8233}function isIdentifierStart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))}function isIdentifierPart(ch){return ch>=97&&ch<=122||ch>=65&&ch<=90||ch>=48&&ch<=57||ch===36||ch===95||ch===92||ch>=128&&Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))}module.exports={isDecimalDigit:isDecimalDigit,isHexDigit:isHexDigit,isOctalDigit:isOctalDigit,isWhiteSpace:isWhiteSpace,isLineTerminator:isLineTerminator,isIdentifierStart:isIdentifierStart,isIdentifierPart:isIdentifierPart}})()},{}],106:[function(require,module,exports){(function(){"use strict";var code=require("./code");function isStrictModeReservedWordES6(id){switch(id){case"implements":case"interface":case"package":case"private":case"protected":case"public":case"static":case"let":return true;default:return false}}function isKeywordES5(id,strict){if(!strict&&id==="yield"){return false}return isKeywordES6(id,strict)}function isKeywordES6(id,strict){if(strict&&isStrictModeReservedWordES6(id)){return true}switch(id.length){case 2:return id==="if"||id==="in"||id==="do";case 3:return id==="var"||id==="for"||id==="new"||id==="try";case 4:return id==="this"||id==="else"||id==="case"||id==="void"||id==="with"||id==="enum";case 5:return id==="while"||id==="break"||id==="catch"||id==="throw"||id==="const"||id==="yield"||id==="class"||id==="super";case 6:return id==="return"||id==="typeof"||id==="delete"||id==="switch"||id==="export"||id==="import";case 7:return id==="default"||id==="finally"||id==="extends";case 8:return id==="function"||id==="continue"||id==="debugger";case 10:return id==="instanceof";default:return false}}function isReservedWordES5(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES5(id,strict)}function isReservedWordES6(id,strict){return id==="null"||id==="true"||id==="false"||isKeywordES6(id,strict)}function isRestrictedWord(id){return id==="eval"||id==="arguments"}function isIdentifierName(id){var i,iz,ch;if(id.length===0){return false}ch=id.charCodeAt(0);if(!code.isIdentifierStart(ch)||ch===92){return false}for(i=1,iz=id.length;i<iz;++i){ch=id.charCodeAt(i);if(!code.isIdentifierPart(ch)||ch===92){return false}}return true}function isIdentifierES5(id,strict){return isIdentifierName(id)&&!isReservedWordES5(id,strict)}function isIdentifierES6(id,strict){return isIdentifierName(id)&&!isReservedWordES6(id,strict)}module.exports={isKeywordES5:isKeywordES5,isKeywordES6:isKeywordES6,isReservedWordES5:isReservedWordES5,isReservedWordES6:isReservedWordES6,isRestrictedWord:isRestrictedWord,isIdentifierName:isIdentifierName,isIdentifierES5:isIdentifierES5,isIdentifierES6:isIdentifierES6}})()},{"./code":105}],107:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":104,"./code":105,"./keyword":106}],108:[function(require,module,exports){(function(global){(function(){var undefined;var arrayPool=[],objectPool=[];var idCounter=0;var keyPrefix=+new Date+"";var largeArraySize=75;var maxPoolSize=40;var whitespace=" \f "+"\n\r\u2028\u2029"+" ᠎              ";var reEmptyStringLeading=/\b__p \+= '';/g,reEmptyStringMiddle=/\b(__p \+=) '' \+/g,reEmptyStringTrailing=/(__e\(.*?\)|\b__t\)) \+\n'';/g;var reEsTemplate=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;var reFlags=/\w*$/;var reFuncName=/^\s*function[ \n\r\t]+\w/;var reInterpolate=/<%=([\s\S]+?)%>/g;var reLeadingSpacesAndZeros=RegExp("^["+whitespace+"]*0+(?=.$)");var reNoMatch=/($^)/;var reThis=/\bthis\b/;var reUnescapedString=/['\n\r\t\u2028\u2029\\]/g;var contextProps=["Array","Boolean","Date","Function","Math","Number","Object","RegExp","String","_","attachEvent","clearTimeout","isFinite","isNaN","parseInt","setTimeout"];var templateCounter=0;var argsClass="[object Arguments]",arrayClass="[object Array]",boolClass="[object Boolean]",dateClass="[object Date]",funcClass="[object Function]",numberClass="[object Number]",objectClass="[object Object]",regexpClass="[object RegExp]",stringClass="[object String]";var cloneableClasses={};cloneableClasses[funcClass]=false;cloneableClasses[argsClass]=cloneableClasses[arrayClass]=cloneableClasses[boolClass]=cloneableClasses[dateClass]=cloneableClasses[numberClass]=cloneableClasses[objectClass]=cloneableClasses[regexpClass]=cloneableClasses[stringClass]=true;var debounceOptions={leading:false,maxWait:0,trailing:false};var descriptor={configurable:false,enumerable:false,value:null,writable:false};var objectTypes={"boolean":false,"function":true,object:true,number:false,string:false,undefined:false};var stringEscapes={"\\":"\\","'":"'","\n":"n","\r":"r"," ":"t","\u2028":"u2028","\u2029":"u2029"};var root=objectTypes[typeof window]&&window||this;var freeExports=objectTypes[typeof exports]&&exports&&!exports.nodeType&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var moduleExports=freeModule&&freeModule.exports===freeExports&&freeExports;var freeGlobal=objectTypes[typeof global]&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal)){root=freeGlobal}function baseIndexOf(array,value,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0;while(++index<length){if(array[index]===value){return index}}return-1}function cacheIndexOf(cache,value){var type=typeof value;cache=cache.cache;if(type=="boolean"||value==null){return cache[value]?0:-1}if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value;cache=(cache=cache[type])&&cache[key];return type=="object"?cache&&baseIndexOf(cache,value)>-1?0:-1:cache?0:-1}function cachePush(value){var cache=this.cache,type=typeof value;if(type=="boolean"||value==null){cache[value]=true}else{if(type!="number"&&type!="string"){type="object"}var key=type=="number"?value:keyPrefix+value,typeCache=cache[type]||(cache[type]={});if(type=="object"){(typeCache[key]||(typeCache[key]=[])).push(value)}else{typeCache[key]=true}}}function charAtCallback(value){return value.charCodeAt(0)}function compareAscending(a,b){var ac=a.criteria,bc=b.criteria,index=-1,length=ac.length;while(++index<length){var value=ac[index],other=bc[index];if(value!==other){if(value>other||typeof value=="undefined"){return 1}if(value<other||typeof other=="undefined"){return-1}}}return a.index-b.index}function createCache(array){var index=-1,length=array.length,first=array[0],mid=array[length/2|0],last=array[length-1];if(first&&typeof first=="object"&&mid&&typeof mid=="object"&&last&&typeof last=="object"){return false}var cache=getObject();cache["false"]=cache["null"]=cache["true"]=cache["undefined"]=false;var result=getObject();result.array=array;result.cache=cache;result.push=cachePush;while(++index<length){result.push(array[index])}return result}function escapeStringChar(match){return"\\"+stringEscapes[match]}function getArray(){return arrayPool.pop()||[]}function getObject(){return objectPool.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 releaseArray(array){array.length=0;if(arrayPool.length<maxPoolSize){arrayPool.push(array)}}function releaseObject(object){var cache=object.cache;if(cache){releaseObject(cache)}object.array=object.cache=object.criteria=object.object=object.number=object.string=object.value=null;if(objectPool.length<maxPoolSize){objectPool.push(object)}}function slice(array,start,end){start||(start=0);if(typeof end=="undefined"){end=array?array.length:0}var index=-1,length=end-start||0,result=Array(length<0?0:length);while(++index<length){result[index]=array[start+index]}return result}function runInContext(context){context=context?_.defaults(root.Object(),context,_.pick(root,contextProps)):root;var Array=context.Array,Boolean=context.Boolean,Date=context.Date,Function=context.Function,Math=context.Math,Number=context.Number,Object=context.Object,RegExp=context.RegExp,String=context.String,TypeError=context.TypeError;var arrayRef=[];var objectProto=Object.prototype;var oldDash=context._;var toString=objectProto.toString;var reNative=RegExp("^"+String(toString).replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/toString| for [^\]]+/g,".*?")+"$");var ceil=Math.ceil,clearTimeout=context.clearTimeout,floor=Math.floor,fnToString=Function.prototype.toString,getPrototypeOf=isNative(getPrototypeOf=Object.getPrototypeOf)&&getPrototypeOf,hasOwnProperty=objectProto.hasOwnProperty,push=arrayRef.push,setTimeout=context.setTimeout,splice=arrayRef.splice,unshift=arrayRef.unshift;var defineProperty=function(){try{var o={},func=isNative(func=Object.defineProperty)&&func,result=func(o,o,o)&&func}catch(e){}return result}();var nativeCreate=isNative(nativeCreate=Object.create)&&nativeCreate,nativeIsArray=isNative(nativeIsArray=Array.isArray)&&nativeIsArray,nativeIsFinite=context.isFinite,nativeIsNaN=context.isNaN,nativeKeys=isNative(nativeKeys=Object.keys)&&nativeKeys,nativeMax=Math.max,nativeMin=Math.min,nativeParseInt=context.parseInt,nativeRandom=Math.random;var ctorByClass={};ctorByClass[arrayClass]=Array;ctorByClass[boolClass]=Boolean;ctorByClass[dateClass]=Date;ctorByClass[funcClass]=Function;ctorByClass[objectClass]=Object;ctorByClass[numberClass]=Number;ctorByClass[regexpClass]=RegExp;ctorByClass[stringClass]=String;function lodash(value){return value&&typeof value=="object"&&!isArray(value)&&hasOwnProperty.call(value,"__wrapped__")?value:new lodashWrapper(value)}function lodashWrapper(value,chainAll){this.__chain__=!!chainAll;this.__wrapped__=value}lodashWrapper.prototype=lodash.prototype;var support=lodash.support={};support.funcDecomp=!isNative(context.WinRTError)&&reThis.test(runInContext);support.funcNames=typeof Function.name=="string";lodash.templateSettings={escape:/<%-([\s\S]+?)%>/g,evaluate:/<%([\s\S]+?)%>/g,interpolate:reInterpolate,variable:"",imports:{_:lodash}};function baseBind(bindData){var func=bindData[0],partialArgs=bindData[2],thisArg=bindData[4];function bound(){if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(this instanceof bound){var thisBinding=baseCreate(func.prototype),result=func.apply(thisBinding,args||arguments);return isObject(result)?result:thisBinding}return func.apply(thisArg,args||arguments)}setBindData(bound,bindData);return bound}function baseClone(value,isDeep,callback,stackA,stackB){if(callback){var result=callback(value);if(typeof result!="undefined"){return result}}var isObj=isObject(value);if(isObj){var className=toString.call(value);if(!cloneableClasses[className]){return value}var ctor=ctorByClass[className];switch(className){case boolClass:case dateClass:return new ctor(+value);case numberClass:case stringClass:return new ctor(value);case regexpClass:result=ctor(value.source,reFlags.exec(value));result.lastIndex=value.lastIndex;return result}}else{return value}var isArr=isArray(value);if(isDeep){var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==value){return stackB[length]}}result=isArr?ctor(value.length):{}}else{result=isArr?slice(value):assign({},value)}if(isArr){if(hasOwnProperty.call(value,"index")){result.index=value.index}if(hasOwnProperty.call(value,"input")){result.input=value.input}}if(!isDeep){return result}stackA.push(value);stackB.push(result);(isArr?forEach:forOwn)(value,function(objValue,key){result[key]=baseClone(objValue,isDeep,callback,stackA,stackB)});if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseCreate(prototype,properties){return isObject(prototype)?nativeCreate(prototype):{}}if(!nativeCreate){baseCreate=function(){function Object(){}return function(prototype){if(isObject(prototype)){Object.prototype=prototype;var result=new Object;Object.prototype=null}return result||context.Object()}}()}function baseCreateCallback(func,thisArg,argCount){if(typeof func!="function"){return identity}if(typeof thisArg=="undefined"||!("prototype"in func)){return func}var bindData=func.__bindData__;if(typeof bindData=="undefined"){if(support.funcNames){bindData=!func.name}bindData=bindData||!support.funcDecomp;if(!bindData){var source=fnToString.call(func);if(!support.funcNames){bindData=!reFuncName.test(source)}if(!bindData){bindData=reThis.test(source);setBindData(func,bindData)}}}if(bindData===false||bindData!==true&&bindData[1]&1){return func}switch(argCount){case 1:return function(value){return func.call(thisArg,value)};case 2:return function(a,b){return func.call(thisArg,a,b)};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)}}return bind(func,thisArg)}function baseCreateWrapper(bindData){var func=bindData[0],bitmask=bindData[1],partialArgs=bindData[2],partialRightArgs=bindData[3],thisArg=bindData[4],arity=bindData[5];var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,key=func;function bound(){var thisBinding=isBind?thisArg:this;if(partialArgs){var args=slice(partialArgs);push.apply(args,arguments)}if(partialRightArgs||isCurry){args||(args=slice(arguments));if(partialRightArgs){push.apply(args,partialRightArgs)}if(isCurry&&args.length<arity){bitmask|=16&~32;return baseCreateWrapper([func,isCurryBound?bitmask:bitmask&~3,args,null,thisArg,arity])}}args||(args=arguments);if(isBindKey){func=thisBinding[key]}if(this instanceof bound){thisBinding=baseCreate(func.prototype);var result=func.apply(thisBinding,args);return isObject(result)?result:thisBinding}return func.apply(thisBinding,args)}setBindData(bound,bindData);return bound}function baseDifference(array,values){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,isLarge=length>=largeArraySize&&indexOf===baseIndexOf,result=[];if(isLarge){var cache=createCache(values);if(cache){indexOf=cacheIndexOf;values=cache}else{isLarge=false}}while(++index<length){var value=array[index];if(indexOf(values,value)<0){result.push(value)}}if(isLarge){releaseObject(values)}return result}function baseFlatten(array,isShallow,isStrict,fromIndex){var index=(fromIndex||0)-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value&&typeof value=="object"&&typeof value.length=="number"&&(isArray(value)||isArguments(value))){if(!isShallow){value=baseFlatten(value,isShallow,isStrict)}var valIndex=-1,valLength=value.length,resIndex=result.length;result.length+=valLength;while(++valIndex<valLength){result[resIndex++]=value[valIndex]}}else if(!isStrict){result.push(value)}}return result}function baseIsEqual(a,b,callback,isWhere,stackA,stackB){if(callback){var result=callback(a,b);if(typeof result!="undefined"){return!!result}}if(a===b){return a!==0||1/a==1/b}var type=typeof a,otherType=typeof b;if(a===a&&!(a&&objectTypes[type])&&!(b&&objectTypes[otherType])){return false}if(a==null||b==null){return a===b}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:return+a==+b;case numberClass:return a!=+a?b!=+b:a==0?1/a==1/b:a==+b;case regexpClass:case stringClass:return a==String(b)}var isArr=className==arrayClass;if(!isArr){var aWrapped=hasOwnProperty.call(a,"__wrapped__"),bWrapped=hasOwnProperty.call(b,"__wrapped__");if(aWrapped||bWrapped){return baseIsEqual(aWrapped?a.__wrapped__:a,bWrapped?b.__wrapped__:b,callback,isWhere,stackA,stackB)}if(className!=objectClass){return false}var ctorA=a.constructor,ctorB=b.constructor;if(ctorA!=ctorB&&!(isFunction(ctorA)&&ctorA instanceof ctorA&&isFunction(ctorB)&&ctorB instanceof ctorB)&&("constructor"in a&&"constructor"in b)){return false}}var initedStack=!stackA;stackA||(stackA=getArray());stackB||(stackB=getArray());var length=stackA.length;while(length--){if(stackA[length]==a){return stackB[length]==b}}var size=0;result=true;stackA.push(a);stackB.push(b);if(isArr){length=a.length;size=b.length;result=size==length;if(result||isWhere){while(size--){var index=length,value=b[size];if(isWhere){while(index--){if(result=baseIsEqual(a[index],value,callback,isWhere,stackA,stackB)){break}}}else if(!(result=baseIsEqual(a[size],value,callback,isWhere,stackA,stackB))){break}}}}else{forIn(b,function(value,key,b){if(hasOwnProperty.call(b,key)){size++;return result=hasOwnProperty.call(a,key)&&baseIsEqual(a[key],value,callback,isWhere,stackA,stackB)}});if(result&&!isWhere){forIn(a,function(value,key,a){if(hasOwnProperty.call(a,key)){return result=--size>-1}})}}stackA.pop();stackB.pop();if(initedStack){releaseArray(stackA);releaseArray(stackB)}return result}function baseMerge(object,source,callback,stackA,stackB){(isArray(source)?forEach:forOwn)(source,function(source,key){var found,isArr,result=source,value=object[key];if(source&&((isArr=isArray(source))||isPlainObject(source))){var stackLength=stackA.length;while(stackLength--){if(found=stackA[stackLength]==source){value=stackB[stackLength];break}}if(!found){var isShallow;if(callback){result=callback(value,source);if(isShallow=typeof result!="undefined"){value=result}}if(!isShallow){value=isArr?isArray(value)?value:[]:isPlainObject(value)?value:{}}stackA.push(source);stackB.push(value);if(!isShallow){baseMerge(value,source,callback,stackA,stackB)}}}else{if(callback){result=callback(value,source);if(typeof result=="undefined"){result=source}}if(typeof result!="undefined"){value=result}}object[key]=value})}function baseRandom(min,max){return min+floor(nativeRandom()*(max-min+1))}function baseUniq(array,isSorted,callback){var index=-1,indexOf=getIndexOf(),length=array?array.length:0,result=[];var isLarge=!isSorted&&length>=largeArraySize&&indexOf===baseIndexOf,seen=callback||isLarge?getArray():result;if(isLarge){var cache=createCache(seen);indexOf=cacheIndexOf;seen=cache}while(++index<length){var value=array[index],computed=callback?callback(value,index,array):value;if(isSorted?!index||seen[seen.length-1]!==computed:indexOf(seen,computed)<0){if(callback||isLarge){seen.push(computed)}result.push(value)}}if(isLarge){releaseArray(seen.array);releaseObject(seen)}else if(callback){releaseArray(seen)}return result}function createAggregator(setter){return function(collection,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];setter(result,value,callback(value,index,collection),collection)}}else{forOwn(collection,function(value,key,collection){setter(result,value,callback(value,key,collection),collection)})}return result}}function createWrapper(func,bitmask,partialArgs,partialRightArgs,thisArg,arity){var isBind=bitmask&1,isBindKey=bitmask&2,isCurry=bitmask&4,isCurryBound=bitmask&8,isPartial=bitmask&16,isPartialRight=bitmask&32;if(!isBindKey&&!isFunction(func)){throw new TypeError}if(isPartial&&!partialArgs.length){bitmask&=~16;isPartial=partialArgs=false}if(isPartialRight&&!partialRightArgs.length){bitmask&=~32;isPartialRight=partialRightArgs=false}var bindData=func&&func.__bindData__;if(bindData&&bindData!==true){bindData=slice(bindData);if(bindData[2]){bindData[2]=slice(bindData[2])}if(bindData[3]){bindData[3]=slice(bindData[3])}if(isBind&&!(bindData[1]&1)){bindData[4]=thisArg}if(!isBind&&bindData[1]&1){bitmask|=8}if(isCurry&&!(bindData[1]&4)){bindData[5]=arity}if(isPartial){push.apply(bindData[2]||(bindData[2]=[]),partialArgs)}if(isPartialRight){unshift.apply(bindData[3]||(bindData[3]=[]),partialRightArgs)}bindData[1]|=bitmask;return createWrapper.apply(null,bindData)}var creater=bitmask==1||bitmask===17?baseBind:baseCreateWrapper;return creater([func,bitmask,partialArgs,partialRightArgs,thisArg,arity])}function escapeHtmlChar(match){return htmlEscapes[match]}function getIndexOf(){var result=(result=lodash.indexOf)===indexOf?baseIndexOf:result;return result}function isNative(value){return typeof value=="function"&&reNative.test(value)}var setBindData=!defineProperty?noop:function(func,value){descriptor.value=value;defineProperty(func,"__bindData__",descriptor)};function shimIsPlainObject(value){var ctor,result;if(!(value&&toString.call(value)==objectClass)||(ctor=value.constructor,isFunction(ctor)&&!(ctor instanceof ctor))){return false}forIn(value,function(value,key){result=key});return typeof result=="undefined"||hasOwnProperty.call(value,result)}function unescapeHtmlChar(match){return htmlUnescapes[match]}function isArguments(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==argsClass||false}var isArray=nativeIsArray||function(value){return value&&typeof value=="object"&&typeof value.length=="number"&&toString.call(value)==arrayClass||false};var shimKeys=function(object){var index,iterable=object,result=[];if(!iterable)return result;if(!objectTypes[typeof object])return result;for(index in iterable){if(hasOwnProperty.call(iterable,index)){result.push(index)}}return result};var keys=!nativeKeys?shimKeys:function(object){if(!isObject(object)){return[]}return nativeKeys(object)};var htmlEscapes={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};var htmlUnescapes=invert(htmlEscapes);var reEscapedHtml=RegExp("("+keys(htmlUnescapes).join("|")+")","g"),reUnescapedHtml=RegExp("["+keys(htmlEscapes).join("")+"]","g");var assign=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;if(argsLength>3&&typeof args[argsLength-2]=="function"){var callback=baseCreateCallback(args[--argsLength-1],args[argsLength--],2)}else if(argsLength>2&&typeof args[argsLength-1]=="function"){callback=args[--argsLength]}while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];result[index]=callback?callback(result[index],iterable[index]):iterable[index]}}}return result};function clone(value,isDeep,callback,thisArg){if(typeof isDeep!="boolean"&&isDeep!=null){thisArg=callback;callback=isDeep;isDeep=false}return baseClone(value,isDeep,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function cloneDeep(value,callback,thisArg){return baseClone(value,true,typeof callback=="function"&&baseCreateCallback(callback,thisArg,1))}function create(prototype,properties){var result=baseCreate(prototype);return properties?assign(result,properties):result}var defaults=function(object,source,guard){var index,iterable=object,result=iterable;if(!iterable)return result;var args=arguments,argsIndex=0,argsLength=typeof guard=="number"?2:args.length;while(++argsIndex<argsLength){iterable=args[argsIndex];if(iterable&&objectTypes[typeof iterable]){var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(typeof result[index]=="undefined")result[index]=iterable[index]}}}return result};function findKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}function findLastKey(object,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forOwnRight(object,function(value,key,object){if(callback(value,key,object)){result=key;return false}});return result}var forIn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);for(index in iterable){if(callback(iterable[index],index,collection)===false)return result}return result};function forInRight(object,callback,thisArg){var pairs=[];forIn(object,function(value,key){pairs.push(key,value)});var length=pairs.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){if(callback(pairs[length--],pairs[length],object)===false){break }}return object}var forOwn=function(collection,callback,thisArg){var index,iterable=collection,result=iterable;if(!iterable)return result;if(!objectTypes[typeof iterable])return result;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);var ownIndex=-1,ownProps=objectTypes[typeof iterable]&&keys(iterable),length=ownProps?ownProps.length:0;while(++ownIndex<length){index=ownProps[ownIndex];if(callback(iterable[index],index,collection)===false)return result}return result};function forOwnRight(object,callback,thisArg){var props=keys(object),length=props.length;callback=baseCreateCallback(callback,thisArg,3);while(length--){var key=props[length];if(callback(object[key],key,object)===false){break}}return object}function functions(object){var result=[];forIn(object,function(value,key){if(isFunction(value)){result.push(key)}});return result.sort()}function has(object,key){return object?hasOwnProperty.call(object,key):false}function invert(object){var index=-1,props=keys(object),length=props.length,result={};while(++index<length){var key=props[index];result[object[key]]=key}return result}function isBoolean(value){return value===true||value===false||value&&typeof value=="object"&&toString.call(value)==boolClass||false}function isDate(value){return value&&typeof value=="object"&&toString.call(value)==dateClass||false}function isElement(value){return value&&value.nodeType===1||false}function isEmpty(value){var result=true;if(!value){return result}var className=toString.call(value),length=value.length;if(className==arrayClass||className==stringClass||className==argsClass||className==objectClass&&typeof length=="number"&&isFunction(value.splice)){return!length}forOwn(value,function(){return result=false});return result}function isEqual(a,b,callback,thisArg){return baseIsEqual(a,b,typeof callback=="function"&&baseCreateCallback(callback,thisArg,2))}function isFinite(value){return nativeIsFinite(value)&&!nativeIsNaN(parseFloat(value))}function isFunction(value){return typeof value=="function"}function isObject(value){return!!(value&&objectTypes[typeof value])}function isNaN(value){return isNumber(value)&&value!=+value}function isNull(value){return value===null}function isNumber(value){return typeof value=="number"||value&&typeof value=="object"&&toString.call(value)==numberClass||false}var isPlainObject=!getPrototypeOf?shimIsPlainObject:function(value){if(!(value&&toString.call(value)==objectClass)){return false}var valueOf=value.valueOf,objProto=isNative(valueOf)&&(objProto=getPrototypeOf(valueOf))&&getPrototypeOf(objProto);return objProto?value==objProto||getPrototypeOf(value)==objProto:shimIsPlainObject(value)};function isRegExp(value){return value&&typeof value=="object"&&toString.call(value)==regexpClass||false}function isString(value){return typeof value=="string"||value&&typeof value=="object"&&toString.call(value)==stringClass||false}function isUndefined(value){return typeof value=="undefined"}function mapValues(object,callback,thisArg){var result={};callback=lodash.createCallback(callback,thisArg,3);forOwn(object,function(value,key,object){result[key]=callback(value,key,object)});return result}function merge(object){var args=arguments,length=2;if(!isObject(object)){return object}if(typeof args[2]!="number"){length=args.length}if(length>3&&typeof args[length-2]=="function"){var callback=baseCreateCallback(args[--length-1],args[length--],2)}else if(length>2&&typeof args[length-1]=="function"){callback=args[--length]}var sources=slice(arguments,1,length),index=-1,stackA=getArray(),stackB=getArray();while(++index<length){baseMerge(object,sources[index],callback,stackA,stackB)}releaseArray(stackA);releaseArray(stackB);return object}function omit(object,callback,thisArg){var result={};if(typeof callback!="function"){var props=[];forIn(object,function(value,key){props.push(key)});props=baseDifference(props,baseFlatten(arguments,true,false,1));var index=-1,length=props.length;while(++index<length){var key=props[index];result[key]=object[key]}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(!callback(value,key,object)){result[key]=value}})}return result}function pairs(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){var key=props[index];result[index]=[key,object[key]]}return result}function pick(object,callback,thisArg){var result={};if(typeof callback!="function"){var index=-1,props=baseFlatten(arguments,true,false,1),length=isObject(object)?props.length:0;while(++index<length){var key=props[index];if(key in object){result[key]=object[key]}}}else{callback=lodash.createCallback(callback,thisArg,3);forIn(object,function(value,key,object){if(callback(value,key,object)){result[key]=value}})}return result}function transform(object,callback,accumulator,thisArg){var isArr=isArray(object);if(accumulator==null){if(isArr){accumulator=[]}else{var ctor=object&&object.constructor,proto=ctor&&ctor.prototype;accumulator=baseCreate(proto)}}if(callback){callback=lodash.createCallback(callback,thisArg,4);(isArr?forEach:forOwn)(object,function(value,index,object){return callback(accumulator,value,index,object)})}return accumulator}function values(object){var index=-1,props=keys(object),length=props.length,result=Array(length);while(++index<length){result[index]=object[props[index]]}return result}function at(collection){var args=arguments,index=-1,props=baseFlatten(args,true,false,1),length=args[2]&&args[2][args[1]]===collection?1:props.length,result=Array(length);while(++index<length){result[index]=collection[props[index]]}return result}function contains(collection,target,fromIndex){var index=-1,indexOf=getIndexOf(),length=collection?collection.length:0,result=false;fromIndex=(fromIndex<0?nativeMax(0,length+fromIndex):fromIndex)||0;if(isArray(collection)){result=indexOf(collection,target,fromIndex)>-1}else if(typeof length=="number"){result=(isString(collection)?collection.indexOf(target,fromIndex):indexOf(collection,target,fromIndex))>-1}else{forOwn(collection,function(value){if(++index>=fromIndex){return!(result=value===target)}})}return result}var countBy=createAggregator(function(result,value,key){hasOwnProperty.call(result,key)?result[key]++:result[key]=1});function every(collection,callback,thisArg){var result=true;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(!(result=!!callback(collection[index],index,collection))){break}}}else{forOwn(collection,function(value,index,collection){return result=!!callback(value,index,collection)})}return result}function filter(collection,callback,thisArg){var result=[];callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){result.push(value)}}}else{forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result.push(value)}})}return result}function find(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){var value=collection[index];if(callback(value,index,collection)){return value}}}else{var result;forOwn(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}}function findLast(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);forEachRight(collection,function(value,index,collection){if(callback(value,index,collection)){result=value;return false}});return result}function forEach(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(++index<length){if(callback(collection[index],index,collection)===false){break}}}else{forOwn(collection,callback)}return collection}function forEachRight(collection,callback,thisArg){var length=collection?collection.length:0;callback=callback&&typeof thisArg=="undefined"?callback:baseCreateCallback(callback,thisArg,3);if(typeof length=="number"){while(length--){if(callback(collection[length],length,collection)===false){break}}}else{var props=keys(collection);length=props.length;forOwn(collection,function(value,key,collection){key=props?props[--length]:--length;return callback(collection[key],key,collection)})}return collection}var groupBy=createAggregator(function(result,value,key){(hasOwnProperty.call(result,key)?result[key]:result[key]=[]).push(value)});var indexBy=createAggregator(function(result,value,key){result[key]=value});function invoke(collection,methodName){var args=slice(arguments,2),index=-1,isFunc=typeof methodName=="function",length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){result[++index]=(isFunc?methodName:value[methodName]).apply(value,args)});return result}function map(collection,callback,thisArg){var index=-1,length=collection?collection.length:0;callback=lodash.createCallback(callback,thisArg,3);if(typeof length=="number"){var result=Array(length);while(++index<length){result[index]=callback(collection[index],index,collection)}}else{result=[];forOwn(collection,function(value,key,collection){result[++index]=callback(value,key,collection)})}return result}function max(collection,callback,thisArg){var computed=-Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value>result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current>computed){computed=current;result=value}})}return result}function min(collection,callback,thisArg){var computed=Infinity,result=computed;if(typeof callback!="function"&&thisArg&&thisArg[callback]===collection){callback=null}if(callback==null&&isArray(collection)){var index=-1,length=collection.length;while(++index<length){var value=collection[index];if(value<result){result=value}}}else{callback=callback==null&&isString(collection)?charAtCallback:lodash.createCallback(callback,thisArg,3);forEach(collection,function(value,index,collection){var current=callback(value,index,collection);if(current<computed){computed=current;result=value}})}return result}var pluck=map;function reduce(collection,callback,accumulator,thisArg){if(!collection)return accumulator;var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);var index=-1,length=collection.length;if(typeof length=="number"){if(noaccum){accumulator=collection[++index]}while(++index<length){accumulator=callback(accumulator,collection[index],index,collection)}}else{forOwn(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)})}return accumulator}function reduceRight(collection,callback,accumulator,thisArg){var noaccum=arguments.length<3;callback=lodash.createCallback(callback,thisArg,4);forEachRight(collection,function(value,index,collection){accumulator=noaccum?(noaccum=false,value):callback(accumulator,value,index,collection)});return accumulator}function reject(collection,callback,thisArg){callback=lodash.createCallback(callback,thisArg,3);return filter(collection,function(value,index,collection){return!callback(value,index,collection)})}function sample(collection,n,guard){if(collection&&typeof collection.length!="number"){collection=values(collection)}if(n==null||guard){return collection?collection[baseRandom(0,collection.length-1)]:undefined}var result=shuffle(collection);result.length=nativeMin(nativeMax(0,n),result.length);return result}function shuffle(collection){var index=-1,length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);forEach(collection,function(value){var rand=baseRandom(0,++index);result[index]=result[rand];result[rand]=value});return result}function size(collection){var length=collection?collection.length:0;return typeof length=="number"?length:keys(collection).length}function some(collection,callback,thisArg){var result;callback=lodash.createCallback(callback,thisArg,3);var index=-1,length=collection?collection.length:0;if(typeof length=="number"){while(++index<length){if(result=callback(collection[index],index,collection)){break}}}else{forOwn(collection,function(value,index,collection){return!(result=callback(value,index,collection))})}return!!result}function sortBy(collection,callback,thisArg){var index=-1,isArr=isArray(callback),length=collection?collection.length:0,result=Array(typeof length=="number"?length:0);if(!isArr){callback=lodash.createCallback(callback,thisArg,3)}forEach(collection,function(value,key,collection){var object=result[++index]=getObject();if(isArr){object.criteria=map(callback,function(key){return value[key]})}else{(object.criteria=getArray())[0]=callback(value,key,collection)}object.index=index;object.value=value});length=result.length;result.sort(compareAscending);while(length--){var object=result[length];result[length]=object.value;if(!isArr){releaseArray(object.criteria)}releaseObject(object)}return result}function toArray(collection){if(collection&&typeof collection.length=="number"){return slice(collection)}return values(collection)}var where=filter;function compact(array){var index=-1,length=array?array.length:0,result=[];while(++index<length){var value=array[index];if(value){result.push(value)}}return result}function difference(array){return baseDifference(array,baseFlatten(arguments,true,true,1))}function findIndex(array,callback,thisArg){var index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length){if(callback(array[index],index,array)){return index}}return-1}function findLastIndex(array,callback,thisArg){var length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(length--){if(callback(array[length],length,array)){return length}}return-1}function first(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=-1;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[0]:undefined}}return slice(array,0,nativeMin(nativeMax(0,n),length))}function flatten(array,isShallow,callback,thisArg){if(typeof isShallow!="boolean"&&isShallow!=null){thisArg=callback;callback=typeof isShallow!="function"&&thisArg&&thisArg[isShallow]===array?null:isShallow;isShallow=false}if(callback!=null){array=map(array,callback,thisArg)}return baseFlatten(array,isShallow)}function indexOf(array,value,fromIndex){if(typeof fromIndex=="number"){var length=array?array.length:0;fromIndex=fromIndex<0?nativeMax(0,length+fromIndex):fromIndex||0}else if(fromIndex){var index=sortedIndex(array,value);return array[index]===value?index:-1}return baseIndexOf(array,value,fromIndex)}function initial(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:callback||n}return slice(array,0,nativeMin(nativeMax(0,length-n),length))}function intersection(){var args=[],argsIndex=-1,argsLength=arguments.length,caches=getArray(),indexOf=getIndexOf(),trustIndexOf=indexOf===baseIndexOf,seen=getArray();while(++argsIndex<argsLength){var value=arguments[argsIndex];if(isArray(value)||isArguments(value)){args.push(value);caches.push(trustIndexOf&&value.length>=largeArraySize&&createCache(argsIndex?args[argsIndex]:seen))}}var array=args[0],index=-1,length=array?array.length:0,result=[];outer:while(++index<length){var cache=caches[0];value=array[index];if((cache?cacheIndexOf(cache,value):indexOf(seen,value))<0){argsIndex=argsLength;(cache||seen).push(value);while(--argsIndex){cache=caches[argsIndex];if((cache?cacheIndexOf(cache,value):indexOf(args[argsIndex],value))<0){continue outer}}result.push(value)}}while(argsLength--){cache=caches[argsLength];if(cache){releaseObject(cache)}}releaseArray(caches);releaseArray(seen);return result}function last(array,callback,thisArg){var n=0,length=array?array.length:0;if(typeof callback!="number"&&callback!=null){var index=length;callback=lodash.createCallback(callback,thisArg,3);while(index--&&callback(array[index],index,array)){n++}}else{n=callback;if(n==null||thisArg){return array?array[length-1]:undefined}}return slice(array,nativeMax(0,length-n))}function lastIndexOf(array,value,fromIndex){var index=array?array.length:0;if(typeof fromIndex=="number"){index=(fromIndex<0?nativeMax(0,index+fromIndex):nativeMin(fromIndex,index-1))+1}while(index--){if(array[index]===value){return index}}return-1}function pull(array){var args=arguments,argsIndex=0,argsLength=args.length,length=array?array.length:0;while(++argsIndex<argsLength){var index=-1,value=args[argsIndex];while(++index<length){if(array[index]===value){splice.call(array,index--,1);length--}}}return array}function range(start,end,step){start=+start||0;step=typeof step=="number"?step:+step||1;if(end==null){end=start;start=0}var index=-1,length=nativeMax(0,ceil((end-start)/(step||1))),result=Array(length);while(++index<length){result[index]=start;start+=step}return result}function remove(array,callback,thisArg){var index=-1,length=array?array.length:0,result=[];callback=lodash.createCallback(callback,thisArg,3);while(++index<length){var value=array[index];if(callback(value,index,array)){result.push(value);splice.call(array,index--,1);length--}}return result}function rest(array,callback,thisArg){if(typeof callback!="number"&&callback!=null){var n=0,index=-1,length=array?array.length:0;callback=lodash.createCallback(callback,thisArg,3);while(++index<length&&callback(array[index],index,array)){n++}}else{n=callback==null||thisArg?1:nativeMax(0,callback)}return slice(array,n)}function sortedIndex(array,value,callback,thisArg){var low=0,high=array?array.length:low;callback=callback?lodash.createCallback(callback,thisArg,1):identity;value=callback(value);while(low<high){var mid=low+high>>>1;callback(array[mid])<value?low=mid+1:high=mid}return low}function union(){return baseUniq(baseFlatten(arguments,true,true))}function uniq(array,isSorted,callback,thisArg){if(typeof isSorted!="boolean"&&isSorted!=null){thisArg=callback;callback=typeof isSorted!="function"&&thisArg&&thisArg[isSorted]===array?null:isSorted;isSorted=false}if(callback!=null){callback=lodash.createCallback(callback,thisArg,3)}return baseUniq(array,isSorted,callback)}function without(array){return baseDifference(array,slice(arguments,1))}function xor(){var index=-1,length=arguments.length;while(++index<length){var array=arguments[index];if(isArray(array)||isArguments(array)){var result=result?baseUniq(baseDifference(result,array).concat(baseDifference(array,result))):array}}return result||[]}function zip(){var array=arguments.length>1?arguments:arguments[0],index=-1,length=array?max(pluck(array,"length")):0,result=Array(length<0?0:length);while(++index<length){result[index]=pluck(array,index)}return result}function zipObject(keys,values){var index=-1,length=keys?keys.length:0,result={};if(!values&&length&&!isArray(keys[0])){values=[]}while(++index<length){var key=keys[index];if(values){result[key]=values[index]}else if(key){result[key[0]]=key[1]}}return result}function after(n,func){if(!isFunction(func)){throw new TypeError}return function(){if(--n<1){return func.apply(this,arguments)}}}function bind(func,thisArg){return arguments.length>2?createWrapper(func,17,slice(arguments,2),null,thisArg):createWrapper(func,1,null,null,thisArg)}function bindAll(object){var funcs=arguments.length>1?baseFlatten(arguments,true,false,1):functions(object),index=-1,length=funcs.length;while(++index<length){var key=funcs[index];object[key]=createWrapper(object[key],1,null,null,object)}return object}function bindKey(object,key){return arguments.length>2?createWrapper(key,19,slice(arguments,2),null,object):createWrapper(key,3,null,null,object)}function compose(){var funcs=arguments,length=funcs.length;while(length--){if(!isFunction(funcs[length])){throw new TypeError}}return function(){var args=arguments,length=funcs.length;while(length--){args=[funcs[length].apply(this,args)]}return args[0]}}function curry(func,arity){arity=typeof arity=="number"?arity:+arity||func.length;return createWrapper(func,4,null,null,null,arity)}function debounce(func,wait,options){var args,maxTimeoutId,result,stamp,thisArg,timeoutId,trailingCall,lastCalled=0,maxWait=false,trailing=true;if(!isFunction(func)){throw new TypeError}wait=nativeMax(0,wait)||0;if(options===true){var leading=true;trailing=false}else if(isObject(options)){leading=options.leading;maxWait="maxWait"in options&&(nativeMax(wait,options.maxWait)||0);trailing="trailing"in options?options.trailing:trailing}var delayed=function(){var remaining=wait-(now()-stamp);if(remaining<=0){if(maxTimeoutId){clearTimeout(maxTimeoutId)}var isCalled=trailingCall;maxTimeoutId=timeoutId=trailingCall=undefined;if(isCalled){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}}else{timeoutId=setTimeout(delayed,remaining)}};var maxDelayed=function(){if(timeoutId){clearTimeout(timeoutId)}maxTimeoutId=timeoutId=trailingCall=undefined;if(trailing||maxWait!==wait){lastCalled=now();result=func.apply(thisArg,args);if(!timeoutId&&!maxTimeoutId){args=thisArg=null}}};return function(){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;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=null}return result}}function defer(func){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,1);return setTimeout(function(){func.apply(undefined,args)},1)}function delay(func,wait){if(!isFunction(func)){throw new TypeError}var args=slice(arguments,2);return setTimeout(function(){func.apply(undefined,args)},wait)}function memoize(func,resolver){if(!isFunction(func)){throw new TypeError}var memoized=function(){var cache=memoized.cache,key=resolver?resolver.apply(this,arguments):keyPrefix+arguments[0];return hasOwnProperty.call(cache,key)?cache[key]:cache[key]=func.apply(this,arguments)};memoized.cache={};return memoized}function once(func){var ran,result;if(!isFunction(func)){throw new TypeError}return function(){if(ran){return result}ran=true;result=func.apply(this,arguments);func=null;return result}}function partial(func){return createWrapper(func,16,slice(arguments,1))}function partialRight(func){return createWrapper(func,32,null,slice(arguments,1))}function throttle(func,wait,options){var leading=true,trailing=true;if(!isFunction(func)){throw new TypeError}if(options===false){leading=false}else if(isObject(options)){leading="leading"in options?options.leading:leading;trailing="trailing"in options?options.trailing:trailing}debounceOptions.leading=leading;debounceOptions.maxWait=wait;debounceOptions.trailing=trailing;return debounce(func,wait,debounceOptions)}function wrap(value,wrapper){return createWrapper(wrapper,16,[value])}function constant(value){return function(){return value}}function createCallback(func,thisArg,argCount){var type=typeof func;if(func==null||type=="function"){return baseCreateCallback(func,thisArg,argCount)}if(type!="object"){return property(func)}var props=keys(func),key=props[0],a=func[key];if(props.length==1&&a===a&&!isObject(a)){return function(object){var b=object[key];return a===b&&(a!==0||1/a==1/b)}}return function(object){var length=props.length,result=false;while(length--){if(!(result=baseIsEqual(object[props[length]],func[props[length]],null,true))){break}}return result}}function escape(string){return string==null?"":String(string).replace(reUnescapedHtml,escapeHtmlChar)}function identity(value){return value}function mixin(object,source,options){var chain=true,methodNames=source&&functions(source);if(!source||!options&&!methodNames.length){if(options==null){options=source}ctor=lodashWrapper;source=object;object=lodash;methodNames=functions(source)}if(options===false){chain=false}else if(isObject(options)&&"chain"in options){chain=options.chain}var ctor=object,isFunc=isFunction(ctor);forEach(methodNames,function(methodName){var func=object[methodName]=source[methodName];if(isFunc){ctor.prototype[methodName]=function(){var chainAll=this.__chain__,value=this.__wrapped__,args=[value];push.apply(args,arguments);var result=func.apply(object,args);if(chain||chainAll){if(value===result&&isObject(result)){return this}result=new ctor(result);result.__chain__=chainAll}return result}}})}function noConflict(){context._=oldDash;return this}function noop(){}var now=isNative(now=Date.now)&&now||function(){return(new Date).getTime()};var parseInt=nativeParseInt(whitespace+"08")==8?nativeParseInt:function(value,radix){return nativeParseInt(isString(value)?value.replace(reLeadingSpacesAndZeros,""):value,radix||0)};function property(key){return function(object){return object[key]}}function random(min,max,floating){var noMin=min==null,noMax=max==null;if(floating==null){if(typeof min=="boolean"&&noMax){floating=min;min=1}else if(!noMax&&typeof max=="boolean"){floating=max;noMax=true}}if(noMin&&noMax){max=1}min=+min||0;if(noMax){max=min;min=0}else{max=+max||0}if(floating||min%1||max%1){var rand=nativeRandom();return nativeMin(min+rand*(max-min+parseFloat("1e-"+((rand+"").length-1))),max)}return baseRandom(min,max)}function result(object,key){if(object){var value=object[key];return isFunction(value)?object[key]():value}}function template(text,data,options){var settings=lodash.templateSettings;text=String(text||"");options=defaults({},options,settings);var imports=defaults({},options.imports,settings.imports),importsKeys=keys(imports),importsValues=values(imports);var isEvaluating,index=0,interpolate=options.interpolate||reNoMatch,source="__p += '";var reDelimiters=RegExp((options.escape||reNoMatch).source+"|"+interpolate.source+"|"+(interpolate===reInterpolate?reEsTemplate:reNoMatch).source+"|"+(options.evaluate||reNoMatch).source+"|$","g");text.replace(reDelimiters,function(match,escapeValue,interpolateValue,esTemplateValue,evaluateValue,offset){interpolateValue||(interpolateValue=esTemplateValue);source+=text.slice(index,offset).replace(reUnescapedString,escapeStringChar);if(escapeValue){source+="' +\n__e("+escapeValue+") +\n'"}if(evaluateValue){isEvaluating=true;source+="';\n"+evaluateValue+";\n__p += '"}if(interpolateValue){source+="' +\n((__t = ("+interpolateValue+")) == null ? '' : __t) +\n'"}index=offset+match.length;return match});source+="';\n";var variable=options.variable,hasVariable=variable;if(!hasVariable){variable="obj";source="with ("+variable+") {\n"+source+"\n}\n"}source=(isEvaluating?source.replace(reEmptyStringLeading,""):source).replace(reEmptyStringMiddle,"$1").replace(reEmptyStringTrailing,"$1;");source="function("+variable+") {\n"+(hasVariable?"":variable+" || ("+variable+" = {});\n")+"var __t, __p = '', __e = _.escape"+(isEvaluating?", __j = Array.prototype.join;\n"+"function print() { __p += __j.call(arguments, '') }\n":";\n")+source+"return __p\n}";var sourceURL="\n/*\n//# sourceURL="+(options.sourceURL||"/lodash/template/source["+templateCounter++ +"]")+"\n*/";try{var result=Function(importsKeys,"return "+source+sourceURL).apply(undefined,importsValues)}catch(e){e.source=source;throw e}if(data){return result(data)}result.source=source;return result}function times(n,callback,thisArg){n=(n=+n)>-1?n:0;var index=-1,result=Array(n);callback=baseCreateCallback(callback,thisArg,1);while(++index<n){result[index]=callback(index)}return result}function unescape(string){return string==null?"":String(string).replace(reEscapedHtml,unescapeHtmlChar)}function uniqueId(prefix){var id=++idCounter;return String(prefix==null?"":prefix)+id}function chain(value){value=new lodashWrapper(value);value.__chain__=true;return value}function tap(value,interceptor){interceptor(value);return value}function wrapperChain(){this.__chain__=true;return this}function wrapperToString(){return String(this.__wrapped__)}function wrapperValueOf(){return this.__wrapped__}lodash.after=after;lodash.assign=assign;lodash.at=at;lodash.bind=bind;lodash.bindAll=bindAll;lodash.bindKey=bindKey;lodash.chain=chain;lodash.compact=compact;lodash.compose=compose;lodash.constant=constant;lodash.countBy=countBy;lodash.create=create;lodash.createCallback=createCallback;lodash.curry=curry;lodash.debounce=debounce;lodash.defaults=defaults;lodash.defer=defer;lodash.delay=delay;lodash.difference=difference;lodash.filter=filter;lodash.flatten=flatten;lodash.forEach=forEach;lodash.forEachRight=forEachRight;lodash.forIn=forIn;lodash.forInRight=forInRight;lodash.forOwn=forOwn;lodash.forOwnRight=forOwnRight;lodash.functions=functions;lodash.groupBy=groupBy;lodash.indexBy=indexBy;lodash.initial=initial;lodash.intersection=intersection;lodash.invert=invert;lodash.invoke=invoke;lodash.keys=keys;lodash.map=map;lodash.mapValues=mapValues;lodash.max=max;lodash.memoize=memoize;lodash.merge=merge;lodash.min=min;lodash.omit=omit;lodash.once=once;lodash.pairs=pairs;lodash.partial=partial;lodash.partialRight=partialRight;lodash.pick=pick;lodash.pluck=pluck;lodash.property=property;lodash.pull=pull;lodash.range=range;lodash.reject=reject;lodash.remove=remove;lodash.rest=rest;lodash.shuffle=shuffle;lodash.sortBy=sortBy;lodash.tap=tap;lodash.throttle=throttle;lodash.times=times;lodash.toArray=toArray;lodash.transform=transform;lodash.union=union;lodash.uniq=uniq;lodash.values=values;lodash.where=where;lodash.without=without;lodash.wrap=wrap;lodash.xor=xor;lodash.zip=zip;lodash.zipObject=zipObject;lodash.collect=map;lodash.drop=rest;lodash.each=forEach;lodash.eachRight=forEachRight;lodash.extend=assign;lodash.methods=functions;lodash.object=zipObject;lodash.select=filter;lodash.tail=rest;lodash.unique=uniq;lodash.unzip=zip;mixin(lodash);lodash.clone=clone;lodash.cloneDeep=cloneDeep;lodash.contains=contains;lodash.escape=escape;lodash.every=every;lodash.find=find;lodash.findIndex=findIndex;lodash.findKey=findKey;lodash.findLast=findLast;lodash.findLastIndex=findLastIndex;lodash.findLastKey=findLastKey;lodash.has=has;lodash.identity=identity;lodash.indexOf=indexOf;lodash.isArguments=isArguments;lodash.isArray=isArray;lodash.isBoolean=isBoolean;lodash.isDate=isDate;lodash.isElement=isElement;lodash.isEmpty=isEmpty;lodash.isEqual=isEqual;lodash.isFinite=isFinite;lodash.isFunction=isFunction;lodash.isNaN=isNaN;lodash.isNull=isNull;lodash.isNumber=isNumber;lodash.isObject=isObject;lodash.isPlainObject=isPlainObject;lodash.isRegExp=isRegExp;lodash.isString=isString;lodash.isUndefined=isUndefined;lodash.lastIndexOf=lastIndexOf;lodash.mixin=mixin;lodash.noConflict=noConflict;lodash.noop=noop;lodash.now=now;lodash.parseInt=parseInt;lodash.random=random;lodash.reduce=reduce;lodash.reduceRight=reduceRight;lodash.result=result;lodash.runInContext=runInContext; lodash.size=size;lodash.some=some;lodash.sortedIndex=sortedIndex;lodash.template=template;lodash.unescape=unescape;lodash.uniqueId=uniqueId;lodash.all=every;lodash.any=some;lodash.detect=find;lodash.findWhere=find;lodash.foldl=reduce;lodash.foldr=reduceRight;lodash.include=contains;lodash.inject=reduce;mixin(function(){var source={};forOwn(lodash,function(func,methodName){if(!lodash.prototype[methodName]){source[methodName]=func}});return source}(),false);lodash.first=first;lodash.last=last;lodash.sample=sample;lodash.take=first;lodash.head=first;forOwn(lodash,function(func,methodName){var callbackable=methodName!=="sample";if(!lodash.prototype[methodName]){lodash.prototype[methodName]=function(n,guard){var chainAll=this.__chain__,result=func(this.__wrapped__,n,guard);return!chainAll&&(n==null||guard&&!(callbackable&&typeof n=="function"))?result:new lodashWrapper(result,chainAll)}}});lodash.VERSION="2.4.1";lodash.prototype.chain=wrapperChain;lodash.prototype.toString=wrapperToString;lodash.prototype.value=wrapperValueOf;lodash.prototype.valueOf=wrapperValueOf;forEach(["join","pop","shift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){var chainAll=this.__chain__,result=func.apply(this.__wrapped__,arguments);return chainAll?new lodashWrapper(result,chainAll):result}});forEach(["push","reverse","sort","unshift"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){func.apply(this.__wrapped__,arguments);return this}});forEach(["concat","slice","splice"],function(methodName){var func=arrayRef[methodName];lodash.prototype[methodName]=function(){return new lodashWrapper(func.apply(this.__wrapped__,arguments),this.__chain__)}});return lodash}var _=runInContext();if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){root._=_;define(function(){return _})}else if(freeExports&&freeModule){if(moduleExports){(freeModule.exports=_)._=_}else{freeExports._=_}}else{root._=_}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],109:[function(require,module,exports){"use strict";var originalObject=Object;var originalDefProp=Object.defineProperty;var originalCreate=Object.create;function defProp(obj,name,value){if(originalDefProp)try{originalDefProp.call(originalObject,obj,name,{value:value})}catch(definePropertyIsBrokenInIE8){obj[name]=value}else{obj[name]=value}}function makeSafeToCall(fun){if(fun){defProp(fun,"call",fun.call);defProp(fun,"apply",fun.apply)}return fun}makeSafeToCall(originalDefProp);makeSafeToCall(originalCreate);var hasOwn=makeSafeToCall(Object.prototype.hasOwnProperty);var numToStr=makeSafeToCall(Number.prototype.toString);var strSlice=makeSafeToCall(String.prototype.slice);var cloner=function(){};function create(prototype){if(originalCreate){return originalCreate.call(originalObject,prototype)}cloner.prototype=prototype||null;return new cloner}var rand=Math.random;var uniqueKeys=create(null);function makeUniqueKey(){do var uniqueKey=internString(strSlice.call(numToStr.call(rand(),36),2));while(hasOwn.call(uniqueKeys,uniqueKey));return uniqueKeys[uniqueKey]=uniqueKey}function internString(str){var obj={};obj[str]=true;return Object.keys(obj)[0]}defProp(exports,"makeUniqueKey",makeUniqueKey);var originalGetOPNs=Object.getOwnPropertyNames;Object.getOwnPropertyNames=function getOwnPropertyNames(object){for(var names=originalGetOPNs(object),src=0,dst=0,len=names.length;src<len;++src){if(!hasOwn.call(uniqueKeys,names[src])){if(src>dst){names[dst]=names[src]}++dst}}names.length=dst;return names};function defaultCreatorFn(object){return create(null)}function makeAccessor(secretCreatorFn){var brand=makeUniqueKey();var passkey=create(null);secretCreatorFn=secretCreatorFn||defaultCreatorFn;function register(object){var secret;function vault(key,forget){if(key===passkey){return forget?secret=null:secret||(secret=secretCreatorFn(object))}}defProp(object,brand,vault)}function accessor(object){if(!hasOwn.call(object,brand))register(object);return object[brand](passkey)}accessor.forget=function(object){if(hasOwn.call(object,brand))object[brand](passkey,true)};return accessor}defProp(exports,"makeAccessor",makeAccessor)},{}],110:[function(require,module,exports){var regenerate=require("regenerate");exports.REGULAR={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,65535),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().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:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,65535)};exports.UNICODE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().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:regenerate(95).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)};exports.UNICODE_IGNORE_CASE={d:regenerate().addRange(48,57),D:regenerate().addRange(0,47).addRange(58,1114111),s:regenerate(32,160,5760,6158,8239,8287,12288,65279).addRange(9,13).addRange(8192,8202).addRange(8232,8233),S:regenerate().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:regenerate(95,383,8490).addRange(48,57).addRange(65,90).addRange(97,122),W:regenerate(75,83,96).addRange(0,47).addRange(58,64).addRange(91,94).addRange(123,1114111)}},{regenerate:112}],111:[function(require,module,exports){module.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}},{}],112:[function(require,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var ERRORS={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 HIGH_SURROGATE_MIN=55296;var HIGH_SURROGATE_MAX=56319;var LOW_SURROGATE_MIN=56320;var LOW_SURROGATE_MAX=57343;var regexNull=/\\x00([^0123456789]|$)/g;var object={};var hasOwnProperty=object.hasOwnProperty;var extend=function(destination,source){var key;for(key in source){if(hasOwnProperty.call(source,key)){destination[key]=source[key]}}return destination};var forEach=function(array,callback){var index=-1;var length=array.length;while(++index<length){callback(array[index],index)}};var toString=object.toString;var isArray=function(value){return toString.call(value)=="[object Array]"};var isNumber=function(value){return typeof value=="number"||toString.call(value)=="[object Number]"};var zeroes="0000";var pad=function(number,totalCharacters){var string=String(number);return string.length<totalCharacters?(zeroes+string).slice(-totalCharacters):string};var hex=function(number){return Number(number).toString(16).toUpperCase()};var slice=[].slice;var dataFromCodePoints=function(codePoints){var index=-1;var length=codePoints.length;var max=length-1;var result=[];var isStart=true;var tmp;var previous=0;while(++index<length){tmp=codePoints[index];if(isStart){result.push(tmp);previous=tmp;isStart=false}else{if(tmp==previous+1){if(index!=max){previous=tmp;continue}else{isStart=true;result.push(tmp+1)}}else{result.push(previous+1,tmp);previous=tmp}}}if(!isStart){result.push(tmp+1)}return result};var dataRemove=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){if(codePoint==start){if(end==start+1){data.splice(index,2);return data}else{data[index]=codePoint+1;return data}}else if(codePoint==end-1){data[index+1]=codePoint;return data}else{data.splice(index,2,start,codePoint,codePoint+1,end);return data}}index+=2}return data};var dataRemoveRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}var index=0;var start;var end;while(index<data.length){start=data[index];end=data[index+1]-1;if(start>rangeEnd){return data}if(rangeStart<=start&&rangeEnd>=end){data.splice(index,2);continue}if(rangeStart>=start&&rangeEnd<end){if(rangeStart==start){data[index]=rangeEnd+1;data[index+1]=end+1;return data}data.splice(index,2,start,rangeStart,rangeEnd+1,end+1);return data}if(rangeStart>=start&&rangeStart<=end){data[index+1]=rangeStart}else if(rangeEnd>=start&&rangeEnd<=end){data[index]=rangeEnd+1;return data}index+=2}return data};var dataAdd=function(data,codePoint){var index=0;var start;var end;var lastIndex=null;var length=data.length;if(codePoint<0||codePoint>1114111){throw RangeError(ERRORS.codePointRange)}while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return data}if(codePoint==start-1){data[index]=codePoint;return data}if(start>codePoint){data.splice(lastIndex!=null?lastIndex+2:0,0,codePoint,codePoint+1);return data}if(codePoint==end){if(codePoint+1==data[index+2]){data.splice(index,4,start,data[index+3]);return data}data[index+1]=codePoint+1;return data}lastIndex=index;index+=2}data.push(codePoint,codePoint+1);return data};var dataAddData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataAdd(data,start)}else{data=dataAddRange(data,start,end)}index+=2}return data};var dataRemoveData=function(dataA,dataB){var index=0;var start;var end;var data=dataA.slice();var length=dataB.length;while(index<length){start=dataB[index];end=dataB[index+1]-1;if(start==end){data=dataRemove(data,start)}else{data=dataRemoveRange(data,start,end)}index+=2}return data};var dataAddRange=function(data,rangeStart,rangeEnd){if(rangeEnd<rangeStart){throw Error(ERRORS.rangeOrder)}if(rangeStart<0||rangeStart>1114111||rangeEnd<0||rangeEnd>1114111){throw RangeError(ERRORS.codePointRange)}var index=0;var start;var end;var added=false;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(added){if(start==rangeEnd+1){data.splice(index-1,2);return data}if(start>rangeEnd){return data}if(start>=rangeStart&&start<=rangeEnd){if(end>rangeStart&&end-1<=rangeEnd){data.splice(index,2);index-=2}else{data.splice(index-1,2);index-=2}}}else if(start==rangeEnd+1){data[index]=rangeStart;return data}else if(start>rangeEnd){data.splice(index,0,rangeStart,rangeEnd+1);return data}else if(rangeStart>=start&&rangeStart<end&&rangeEnd+1<=end){return data}else if(rangeStart>=start&&rangeStart<end||end==rangeStart){data[index+1]=rangeEnd+1;added=true}else if(rangeStart<=start&&rangeEnd+1>=end){data[index]=rangeStart;data[index+1]=rangeEnd+1;added=true}index+=2}if(!added){data.push(rangeStart,rangeEnd+1)}return data};var dataContains=function(data,codePoint){var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1];if(codePoint>=start&&codePoint<end){return true}index+=2}return false};var dataIntersection=function(data,codePoints){var index=0;var length=codePoints.length;var codePoint;var result=[];while(index<length){codePoint=codePoints[index];if(dataContains(data,codePoint)){result.push(codePoint)}++index}return dataFromCodePoints(result)};var dataIsEmpty=function(data){return!data.length};var dataIsSingleton=function(data){return data.length==2&&data[0]+1==data[1]};var dataToArray=function(data){var index=0;var start;var end;var result=[];var length=data.length;while(index<length){start=data[index];end=data[index+1];while(start<end){result.push(start);++start}index+=2}return result};var floor=Math.floor;var highSurrogate=function(codePoint){return parseInt(floor((codePoint-65536)/1024)+HIGH_SURROGATE_MIN,10)};var lowSurrogate=function(codePoint){return parseInt((codePoint-65536)%1024+LOW_SURROGATE_MIN,10)};var stringFromCharCode=String.fromCharCode;var codePointToString=function(codePoint){var string;if(codePoint==9){string="\\t"}else if(codePoint==10){string="\\n"}else if(codePoint==12){string="\\f"}else if(codePoint==13){string="\\r"}else if(codePoint==92){string="\\\\"}else if(codePoint==36||codePoint>=40&&codePoint<=43||codePoint==45||codePoint==46||codePoint==63||codePoint>=91&&codePoint<=94||codePoint>=123&&codePoint<=125){string="\\"+stringFromCharCode(codePoint)}else if(codePoint>=32&&codePoint<=126){string=stringFromCharCode(codePoint)}else if(codePoint<=255){string="\\x"+pad(hex(codePoint),2)}else{string="\\u"+pad(hex(codePoint),4)}return string};var symbolToCodePoint=function(symbol){var length=symbol.length;var first=symbol.charCodeAt(0);var second;if(first>=HIGH_SURROGATE_MIN&&first<=HIGH_SURROGATE_MAX&&length>1){second=symbol.charCodeAt(1);return(first-HIGH_SURROGATE_MIN)*1024+second-LOW_SURROGATE_MIN+65536}return first};var createBMPCharacterClasses=function(data){var result="";var index=0;var start;var end;var length=data.length;if(dataIsSingleton(data)){return codePointToString(data[0])}while(index<length){start=data[index];end=data[index+1]-1;if(start==end){result+=codePointToString(start)}else if(start+1==end){result+=codePointToString(start)+codePointToString(end)}else{result+=codePointToString(start)+"-"+codePointToString(end)}index+=2}return"["+result+"]"};var splitAtBMP=function(data){var loneHighSurrogates=[];var bmp=[];var astral=[];var index=0;var start;var end;var length=data.length;while(index<length){start=data[index];end=data[index+1]-1;if(start<=65535&&end<=65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){if(end<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,end+1)}else{loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,end+1)}}else if(end>=HIGH_SURROGATE_MIN&&end<=HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN);loneHighSurrogates.push(HIGH_SURROGATE_MIN,end+1)}else if(start<HIGH_SURROGATE_MIN&&end>HIGH_SURROGATE_MAX){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,end+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,end+1)}}else if(start<=65535&&end>65535){if(start>=HIGH_SURROGATE_MIN&&start<=HIGH_SURROGATE_MAX){loneHighSurrogates.push(start,HIGH_SURROGATE_MAX+1);bmp.push(HIGH_SURROGATE_MAX+1,65535+1)}else if(start<HIGH_SURROGATE_MIN){bmp.push(start,HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1,65535+1);loneHighSurrogates.push(HIGH_SURROGATE_MIN,HIGH_SURROGATE_MAX+1)}else{bmp.push(start,65535+1)}astral.push(65535+1,end+1)}else{astral.push(start,end+1)}index+=2}return{loneHighSurrogates:loneHighSurrogates,bmp:bmp,astral:astral}};var optimizeSurrogateMappings=function(surrogateMappings){var result=[];var tmpLow=[];var addLow=false;var mapping;var nextMapping;var highSurrogates;var lowSurrogates;var nextHighSurrogates;var nextLowSurrogates;var index=-1;var length=surrogateMappings.length;while(++index<length){mapping=surrogateMappings[index];nextMapping=surrogateMappings[index+1];if(!nextMapping){result.push(mapping);continue}highSurrogates=mapping[0];lowSurrogates=mapping[1];nextHighSurrogates=nextMapping[0];nextLowSurrogates=nextMapping[1];tmpLow=lowSurrogates;while(nextHighSurrogates&&highSurrogates[0]==nextHighSurrogates[0]&&highSurrogates[1]==nextHighSurrogates[1]){if(dataIsSingleton(nextLowSurrogates)){tmpLow=dataAdd(tmpLow,nextLowSurrogates[0])}else{tmpLow=dataAddRange(tmpLow,nextLowSurrogates[0],nextLowSurrogates[1]-1)}++index;mapping=surrogateMappings[index];highSurrogates=mapping[0];lowSurrogates=mapping[1];nextMapping=surrogateMappings[index+1];nextHighSurrogates=nextMapping&&nextMapping[0];nextLowSurrogates=nextMapping&&nextMapping[1];addLow=true}result.push([highSurrogates,addLow?tmpLow:lowSurrogates]);addLow=false}return optimizeByLowSurrogates(result)};var optimizeByLowSurrogates=function(surrogateMappings){if(surrogateMappings.length==1){return surrogateMappings}var index=-1;var innerIndex=-1;while(++index<surrogateMappings.length){var mapping=surrogateMappings[index];var lowSurrogates=mapping[1];var lowSurrogateStart=lowSurrogates[0];var lowSurrogateEnd=lowSurrogates[1];innerIndex=index;while(++innerIndex<surrogateMappings.length){var otherMapping=surrogateMappings[innerIndex];var otherLowSurrogates=otherMapping[1];var otherLowSurrogateStart=otherLowSurrogates[0];var otherLowSurrogateEnd=otherLowSurrogates[1];if(lowSurrogateStart==otherLowSurrogateStart&&lowSurrogateEnd==otherLowSurrogateEnd){if(dataIsSingleton(otherMapping[0])){mapping[0]=dataAdd(mapping[0],otherMapping[0][0])}else{mapping[0]=dataAddRange(mapping[0],otherMapping[0][0],otherMapping[0][1]-1)}surrogateMappings.splice(innerIndex,1);--innerIndex}}}return surrogateMappings};var surrogateSet=function(data){if(!data.length){return[]}var index=0;var start;var end;var startHigh;var startLow;var prevStartHigh=0;var prevEndHigh=0;var tmpLow=[];var endHigh;var endLow;var surrogateMappings=[];var length=data.length;var dataHigh=[];while(index<length){start=data[index];end=data[index+1]-1;startHigh=highSurrogate(start);startLow=lowSurrogate(start);endHigh=highSurrogate(end);endLow=lowSurrogate(end);var startsWithLowestLowSurrogate=startLow==LOW_SURROGATE_MIN;var endsWithHighestLowSurrogate=endLow==LOW_SURROGATE_MAX;var complete=false;if(startHigh==endHigh||startsWithLowestLowSurrogate&&endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh,endHigh+1],[startLow,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh,startHigh+1],[startLow,LOW_SURROGATE_MAX+1]])}if(!complete&&startHigh+1<endHigh){if(endsWithHighestLowSurrogate){surrogateMappings.push([[startHigh+1,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]]);complete=true}else{surrogateMappings.push([[startHigh+1,endHigh],[LOW_SURROGATE_MIN,LOW_SURROGATE_MAX+1]])}}if(!complete){surrogateMappings.push([[endHigh,endHigh+1],[LOW_SURROGATE_MIN,endLow+1]])}prevStartHigh=startHigh;prevEndHigh=endHigh;index+=2}return optimizeSurrogateMappings(surrogateMappings)};var createSurrogateCharacterClasses=function(surrogateMappings){var result=[];forEach(surrogateMappings,function(surrogateMapping){var highSurrogates=surrogateMapping[0];var lowSurrogates=surrogateMapping[1];result.push(createBMPCharacterClasses(highSurrogates)+createBMPCharacterClasses(lowSurrogates))});return result.join("|")};var createCharacterClassesFromData=function(data){var result=[];var parts=splitAtBMP(data);var loneHighSurrogates=parts.loneHighSurrogates;var bmp=parts.bmp;var astral=parts.astral;var hasAstral=!dataIsEmpty(parts.astral);var hasLoneSurrogates=!dataIsEmpty(loneHighSurrogates);var surrogateMappings=surrogateSet(astral);if(!hasAstral&&hasLoneSurrogates){bmp=dataAddData(bmp,loneHighSurrogates)}if(!dataIsEmpty(bmp)){result.push(createBMPCharacterClasses(bmp))}if(surrogateMappings.length){result.push(createSurrogateCharacterClasses(surrogateMappings))}if(hasAstral&&hasLoneSurrogates){result.push(createBMPCharacterClasses(loneHighSurrogates))}return result.join("|")};var regenerate=function(value){if(arguments.length>1){value=slice.call(arguments)}if(this instanceof regenerate){this.data=[];return value?this.add(value):this}return(new regenerate).add(value)};regenerate.version="1.0.1";var proto=regenerate.prototype;extend(proto,{add:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataAddData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.add(item)});return $this}$this.data=dataAdd($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},remove:function(value){var $this=this;if(value==null){return $this}if(value instanceof regenerate){$this.data=dataRemoveData($this.data,value.data);return $this}if(arguments.length>1){value=slice.call(arguments)}if(isArray(value)){forEach(value,function(item){$this.remove(item)});return $this}$this.data=dataRemove($this.data,isNumber(value)?value:symbolToCodePoint(value));return $this},addRange:function(start,end){var $this=this;$this.data=dataAddRange($this.data,isNumber(start)?start:symbolToCodePoint(start),isNumber(end)?end:symbolToCodePoint(end));return $this},removeRange:function(start,end){var $this=this;var startCodePoint=isNumber(start)?start:symbolToCodePoint(start);var endCodePoint=isNumber(end)?end:symbolToCodePoint(end);$this.data=dataRemoveRange($this.data,startCodePoint,endCodePoint);return $this},intersection:function(argument){var $this=this;var array=argument instanceof regenerate?dataToArray(argument.data):argument;$this.data=dataIntersection($this.data,array);return $this},contains:function(codePoint){return dataContains(this.data,isNumber(codePoint)?codePoint:symbolToCodePoint(codePoint))},clone:function(){var set=new regenerate;set.data=this.data.slice(0);return set},toString:function(){var result=createCharacterClassesFromData(this.data);return result.replace(regexNull,"\\0$1")},toRegExp:function(flags){return RegExp(this.toString(),flags||"")},valueOf:function(){return dataToArray(this.data)}});proto.toArray=proto.valueOf;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return regenerate})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=regenerate}else{freeExports.regenerate=regenerate}}else{root.regenerate=regenerate}})(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],113:[function(require,module,exports){(function(global){(function(){"use strict";var objectTypes={"function":true,object:true};var root=objectTypes[typeof window]&&window||this;var oldRoot=root;var freeExports=objectTypes[typeof exports]&&exports;var freeModule=objectTypes[typeof module]&&module&&!module.nodeType&&module;var freeGlobal=freeExports&&freeModule&&typeof global=="object"&&global;if(freeGlobal&&(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal||freeGlobal.self===freeGlobal)){root=freeGlobal}var stringFromCharCode=String.fromCharCode;var floor=Math.floor;function fromCodePoint(){var MAX_SIZE=16384;var codeUnits=[];var highSurrogate;var lowSurrogate;var index=-1;var length=arguments.length;if(!length){return""}var result="";while(++index<length){var codePoint=Number(arguments[index]);if(!isFinite(codePoint)||codePoint<0||codePoint>1114111||floor(codePoint)!=codePoint){throw RangeError("Invalid code point: "+codePoint)}if(codePoint<=65535){codeUnits.push(codePoint)}else{codePoint-=65536;highSurrogate=(codePoint>>10)+55296;lowSurrogate=codePoint%1024+56320;codeUnits.push(highSurrogate,lowSurrogate)}if(index+1==length||codeUnits.length>MAX_SIZE){result+=stringFromCharCode.apply(null,codeUnits);codeUnits.length=0}}return result}function assertType(type,expected){if(expected.indexOf("|")==-1){if(type==expected){return}throw Error("Invalid node type: "+type)}expected=assertType.hasOwnProperty(expected)?assertType[expected]:assertType[expected]=RegExp("^(?:"+expected+")$");if(expected.test(type)){return}throw Error("Invalid node type: "+type)}function generate(node){var type=node.type;if(generate.hasOwnProperty(type)&&typeof generate[type]=="function"){return generate[type](node)}throw Error("Invalid node type: "+type)}function generateAlternative(node){assertType(node.type,"alternative");var terms=node.body,length=terms?terms.length:0;if(length==1){return generateTerm(terms[0])}else{var i=-1,result="";while(++i<length){result+=generateTerm(terms[i])}return result}}function generateAnchor(node){assertType(node.type,"anchor");switch(node.kind){case"start":return"^";case"end":return"$";case"boundary":return"\\b";case"not-boundary":return"\\B";default:throw Error("Invalid assertion")}}function generateAtom(node){assertType(node.type,"anchor|characterClass|characterClassEscape|dot|group|reference|value");return generate(node)}function generateCharacterClass(node){assertType(node.type,"characterClass");var classRanges=node.body,length=classRanges?classRanges.length:0;var i=-1,result="[";if(node.negative){result+="^"}while(++i<length){result+=generateClassAtom(classRanges[i])}result+="]";return result}function generateCharacterClassEscape(node){assertType(node.type,"characterClassEscape");return"\\"+node.value}function generateCharacterClassRange(node){assertType(node.type,"characterClassRange");var min=node.min,max=node.max;if(min.type=="characterClassRange"||max.type=="characterClassRange"){throw Error("Invalid character class range")}return generateClassAtom(min)+"-"+generateClassAtom(max)}function generateClassAtom(node){assertType(node.type,"anchor|characterClassEscape|characterClassRange|dot|value");return generate(node)}function generateDisjunction(node){assertType(node.type,"disjunction");var body=node.body,length=body?body.length:0;if(length==0){throw Error("No body")}else if(length==1){return generate(body[0])}else{var i=-1,result="";while(++i<length){if(i!=0){result+="|"}result+=generate(body[i])}return result}}function generateDot(node){assertType(node.type,"dot");return"."}function generateGroup(node){assertType(node.type,"group");var result="(";switch(node.behavior){case"normal":break;case"ignore":result+="?:";break;case"lookahead":result+="?=";break;case"negativeLookahead":result+="?!";break;default:throw Error("Invalid behaviour: "+node.behaviour)}var body=node.body,length=body?body.length:0;if(length==1){result+=generate(body[0])}else{var i=-1;while(++i<length){result+=generate(body[i])}}result+=")";return result}function generateQuantifier(node){assertType(node.type,"quantifier");var quantifier="",min=node.min,max=node.max;switch(max){case undefined:case null:switch(min){case 0:quantifier="*";break;case 1:quantifier="+";break;default:quantifier="{"+min+",}";break}break;default:if(min==max){quantifier="{"+min+"}"}else if(min==0&&max==1){quantifier="?"}else{quantifier="{"+min+","+max+"}"}break}if(!node.greedy){quantifier+="?"}return generateAtom(node.body[0])+quantifier}function generateReference(node){assertType(node.type,"reference");return"\\"+node.matchIndex}function generateTerm(node){assertType(node.type,"anchor|characterClass|characterClassEscape|empty|group|quantifier|reference|value");return generate(node)}function generateValue(node){assertType(node.type,"value");var kind=node.kind,codePoint=node.codePoint;switch(kind){case"controlLetter":return"\\c"+fromCodePoint(codePoint+64);case"hexadecimalEscape":return"\\x"+("00"+codePoint.toString(16).toUpperCase()).slice(-2);case"identifier":return"\\"+fromCodePoint(codePoint);case"null":return"\\"+codePoint;case"octal":return"\\"+codePoint.toString(8);case"singleEscape":switch(codePoint){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: "+codePoint)}case"symbol":return fromCodePoint(codePoint);case"unicodeEscape":return"\\u"+("0000"+codePoint.toString(16).toUpperCase()).slice(-4);case"unicodeCodePointEscape":return"\\u{"+codePoint.toString(16).toUpperCase()+"}";default:throw Error("Unsupported node kind: "+kind)}}generate.alternative=generateAlternative;generate.anchor=generateAnchor;generate.characterClass=generateCharacterClass;generate.characterClassEscape=generateCharacterClassEscape;generate.characterClassRange=generateCharacterClassRange;generate.disjunction=generateDisjunction;generate.dot=generateDot;generate.group=generateGroup;generate.quantifier=generateQuantifier;generate.reference=generateReference;generate.value=generateValue;if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return{generate:generate}})}else if(freeExports&&freeModule){freeExports.generate=generate}else{root.regjsgen={generate:generate}}}).call(this)}).call(this,typeof global!=="undefined"?global:typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],114:[function(require,module,exports){(function(){function parse(str,flags){var hasUnicodeFlag=(flags||"").indexOf("u")!==-1;var pos=0;var closedCaptureCounter=0;function addRaw(node){node.raw=str.substring(node.range[0],node.range[1]);return node}function updateRawStart(node,start){node.range[0]=start;return addRaw(node)}function createAnchor(kind,rawLength){return addRaw({type:"anchor",kind:kind,range:[pos-rawLength,pos]})}function createValue(kind,codePoint,from,to){return addRaw({type:"value",kind:kind,codePoint:codePoint,range:[from,to]})}function createEscaped(kind,codePoint,value,fromOffset){fromOffset=fromOffset||0;return createValue(kind,codePoint,pos-(value.length+fromOffset),pos)}function createCharacter(matches){var _char=matches[0];var first=_char.charCodeAt(0);if(hasUnicodeFlag){var second;if(_char.length===1&&first>=55296&&first<=56319){second=lookahead().charCodeAt(0);if(second>=56320&&second<=57343){pos++;return createValue("symbol",(first-55296)*1024+second-56320+65536,pos-2,pos)}}}return createValue("symbol",first,pos-1,pos)}function createDisjunction(alternatives,from,to){return addRaw({type:"disjunction",body:alternatives,range:[from,to]})}function createDot(){return addRaw({type:"dot",range:[pos-1,pos]})}function createCharacterClassEscape(value){return addRaw({type:"characterClassEscape",value:value,range:[pos-2,pos]}) }function createReference(matchIndex){return addRaw({type:"reference",matchIndex:parseInt(matchIndex,10),range:[pos-1-matchIndex.length,pos]})}function createGroup(behavior,disjunction,from,to){return addRaw({type:"group",behavior:behavior,body:disjunction,range:[from,to]})}function createQuantifier(min,max,from,to){if(to==null){from=pos-1;to=pos}return addRaw({type:"quantifier",min:min,max:max,greedy:true,body:null,range:[from,to]})}function createAlternative(terms,from,to){return addRaw({type:"alternative",body:terms,range:[from,to]})}function createCharacterClass(classRanges,negative,from,to){return addRaw({type:"characterClass",body:classRanges,negative:negative,range:[from,to]})}function createClassRange(min,max,from,to){if(min.codePoint>max.codePoint){throw SyntaxError("invalid range in character class")}return addRaw({type:"characterClassRange",min:min,max:max,range:[from,to]})}function flattenBody(body){if(body.type==="alternative"){return body.body}else{return[body]}}function isEmpty(obj){return obj.type==="empty"}function incr(amount){amount=amount||1;var res=str.substring(pos,pos+amount);pos+=amount||1;return res}function skip(value){if(!match(value)){throw SyntaxError("character: "+value)}}function match(value){if(str.indexOf(value,pos)===pos){return incr(value.length)}}function lookahead(){return str[pos]}function current(value){return str.indexOf(value,pos)===pos}function next(value){return str[pos+1]===value}function matchReg(regExp){var subStr=str.substring(pos);var res=subStr.match(regExp);if(res){res.range=[];res.range[0]=pos;incr(res[0].length);res.range[1]=pos}return res}function parseDisjunction(){var res=[],from=pos;res.push(parseAlternative());while(match("|")){res.push(parseAlternative())}if(res.length===1){return res[0]}return createDisjunction(res,from,pos)}function parseAlternative(){var res=[],from=pos;var term;while(term=parseTerm()){res.push(term)}if(res.length===1){return res[0]}return createAlternative(res,from,pos)}function parseTerm(){if(pos>=str.length||current("|")||current(")")){return null}var anchor=parseAnchor();if(anchor){return anchor}var atom=parseAtom();if(!atom){throw SyntaxError("Expected atom")}var quantifier=parseQuantifier()||false;if(quantifier){quantifier.body=flattenBody(atom);updateRawStart(quantifier,atom.range[0]);return quantifier}return atom}function parseGroup(matchA,typeA,matchB,typeB){var type=null,from=pos;if(match(matchA)){type=typeA}else if(match(matchB)){type=typeB}else{return false}var body=parseDisjunction();if(!body){throw SyntaxError("Expected disjunction")}skip(")");var group=createGroup(type,flattenBody(body),from,pos);if(type=="normal"){closedCaptureCounter++}return group}function parseAnchor(){var res,from=pos;if(match("^")){return createAnchor("start",1)}else if(match("$")){return createAnchor("end",1)}else if(match("\\b")){return createAnchor("boundary",2)}else if(match("\\B")){return createAnchor("not-boundary",2)}else{return parseGroup("(?=","lookahead","(?!","negativeLookahead")}}function parseQuantifier(){var res;var quantifier;var min,max;if(match("*")){quantifier=createQuantifier(0)}else if(match("+")){quantifier=createQuantifier(1)}else if(match("?")){quantifier=createQuantifier(0,1)}else if(res=matchReg(/^\{([0-9]+)\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,min,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),\}/)){min=parseInt(res[1],10);quantifier=createQuantifier(min,undefined,res.range[0],res.range[1])}else if(res=matchReg(/^\{([0-9]+),([0-9]+)\}/)){min=parseInt(res[1],10);max=parseInt(res[2],10);if(min>max){throw SyntaxError("numbers out of order in {} quantifier")}quantifier=createQuantifier(min,max,res.range[0],res.range[1])}if(quantifier){if(match("?")){quantifier.greedy=false;quantifier.range[1]+=1}}return quantifier}function parseAtom(){var res;if(res=matchReg(/^[^^$\\.*+?(){[|]/)){return createCharacter(res)}else if(match(".")){return createDot()}else if(match("\\")){res=parseAtomEscape();if(!res){throw SyntaxError("atomEscape")}return res}else if(res=parseCharacterClass()){return res}else{return parseGroup("(?:","ignore","(","normal")}}function parseUnicodeSurrogatePairEscape(firstEscape){if(hasUnicodeFlag){var first,second;if(firstEscape.kind=="unicodeEscape"&&(first=firstEscape.codePoint)>=55296&&first<=56319&&current("\\")&&next("u")){var prevPos=pos;pos++;var secondEscape=parseClassEscape();if(secondEscape.kind=="unicodeEscape"&&(second=secondEscape.codePoint)>=56320&&second<=57343){firstEscape.range[1]=secondEscape.range[1];firstEscape.codePoint=(first-55296)*1024+second-56320+65536;firstEscape.type="value";firstEscape.kind="unicodeCodePointEscape";addRaw(firstEscape)}else{pos=prevPos}}}return firstEscape}function parseClassEscape(){return parseAtomEscape(true)}function parseAtomEscape(insideCharacterClass){var res;res=parseDecimalEscape();if(res){return res}if(insideCharacterClass){if(match("b")){return createEscaped("singleEscape",8,"\\b")}else if(match("B")){throw SyntaxError("\\B not possible inside of CharacterClass")}}res=parseCharacterEscape();return res}function parseDecimalEscape(){var res,match;if(res=matchReg(/^(?!0)\d+/)){match=res[0];var refIdx=parseInt(res[0],10);if(refIdx<=closedCaptureCounter){return createReference(res[0])}else{incr(-res[0].length);if(res=matchReg(/^[0-7]{1,3}/)){return createEscaped("octal",parseInt(res[0],8),res[0],1)}else{res=createCharacter(matchReg(/^[89]/));return updateRawStart(res,res.range[0]-1)}}}else if(res=matchReg(/^[0-7]{1,3}/)){match=res[0];if(/^0{1,3}$/.test(match)){return createEscaped("null",0,"0",match.length+1)}else{return createEscaped("octal",parseInt(match,8),match,1)}}else if(res=matchReg(/^[dDsSwW]/)){return createCharacterClassEscape(res[0])}return false}function parseCharacterEscape(){var res;if(res=matchReg(/^[fnrtv]/)){var codePoint=0;switch(res[0]){case"t":codePoint=9;break;case"n":codePoint=10;break;case"v":codePoint=11;break;case"f":codePoint=12;break;case"r":codePoint=13;break}return createEscaped("singleEscape",codePoint,"\\"+res[0])}else if(res=matchReg(/^c([a-zA-Z])/)){return createEscaped("controlLetter",res[1].charCodeAt(0)%32,res[1],2)}else if(res=matchReg(/^x([0-9a-fA-F]{2})/)){return createEscaped("hexadecimalEscape",parseInt(res[1],16),res[1],2)}else if(res=matchReg(/^u([0-9a-fA-F]{4})/)){return parseUnicodeSurrogatePairEscape(createEscaped("unicodeEscape",parseInt(res[1],16),res[1],2))}else if(hasUnicodeFlag&&(res=matchReg(/^u\{([0-9a-fA-F]{1,6})\}/))){return createEscaped("unicodeCodePointEscape",parseInt(res[1],16),res[1],4)}else{return parseIdentityEscape()}}function isIdentifierPart(ch){var NonAsciiIdentifierPart=new RegExp("[ªµºÀ-ÖØ-öø-ˁˆ-ˑˠ-ˤˬˮ̀-ʹͶͷͺ-ͽͿΆΈ-ΊΌΎ-ΡΣ-ϵϷ-ҁ҃-҇Ҋ-ԯԱ-Ֆՙա-և֑-ׇֽֿׁׂׅׄא-תװ-ײؐ-ؚؠ-٩ٮ-ۓە-ۜ۟-۪ۨ-ۼۿܐ-݊ݍ-ޱ߀-ߵߺࠀ-࠭ࡀ-࡛ࢠ-ࢲࣤ-ॣ०-९ॱ-ঃঅ-ঌএঐও-নপ-রলশ-হ়-ৄেৈো-ৎৗড়ঢ়য়-ৣ০-ৱਁ-ਃਅ-ਊਏਐਓ-ਨਪ-ਰਲਲ਼ਵਸ਼ਸਹ਼ਾ-ੂੇੈੋ-੍ੑਖ਼-ੜਫ਼੦-ੵઁ-ઃઅ-ઍએ-ઑઓ-નપ-રલળવ-હ઼-ૅે-ૉો-્ૐૠ-ૣ૦-૯ଁ-ଃଅ-ଌଏଐଓ-ନପ-ରଲଳଵ-ହ଼-ୄେୈୋ-୍ୖୗଡ଼ଢ଼ୟ-ୣ୦-୯ୱஂஃஅ-ஊஎ-ஐஒ-கஙசஜஞடணதந-பம-ஹா-ூெ-ைொ-்ௐௗ௦-௯ఀ-ఃఅ-ఌఎ-ఐఒ-నప-హఽ-ౄె-ైొ-్ౕౖౘౙౠ-ౣ౦-౯ಁ-ಃಅ-ಌಎ-ಐಒ-ನಪ-ಳವ-ಹ಼-ೄೆ-ೈೊ-್ೕೖೞೠ-ೣ೦-೯ೱೲഁ-ഃഅ-ഌഎ-ഐഒ-ഺഽ-ൄെ-ൈൊ-ൎൗൠ-ൣ൦-൯ൺ-ൿංඃඅ-ඖක-නඳ-රලව-ෆ්ා-ුූෘ-ෟ෦-෯ෲෳก-ฺเ-๎๐-๙ກຂຄງຈຊຍດ-ທນ-ຟມ-ຣລວສຫອ-ູົ-ຽເ-ໄໆ່-ໍ໐-໙ໜ-ໟༀ༘༙༠-༩༹༵༷༾-ཇཉ-ཬཱ-྄྆-ྗྙ-ྼ࿆က-၉ၐ-ႝႠ-ჅჇჍა-ჺჼ-ቈቊ-ቍቐ-ቖቘቚ-ቝበ-ኈኊ-ኍነ-ኰኲ-ኵኸ-ኾዀዂ-ዅወ-ዖዘ-ጐጒ-ጕጘ-ፚ፝-፟ᎀ-ᎏᎠ-Ᏼᐁ-ᙬᙯ-ᙿᚁ-ᚚᚠ-ᛪᛮ-ᛸᜀ-ᜌᜎ-᜔ᜠ-᜴ᝀ-ᝓᝠ-ᝬᝮ-ᝰᝲᝳក-៓ៗៜ៝០-៩᠋-᠍᠐-᠙ᠠ-ᡷᢀ-ᢪᢰ-ᣵᤀ-ᤞᤠ-ᤫᤰ-᤻᥆-ᥭᥰ-ᥴᦀ-ᦫᦰ-ᧉ᧐-᧙ᨀ-ᨛᨠ-ᩞ᩠-᩿᩼-᪉᪐-᪙ᪧ᪰-᪽ᬀ-ᭋ᭐-᭙᭫-᭳ᮀ-᯳ᰀ-᰷᱀-᱉ᱍ-ᱽ᳐-᳔᳒-ᳶ᳸᳹ᴀ-᷵᷼-ἕἘ-Ἕἠ-ὅὈ-Ὅὐ-ὗὙὛὝὟ-ώᾀ-ᾴᾶ-ᾼιῂ-ῄῆ-ῌῐ-ΐῖ-Ίῠ-Ῥῲ-ῴῶ-ῼ‌‍‿⁀⁔ⁱⁿₐ-ₜ⃐-⃥⃜⃡-⃰ℂℇℊ-ℓℕℙ-ℝℤΩℨK-ℭℯ-ℹℼ-ℿⅅ-ⅉⅎⅠ-ↈⰀ-Ⱞⰰ-ⱞⱠ-ⳤⳫ-ⳳⴀ-ⴥⴧⴭⴰ-ⵧⵯ⵿-ⶖⶠ-ⶦⶨ-ⶮⶰ-ⶶⶸ-ⶾⷀ-ⷆⷈ-ⷎⷐ-ⷖⷘ-ⷞⷠ-ⷿⸯ々-〇〡-〯〱-〵〸-〼ぁ-ゖ゙゚ゝ-ゟァ-ヺー-ヿㄅ-ㄭㄱ-ㆎㆠ-ㆺㇰ-ㇿ㐀-䶵一-鿌ꀀ-ꒌꓐ-ꓽꔀ-ꘌꘐ-ꘫꙀ-꙯ꙴ-꙽ꙿ-ꚝꚟ-꛱ꜗ-ꜟꜢ-ꞈꞋ-ꞎꞐ-ꞭꞰꞱꟷ-ꠧꡀ-ꡳꢀ-꣄꣐-꣙꣠-ꣷꣻ꤀-꤭ꤰ-꥓ꥠ-ꥼꦀ-꧀ꧏ-꧙ꧠ-ꧾꨀ-ꨶꩀ-ꩍ꩐-꩙ꩠ-ꩶꩺ-ꫂꫛ-ꫝꫠ-ꫯꫲ-꫶ꬁ-ꬆꬉ-ꬎꬑ-ꬖꬠ-ꬦꬨ-ꬮꬰ-ꭚꭜ-ꭟꭤꭥꯀ-ꯪ꯬꯭꯰-꯹가-힣ힰ-ퟆퟋ-ퟻ豈-舘並-龎ff-stﬓ-ﬗיִ-ﬨשׁ-זּטּ-לּמּנּסּףּפּצּ-ﮱﯓ-ﴽﵐ-ﶏﶒ-ﷇﷰ-ﷻ︀-️︠-︭︳︴﹍-﹏ﹰ-ﹴﹶ-ﻼ0-9A-Z_a-zヲ-하-ᅦᅧ-ᅬᅭ-ᅲᅳ-ᅵ]");return ch===36||ch===95||ch>=65&&ch<=90||ch>=97&&ch<=122||ch>=48&&ch<=57||ch===92||ch>=128&&NonAsciiIdentifierPart.test(String.fromCharCode(ch))}function parseIdentityEscape(){var ZWJ="‌";var ZWNJ="‍";var res;var tmp;if(!isIdentifierPart(lookahead())){tmp=incr();return createEscaped("identifier",tmp.charCodeAt(0),tmp,1)}if(match(ZWJ)){return createEscaped("identifier",8204,ZWJ)}else if(match(ZWNJ)){return createEscaped("identifier",8205,ZWNJ)}return null}function parseCharacterClass(){var res,from=pos;if(res=matchReg(/^\[\^/)){res=parseClassRanges();skip("]");return createCharacterClass(res,true,from,pos)}else if(match("[")){res=parseClassRanges();skip("]");return createCharacterClass(res,false,from,pos)}return null}function parseClassRanges(){var res;if(current("]")){return[]}else{res=parseNonemptyClassRanges();if(!res){throw SyntaxError("nonEmptyClassRanges")}return res}}function parseHelperClassRanges(atom){var from,to,res;if(current("-")&&!next("]")){skip("-");res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}to=pos;var classRanges=parseClassRanges();if(!classRanges){throw SyntaxError("classRanges")}from=atom.range[0];if(classRanges.type==="empty"){return[createClassRange(atom,res,from,to)]}return[createClassRange(atom,res,from,to)].concat(classRanges)}res=parseNonemptyClassRangesNoDash();if(!res){throw SyntaxError("nonEmptyClassRangesNoDash")}return[atom].concat(res)}function parseNonemptyClassRanges(){var atom=parseClassAtom();if(!atom){throw SyntaxError("classAtom")}if(current("]")){return[atom]}return parseHelperClassRanges(atom)}function parseNonemptyClassRangesNoDash(){var res=parseClassAtom();if(!res){throw SyntaxError("classAtom")}if(current("]")){return res}return parseHelperClassRanges(res)}function parseClassAtom(){if(match("-")){return createCharacter("-")}else{return parseClassAtomNoDash()}}function parseClassAtomNoDash(){var res;if(res=matchReg(/^[^\\\]-]/)){return createCharacter(res[0])}else if(match("\\")){res=parseClassEscape();if(!res){throw SyntaxError("classEscape")}return parseUnicodeSurrogatePairEscape(res)}}str=String(str);if(str===""){str="(?:)"}var result=parseDisjunction();if(result.range[1]!==str.length){throw SyntaxError("Could not parse entire input - got stuck: "+str)}return result}var regjsparser={parse:parse};if(typeof module!=="undefined"&&module.exports){module.exports=regjsparser}else{window.regjsparser=regjsparser}})()},{}],115:[function(require,module,exports){var generate=require("regjsgen").generate;var parse=require("regjsparser").parse;var regenerate=require("regenerate");var iuMappings=require("./data/iu-mappings.json");var ESCAPE_SETS=require("./data/character-class-escape-sets.js");function getCharacterClassEscapeSet(character){if(unicode){if(ignoreCase){return ESCAPE_SETS.UNICODE_IGNORE_CASE[character]}return ESCAPE_SETS.UNICODE[character]}return ESCAPE_SETS.REGULAR[character]}var object={};var hasOwnProperty=object.hasOwnProperty;function has(object,property){return hasOwnProperty.call(object,property)}var UNICODE_SET=regenerate().addRange(0,1114111);var BMP_SET=regenerate().addRange(0,65535);var DOT_SET_UNICODE=UNICODE_SET.clone().remove(10,13,8232,8233);var DOT_SET=DOT_SET_UNICODE.clone().intersection(BMP_SET);regenerate.prototype.iuAddRange=function(min,max){var $this=this;do{var folded=caseFold(min);if(folded){$this.add(folded)}}while(++min<=max);return $this};function assign(target,source){for(var key in source){target[key]=source[key]}}function update(item,pattern){var tree=parse(pattern,"");switch(tree.type){case"characterClass":case"group":case"value":break;default:tree=wrap(tree,pattern)}assign(item,tree)}function wrap(tree,pattern){return{type:"group",behavior:"ignore",body:[tree],raw:"(?:"+pattern+")"}}function caseFold(codePoint){return has(iuMappings,codePoint)?iuMappings[codePoint]:false}var ignoreCase=false;var unicode=false;function processCharacterClass(characterClassItem){var set=regenerate();var body=characterClassItem.body.forEach(function(item){switch(item.type){case"value":set.add(item.codePoint);if(ignoreCase&&unicode){var folded=caseFold(item.codePoint);if(folded){set.add(folded)}}break;case"characterClassRange":var min=item.min.codePoint;var max=item.max.codePoint;set.addRange(min,max);if(ignoreCase&&unicode){set.iuAddRange(min,max)}break;case"characterClassEscape":set.add(getCharacterClassEscapeSet(item.value));break;default:throw Error("Unknown term type: "+item.type)}});if(characterClassItem.negative){set=(unicode?UNICODE_SET:BMP_SET).clone().remove(set)}update(characterClassItem,set.toString());return characterClassItem}function processTerm(item){switch(item.type){case"dot":update(item,(unicode?DOT_SET_UNICODE:DOT_SET).toString());break;case"characterClass":item=processCharacterClass(item);break;case"characterClassEscape":update(item,getCharacterClassEscapeSet(item.value).toString());break;case"alternative":case"disjunction":case"group":case"quantifier":item.body=item.body.map(processTerm);break;case"value":var codePoint=item.codePoint;var set=regenerate(codePoint);if(ignoreCase&&unicode){var folded=caseFold(codePoint);if(folded){set.add(folded)}}update(item,set.toString());break;case"anchor":case"empty":case"group":case"reference":break;default:throw Error("Unknown term type: "+item.type)}return item}module.exports=function(pattern,flags){var tree=parse(pattern,flags);ignoreCase=flags?flags.indexOf("i")>-1:false;unicode=flags?flags.indexOf("u")>-1:false;assign(tree,processTerm(tree));return generate(tree)}},{"./data/character-class-escape-sets.js":110,"./data/iu-mappings.json":111,regenerate:112,regjsgen:113,regjsparser:114}],116:[function(require,module,exports){exports.SourceMapGenerator=require("./source-map/source-map-generator").SourceMapGenerator;exports.SourceMapConsumer=require("./source-map/source-map-consumer").SourceMapConsumer;exports.SourceNode=require("./source-map/source-node").SourceNode},{"./source-map/source-map-consumer":121,"./source-map/source-map-generator":122,"./source-map/source-node":123}],117:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");function ArraySet(){this._array=[];this._set={}}ArraySet.fromArray=function ArraySet_fromArray(aArray,aAllowDuplicates){var set=new ArraySet;for(var i=0,len=aArray.length;i<len;i++){set.add(aArray[i],aAllowDuplicates)}return set};ArraySet.prototype.add=function ArraySet_add(aStr,aAllowDuplicates){var isDuplicate=this.has(aStr);var idx=this._array.length;if(!isDuplicate||aAllowDuplicates){this._array.push(aStr)}if(!isDuplicate){this._set[util.toSetString(aStr)]=idx}};ArraySet.prototype.has=function ArraySet_has(aStr){return Object.prototype.hasOwnProperty.call(this._set,util.toSetString(aStr))};ArraySet.prototype.indexOf=function ArraySet_indexOf(aStr){if(this.has(aStr)){return this._set[util.toSetString(aStr)]}throw new Error('"'+aStr+'" is not in the set.')};ArraySet.prototype.at=function ArraySet_at(aIdx){if(aIdx>=0&&aIdx<this._array.length){return this._array[aIdx]}throw new Error("No element indexed by "+aIdx)};ArraySet.prototype.toArray=function ArraySet_toArray(){return this._array.slice()};exports.ArraySet=ArraySet})},{"./util":124,amdefine:125}],118:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64=require("./base64");var VLQ_BASE_SHIFT=5;var VLQ_BASE=1<<VLQ_BASE_SHIFT;var VLQ_BASE_MASK=VLQ_BASE-1;var VLQ_CONTINUATION_BIT=VLQ_BASE;function toVLQSigned(aValue){return aValue<0?(-aValue<<1)+1:(aValue<<1)+0}function fromVLQSigned(aValue){var isNegative=(aValue&1)===1;var shifted=aValue>>1;return isNegative?-shifted:shifted}exports.encode=function base64VLQ_encode(aValue){var encoded="";var digit;var vlq=toVLQSigned(aValue);do{digit=vlq&VLQ_BASE_MASK;vlq>>>=VLQ_BASE_SHIFT;if(vlq>0){digit|=VLQ_CONTINUATION_BIT}encoded+=base64.encode(digit)}while(vlq>0);return encoded};exports.decode=function base64VLQ_decode(aStr,aOutParam){var i=0;var strLen=aStr.length;var result=0;var shift=0;var continuation,digit;do{if(i>=strLen){throw new Error("Expected more digits in base 64 VLQ value.")}digit=base64.decode(aStr.charAt(i++));continuation=!!(digit&VLQ_CONTINUATION_BIT);digit&=VLQ_BASE_MASK;result=result+(digit<<shift);shift+=VLQ_BASE_SHIFT}while(continuation);aOutParam.value=fromVLQSigned(result);aOutParam.rest=aStr.slice(i)}})},{"./base64":119,amdefine:125}],119:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var charToIntMap={};var intToCharMap={};"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").forEach(function(ch,index){charToIntMap[ch]=index;intToCharMap[index]=ch});exports.encode=function base64_encode(aNumber){if(aNumber in intToCharMap){return intToCharMap[aNumber]}throw new TypeError("Must be between 0 and 63: "+aNumber)};exports.decode=function base64_decode(aChar){if(aChar in charToIntMap){return charToIntMap[aChar]}throw new TypeError("Not a valid base 64 digit: "+aChar)}})},{amdefine:125}],120:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function recursiveSearch(aLow,aHigh,aNeedle,aHaystack,aCompare){var mid=Math.floor((aHigh-aLow)/2)+aLow;var cmp=aCompare(aNeedle,aHaystack[mid],true);if(cmp===0){return aHaystack[mid]}else if(cmp>0){if(aHigh-mid>1){return recursiveSearch(mid,aHigh,aNeedle,aHaystack,aCompare)}return aHaystack[mid]}else{if(mid-aLow>1){return recursiveSearch(aLow,mid,aNeedle,aHaystack,aCompare)}return aLow<0?null:aHaystack[aLow]}}exports.search=function search(aNeedle,aHaystack,aCompare){return aHaystack.length>0?recursiveSearch(-1,aHaystack.length,aNeedle,aHaystack,aCompare):null}})},{amdefine:125}],121:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var util=require("./util");var binarySearch=require("./binary-search");var ArraySet=require("./array-set").ArraySet;var base64VLQ=require("./base64-vlq");function SourceMapConsumer(aSourceMap){var sourceMap=aSourceMap;if(typeof aSourceMap==="string"){sourceMap=JSON.parse(aSourceMap.replace(/^\)\]\}'/,""))}var version=util.getArg(sourceMap,"version");var sources=util.getArg(sourceMap,"sources");var names=util.getArg(sourceMap,"names",[]);var sourceRoot=util.getArg(sourceMap,"sourceRoot",null);var sourcesContent=util.getArg(sourceMap,"sourcesContent",null);var mappings=util.getArg(sourceMap,"mappings");var file=util.getArg(sourceMap,"file",null);if(version!=this._version){throw new Error("Unsupported version: "+version)}this._names=ArraySet.fromArray(names,true);this._sources=ArraySet.fromArray(sources,true);this.sourceRoot=sourceRoot;this.sourcesContent=sourcesContent;this._mappings=mappings;this.file=file}SourceMapConsumer.fromSourceMap=function SourceMapConsumer_fromSourceMap(aSourceMap){var smc=Object.create(SourceMapConsumer.prototype);smc._names=ArraySet.fromArray(aSourceMap._names.toArray(),true);smc._sources=ArraySet.fromArray(aSourceMap._sources.toArray(),true);smc.sourceRoot=aSourceMap._sourceRoot;smc.sourcesContent=aSourceMap._generateSourcesContent(smc._sources.toArray(),smc.sourceRoot);smc.file=aSourceMap._file;smc.__generatedMappings=aSourceMap._mappings.slice().sort(util.compareByGeneratedPositions);smc.__originalMappings=aSourceMap._mappings.slice().sort(util.compareByOriginalPositions);return smc};SourceMapConsumer.prototype._version=3;Object.defineProperty(SourceMapConsumer.prototype,"sources",{get:function(){return this._sources.toArray().map(function(s){return this.sourceRoot!=null?util.join(this.sourceRoot,s):s},this)}});SourceMapConsumer.prototype.__generatedMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_generatedMappings",{get:function(){if(!this.__generatedMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__generatedMappings}});SourceMapConsumer.prototype.__originalMappings=null;Object.defineProperty(SourceMapConsumer.prototype,"_originalMappings",{get:function(){if(!this.__originalMappings){this.__generatedMappings=[];this.__originalMappings=[];this._parseMappings(this._mappings,this.sourceRoot)}return this.__originalMappings}});SourceMapConsumer.prototype._nextCharIsMappingSeparator=function SourceMapConsumer_nextCharIsMappingSeparator(aStr){var c=aStr.charAt(0);return c===";"||c===","};SourceMapConsumer.prototype._parseMappings=function SourceMapConsumer_parseMappings(aStr,aSourceRoot){var generatedLine=1;var previousGeneratedColumn=0;var previousOriginalLine=0;var previousOriginalColumn=0;var previousSource=0;var previousName=0;var str=aStr;var temp={};var mapping;while(str.length>0){if(str.charAt(0)===";"){generatedLine++;str=str.slice(1);previousGeneratedColumn=0}else if(str.charAt(0)===","){str=str.slice(1)}else{mapping={};mapping.generatedLine=generatedLine;base64VLQ.decode(str,temp);mapping.generatedColumn=previousGeneratedColumn+temp.value;previousGeneratedColumn=mapping.generatedColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.source=this._sources.at(previousSource+temp.value);previousSource+=temp.value;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source, but no line and column")}base64VLQ.decode(str,temp);mapping.originalLine=previousOriginalLine+temp.value;previousOriginalLine=mapping.originalLine;mapping.originalLine+=1;str=temp.rest;if(str.length===0||this._nextCharIsMappingSeparator(str)){throw new Error("Found a source and line, but no column")}base64VLQ.decode(str,temp);mapping.originalColumn=previousOriginalColumn+temp.value;previousOriginalColumn=mapping.originalColumn;str=temp.rest;if(str.length>0&&!this._nextCharIsMappingSeparator(str)){base64VLQ.decode(str,temp);mapping.name=this._names.at(previousName+temp.value);previousName+=temp.value;str=temp.rest}}this.__generatedMappings.push(mapping);if(typeof mapping.originalLine==="number"){this.__originalMappings.push(mapping)}}}this.__generatedMappings.sort(util.compareByGeneratedPositions);this.__originalMappings.sort(util.compareByOriginalPositions)};SourceMapConsumer.prototype._findMapping=function SourceMapConsumer_findMapping(aNeedle,aMappings,aLineName,aColumnName,aComparator){if(aNeedle[aLineName]<=0){throw new TypeError("Line must be greater than or equal to 1, got "+aNeedle[aLineName])}if(aNeedle[aColumnName]<0){throw new TypeError("Column must be greater than or equal to 0, got "+aNeedle[aColumnName])}return binarySearch.search(aNeedle,aMappings,aComparator)};SourceMapConsumer.prototype.originalPositionFor=function SourceMapConsumer_originalPositionFor(aArgs){var needle={generatedLine:util.getArg(aArgs,"line"),generatedColumn:util.getArg(aArgs,"column")};var mapping=this._findMapping(needle,this._generatedMappings,"generatedLine","generatedColumn",util.compareByGeneratedPositions);if(mapping&&mapping.generatedLine===needle.generatedLine){var source=util.getArg(mapping,"source",null);if(source!=null&&this.sourceRoot!=null){source=util.join(this.sourceRoot,source)}return{source:source,line:util.getArg(mapping,"originalLine",null),column:util.getArg(mapping,"originalColumn",null),name:util.getArg(mapping,"name",null)}}return{source:null,line:null,column:null,name:null}};SourceMapConsumer.prototype.sourceContentFor=function SourceMapConsumer_sourceContentFor(aSource){if(!this.sourcesContent){return null}if(this.sourceRoot!=null){aSource=util.relative(this.sourceRoot,aSource)}if(this._sources.has(aSource)){return this.sourcesContent[this._sources.indexOf(aSource)]}var url;if(this.sourceRoot!=null&&(url=util.urlParse(this.sourceRoot))){var fileUriAbsPath=aSource.replace(/^file:\/\//,"");if(url.scheme=="file"&&this._sources.has(fileUriAbsPath)){return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]}if((!url.path||url.path=="/")&&this._sources.has("/"+aSource)){return this.sourcesContent[this._sources.indexOf("/"+aSource)]}}throw new Error('"'+aSource+'" is not in the SourceMap.')};SourceMapConsumer.prototype.generatedPositionFor=function SourceMapConsumer_generatedPositionFor(aArgs){var needle={source:util.getArg(aArgs,"source"),originalLine:util.getArg(aArgs,"line"),originalColumn:util.getArg(aArgs,"column")};if(this.sourceRoot!=null){needle.source=util.relative(this.sourceRoot,needle.source)}var mapping=this._findMapping(needle,this._originalMappings,"originalLine","originalColumn",util.compareByOriginalPositions);if(mapping){return{line:util.getArg(mapping,"generatedLine",null),column:util.getArg(mapping,"generatedColumn",null)}}return{line:null,column:null}};SourceMapConsumer.GENERATED_ORDER=1;SourceMapConsumer.ORIGINAL_ORDER=2;SourceMapConsumer.prototype.eachMapping=function SourceMapConsumer_eachMapping(aCallback,aContext,aOrder){var context=aContext||null;var order=aOrder||SourceMapConsumer.GENERATED_ORDER;var mappings;switch(order){case SourceMapConsumer.GENERATED_ORDER:mappings=this._generatedMappings;break;case SourceMapConsumer.ORIGINAL_ORDER:mappings=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var sourceRoot=this.sourceRoot;mappings.map(function(mapping){var source=mapping.source;if(source!=null&&sourceRoot!=null){source=util.join(sourceRoot,source)}return{source:source,generatedLine:mapping.generatedLine,generatedColumn:mapping.generatedColumn,originalLine:mapping.originalLine,originalColumn:mapping.originalColumn,name:mapping.name}}).forEach(aCallback,context)};exports.SourceMapConsumer=SourceMapConsumer})},{"./array-set":117,"./base64-vlq":118,"./binary-search":120,"./util":124,amdefine:125}],122:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var base64VLQ=require("./base64-vlq");var util=require("./util");var ArraySet=require("./array-set").ArraySet;function SourceMapGenerator(aArgs){if(!aArgs){aArgs={}}this._file=util.getArg(aArgs,"file",null);this._sourceRoot=util.getArg(aArgs,"sourceRoot",null);this._sources=new ArraySet;this._names=new ArraySet;this._mappings=[];this._sourcesContents=null}SourceMapGenerator.prototype._version=3;SourceMapGenerator.fromSourceMap=function SourceMapGenerator_fromSourceMap(aSourceMapConsumer){var sourceRoot=aSourceMapConsumer.sourceRoot;var generator=new SourceMapGenerator({file:aSourceMapConsumer.file,sourceRoot:sourceRoot});aSourceMapConsumer.eachMapping(function(mapping){var newMapping={generated:{line:mapping.generatedLine,column:mapping.generatedColumn}};if(mapping.source!=null){newMapping.source=mapping.source;if(sourceRoot!=null){newMapping.source=util.relative(sourceRoot,newMapping.source)}newMapping.original={line:mapping.originalLine,column:mapping.originalColumn};if(mapping.name!=null){newMapping.name=mapping.name}}generator.addMapping(newMapping)});aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){generator.setSourceContent(sourceFile,content)}});return generator};SourceMapGenerator.prototype.addMapping=function SourceMapGenerator_addMapping(aArgs){var generated=util.getArg(aArgs,"generated");var original=util.getArg(aArgs,"original",null);var source=util.getArg(aArgs,"source",null);var name=util.getArg(aArgs,"name",null);this._validateMapping(generated,original,source,name);if(source!=null&&!this._sources.has(source)){this._sources.add(source)}if(name!=null&&!this._names.has(name)){this._names.add(name)}this._mappings.push({generatedLine:generated.line,generatedColumn:generated.column,originalLine:original!=null&&original.line,originalColumn:original!=null&&original.column,source:source,name:name})};SourceMapGenerator.prototype.setSourceContent=function SourceMapGenerator_setSourceContent(aSourceFile,aSourceContent){var source=aSourceFile;if(this._sourceRoot!=null){source=util.relative(this._sourceRoot,source)}if(aSourceContent!=null){if(!this._sourcesContents){this._sourcesContents={}}this._sourcesContents[util.toSetString(source)]=aSourceContent}else if(this._sourcesContents){delete this._sourcesContents[util.toSetString(source)];if(Object.keys(this._sourcesContents).length===0){this._sourcesContents=null}}};SourceMapGenerator.prototype.applySourceMap=function SourceMapGenerator_applySourceMap(aSourceMapConsumer,aSourceFile,aSourceMapPath){var sourceFile=aSourceFile;if(aSourceFile==null){if(aSourceMapConsumer.file==null){throw new Error("SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, "+'or the source map\'s "file" property. Both were omitted.')}sourceFile=aSourceMapConsumer.file}var sourceRoot=this._sourceRoot;if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}var newSources=new ArraySet;var newNames=new ArraySet;this._mappings.forEach(function(mapping){if(mapping.source===sourceFile&&mapping.originalLine!=null){var original=aSourceMapConsumer.originalPositionFor({line:mapping.originalLine,column:mapping.originalColumn});if(original.source!=null){mapping.source=original.source;if(aSourceMapPath!=null){mapping.source=util.join(aSourceMapPath,mapping.source)}if(sourceRoot!=null){mapping.source=util.relative(sourceRoot,mapping.source)}mapping.originalLine=original.line;mapping.originalColumn=original.column;if(original.name!=null){mapping.name=original.name}}}var source=mapping.source;if(source!=null&&!newSources.has(source)){newSources.add(source)}var name=mapping.name;if(name!=null&&!newNames.has(name)){newNames.add(name)}},this);this._sources=newSources;this._names=newNames;aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aSourceMapPath!=null){sourceFile=util.join(aSourceMapPath,sourceFile)}if(sourceRoot!=null){sourceFile=util.relative(sourceRoot,sourceFile)}this.setSourceContent(sourceFile,content)}},this)};SourceMapGenerator.prototype._validateMapping=function SourceMapGenerator_validateMapping(aGenerated,aOriginal,aSource,aName){if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aGenerated.line>0&&aGenerated.column>=0&&!aOriginal&&!aSource&&!aName){return}else if(aGenerated&&"line"in aGenerated&&"column"in aGenerated&&aOriginal&&"line"in aOriginal&&"column"in aOriginal&&aGenerated.line>0&&aGenerated.column>=0&&aOriginal.line>0&&aOriginal.column>=0&&aSource){return}else{throw new Error("Invalid mapping: "+JSON.stringify({generated:aGenerated,source:aSource,original:aOriginal,name:aName}))}};SourceMapGenerator.prototype._serializeMappings=function SourceMapGenerator_serializeMappings(){var previousGeneratedColumn=0;var previousGeneratedLine=1;var previousOriginalColumn=0;var previousOriginalLine=0;var previousName=0;var previousSource=0;var result="";var mapping;this._mappings.sort(util.compareByGeneratedPositions);for(var i=0,len=this._mappings.length;i<len;i++){mapping=this._mappings[i];if(mapping.generatedLine!==previousGeneratedLine){previousGeneratedColumn=0;while(mapping.generatedLine!==previousGeneratedLine){result+=";";previousGeneratedLine++}}else{if(i>0){if(!util.compareByGeneratedPositions(mapping,this._mappings[i-1])){continue}result+=","}}result+=base64VLQ.encode(mapping.generatedColumn-previousGeneratedColumn);previousGeneratedColumn=mapping.generatedColumn;if(mapping.source!=null){result+=base64VLQ.encode(this._sources.indexOf(mapping.source)-previousSource);previousSource=this._sources.indexOf(mapping.source);result+=base64VLQ.encode(mapping.originalLine-1-previousOriginalLine);previousOriginalLine=mapping.originalLine-1;result+=base64VLQ.encode(mapping.originalColumn-previousOriginalColumn);previousOriginalColumn=mapping.originalColumn;if(mapping.name!=null){result+=base64VLQ.encode(this._names.indexOf(mapping.name)-previousName);previousName=this._names.indexOf(mapping.name)}}}return result};SourceMapGenerator.prototype._generateSourcesContent=function SourceMapGenerator_generateSourcesContent(aSources,aSourceRoot){return aSources.map(function(source){if(!this._sourcesContents){return null }if(aSourceRoot!=null){source=util.relative(aSourceRoot,source)}var key=util.toSetString(source);return Object.prototype.hasOwnProperty.call(this._sourcesContents,key)?this._sourcesContents[key]:null},this)};SourceMapGenerator.prototype.toJSON=function SourceMapGenerator_toJSON(){var map={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};if(this._file!=null){map.file=this._file}if(this._sourceRoot!=null){map.sourceRoot=this._sourceRoot}if(this._sourcesContents){map.sourcesContent=this._generateSourcesContent(map.sources,map.sourceRoot)}return map};SourceMapGenerator.prototype.toString=function SourceMapGenerator_toString(){return JSON.stringify(this)};exports.SourceMapGenerator=SourceMapGenerator})},{"./array-set":117,"./base64-vlq":118,"./util":124,amdefine:125}],123:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){var SourceMapGenerator=require("./source-map-generator").SourceMapGenerator;var util=require("./util");var REGEX_NEWLINE=/(\r?\n)/;var REGEX_CHARACTER=/\r\n|[\s\S]/g;function SourceNode(aLine,aColumn,aSource,aChunks,aName){this.children=[];this.sourceContents={};this.line=aLine==null?null:aLine;this.column=aColumn==null?null:aColumn;this.source=aSource==null?null:aSource;this.name=aName==null?null:aName;if(aChunks!=null)this.add(aChunks)}SourceNode.fromStringWithSourceMap=function SourceNode_fromStringWithSourceMap(aGeneratedCode,aSourceMapConsumer,aRelativePath){var node=new SourceNode;var remainingLines=aGeneratedCode.split(REGEX_NEWLINE);var shiftNextLine=function(){var lineContents=remainingLines.shift();var newLine=remainingLines.shift()||"";return lineContents+newLine};var lastGeneratedLine=1,lastGeneratedColumn=0;var lastMapping=null;aSourceMapConsumer.eachMapping(function(mapping){if(lastMapping!==null){if(lastGeneratedLine<mapping.generatedLine){var code="";addMappingWithCode(lastMapping,shiftNextLine());lastGeneratedLine++;lastGeneratedColumn=0}else{var nextLine=remainingLines[0];var code=nextLine.substr(0,mapping.generatedColumn-lastGeneratedColumn);remainingLines[0]=nextLine.substr(mapping.generatedColumn-lastGeneratedColumn);lastGeneratedColumn=mapping.generatedColumn;addMappingWithCode(lastMapping,code);lastMapping=mapping;return}}while(lastGeneratedLine<mapping.generatedLine){node.add(shiftNextLine());lastGeneratedLine++}if(lastGeneratedColumn<mapping.generatedColumn){var nextLine=remainingLines[0];node.add(nextLine.substr(0,mapping.generatedColumn));remainingLines[0]=nextLine.substr(mapping.generatedColumn);lastGeneratedColumn=mapping.generatedColumn}lastMapping=mapping},this);if(remainingLines.length>0){if(lastMapping){addMappingWithCode(lastMapping,shiftNextLine())}node.add(remainingLines.join(""))}aSourceMapConsumer.sources.forEach(function(sourceFile){var content=aSourceMapConsumer.sourceContentFor(sourceFile);if(content!=null){if(aRelativePath!=null){sourceFile=util.join(aRelativePath,sourceFile)}node.setSourceContent(sourceFile,content)}});return node;function addMappingWithCode(mapping,code){if(mapping===null||mapping.source===undefined){node.add(code)}else{var source=aRelativePath?util.join(aRelativePath,mapping.source):mapping.source;node.add(new SourceNode(mapping.originalLine,mapping.originalColumn,source,code,mapping.name))}}};SourceNode.prototype.add=function SourceNode_add(aChunk){if(Array.isArray(aChunk)){aChunk.forEach(function(chunk){this.add(chunk)},this)}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){if(aChunk){this.children.push(aChunk)}}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.prepend=function SourceNode_prepend(aChunk){if(Array.isArray(aChunk)){for(var i=aChunk.length-1;i>=0;i--){this.prepend(aChunk[i])}}else if(aChunk instanceof SourceNode||typeof aChunk==="string"){this.children.unshift(aChunk)}else{throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+aChunk)}return this};SourceNode.prototype.walk=function SourceNode_walk(aFn){var chunk;for(var i=0,len=this.children.length;i<len;i++){chunk=this.children[i];if(chunk instanceof SourceNode){chunk.walk(aFn)}else{if(chunk!==""){aFn(chunk,{source:this.source,line:this.line,column:this.column,name:this.name})}}}};SourceNode.prototype.join=function SourceNode_join(aSep){var newChildren;var i;var len=this.children.length;if(len>0){newChildren=[];for(i=0;i<len-1;i++){newChildren.push(this.children[i]);newChildren.push(aSep)}newChildren.push(this.children[i]);this.children=newChildren}return this};SourceNode.prototype.replaceRight=function SourceNode_replaceRight(aPattern,aReplacement){var lastChild=this.children[this.children.length-1];if(lastChild instanceof SourceNode){lastChild.replaceRight(aPattern,aReplacement)}else if(typeof lastChild==="string"){this.children[this.children.length-1]=lastChild.replace(aPattern,aReplacement)}else{this.children.push("".replace(aPattern,aReplacement))}return this};SourceNode.prototype.setSourceContent=function SourceNode_setSourceContent(aSourceFile,aSourceContent){this.sourceContents[util.toSetString(aSourceFile)]=aSourceContent};SourceNode.prototype.walkSourceContents=function SourceNode_walkSourceContents(aFn){for(var i=0,len=this.children.length;i<len;i++){if(this.children[i]instanceof SourceNode){this.children[i].walkSourceContents(aFn)}}var sources=Object.keys(this.sourceContents);for(var i=0,len=sources.length;i<len;i++){aFn(util.fromSetString(sources[i]),this.sourceContents[sources[i]])}};SourceNode.prototype.toString=function SourceNode_toString(){var str="";this.walk(function(chunk){str+=chunk});return str};SourceNode.prototype.toStringWithSourceMap=function SourceNode_toStringWithSourceMap(aArgs){var generated={code:"",line:1,column:0};var map=new SourceMapGenerator(aArgs);var sourceMappingActive=false;var lastOriginalSource=null;var lastOriginalLine=null;var lastOriginalColumn=null;var lastOriginalName=null;this.walk(function(chunk,original){generated.code+=chunk;if(original.source!==null&&original.line!==null&&original.column!==null){if(lastOriginalSource!==original.source||lastOriginalLine!==original.line||lastOriginalColumn!==original.column||lastOriginalName!==original.name){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}lastOriginalSource=original.source;lastOriginalLine=original.line;lastOriginalColumn=original.column;lastOriginalName=original.name;sourceMappingActive=true}else if(sourceMappingActive){map.addMapping({generated:{line:generated.line,column:generated.column}});lastOriginalSource=null;sourceMappingActive=false}chunk.match(REGEX_CHARACTER).forEach(function(ch,idx,array){if(REGEX_NEWLINE.test(ch)){generated.line++;generated.column=0;if(idx+1===array.length){lastOriginalSource=null;sourceMappingActive=false}else if(sourceMappingActive){map.addMapping({source:original.source,original:{line:original.line,column:original.column},generated:{line:generated.line,column:generated.column},name:original.name})}}else{generated.column+=ch.length}})});this.walkSourceContents(function(sourceFile,sourceContent){map.setSourceContent(sourceFile,sourceContent)});return{code:generated.code,map:map}};exports.SourceNode=SourceNode})},{"./source-map-generator":122,"./util":124,amdefine:125}],124:[function(require,module,exports){if(typeof define!=="function"){var define=require("amdefine")(module,require)}define(function(require,exports,module){function getArg(aArgs,aName,aDefaultValue){if(aName in aArgs){return aArgs[aName]}else if(arguments.length===3){return aDefaultValue}else{throw new Error('"'+aName+'" is a required argument.')}}exports.getArg=getArg;var urlRegexp=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/;var dataUrlRegexp=/^data:.+\,.+$/;function urlParse(aUrl){var match=aUrl.match(urlRegexp);if(!match){return null}return{scheme:match[1],auth:match[2],host:match[3],port:match[4],path:match[5]}}exports.urlParse=urlParse;function urlGenerate(aParsedUrl){var url="";if(aParsedUrl.scheme){url+=aParsedUrl.scheme+":"}url+="//";if(aParsedUrl.auth){url+=aParsedUrl.auth+"@"}if(aParsedUrl.host){url+=aParsedUrl.host}if(aParsedUrl.port){url+=":"+aParsedUrl.port}if(aParsedUrl.path){url+=aParsedUrl.path}return url}exports.urlGenerate=urlGenerate;function normalize(aPath){var path=aPath;var url=urlParse(aPath);if(url){if(!url.path){return aPath}path=url.path}var isAbsolute=path.charAt(0)==="/";var parts=path.split(/\/+/);for(var part,up=0,i=parts.length-1;i>=0;i--){part=parts[i];if(part==="."){parts.splice(i,1)}else if(part===".."){up++}else if(up>0){if(part===""){parts.splice(i+1,up);up=0}else{parts.splice(i,2);up--}}}path=parts.join("/");if(path===""){path=isAbsolute?"/":"."}if(url){url.path=path;return urlGenerate(url)}return path}exports.normalize=normalize;function join(aRoot,aPath){if(aRoot===""){aRoot="."}if(aPath===""){aPath="."}var aPathUrl=urlParse(aPath);var aRootUrl=urlParse(aRoot);if(aRootUrl){aRoot=aRootUrl.path||"/"}if(aPathUrl&&!aPathUrl.scheme){if(aRootUrl){aPathUrl.scheme=aRootUrl.scheme}return urlGenerate(aPathUrl)}if(aPathUrl||aPath.match(dataUrlRegexp)){return aPath}if(aRootUrl&&!aRootUrl.host&&!aRootUrl.path){aRootUrl.host=aPath;return urlGenerate(aRootUrl)}var joined=aPath.charAt(0)==="/"?aPath:normalize(aRoot.replace(/\/+$/,"")+"/"+aPath);if(aRootUrl){aRootUrl.path=joined;return urlGenerate(aRootUrl)}return joined}exports.join=join;function relative(aRoot,aPath){if(aRoot===""){aRoot="."}aRoot=aRoot.replace(/\/$/,"");var url=urlParse(aRoot);if(aPath.charAt(0)=="/"&&url&&url.path=="/"){return aPath.slice(1)}return aPath.indexOf(aRoot+"/")===0?aPath.substr(aRoot.length+1):aPath}exports.relative=relative;function toSetString(aStr){return"$"+aStr}exports.toSetString=toSetString;function fromSetString(aStr){return aStr.substr(1)}exports.fromSetString=fromSetString;function strcmp(aStr1,aStr2){var s1=aStr1||"";var s2=aStr2||"";return(s1>s2)-(s1<s2)}function compareByOriginalPositions(mappingA,mappingB,onlyCompareOriginal){var cmp;cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp||onlyCompareOriginal){return cmp}cmp=strcmp(mappingA.name,mappingB.name);if(cmp){return cmp}cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}return mappingA.generatedColumn-mappingB.generatedColumn}exports.compareByOriginalPositions=compareByOriginalPositions;function compareByGeneratedPositions(mappingA,mappingB,onlyCompareGenerated){var cmp;cmp=mappingA.generatedLine-mappingB.generatedLine;if(cmp){return cmp}cmp=mappingA.generatedColumn-mappingB.generatedColumn;if(cmp||onlyCompareGenerated){return cmp}cmp=strcmp(mappingA.source,mappingB.source);if(cmp){return cmp}cmp=mappingA.originalLine-mappingB.originalLine;if(cmp){return cmp}cmp=mappingA.originalColumn-mappingB.originalColumn;if(cmp){return cmp}return strcmp(mappingA.name,mappingB.name)}exports.compareByGeneratedPositions=compareByGeneratedPositions})},{amdefine:125}],125:[function(require,module,exports){(function(process,__filename){"use strict";function amdefine(module,requireFn){"use strict";var defineCache={},loaderCache={},alreadyCalled=false,path=require("path"),makeRequire,stringRequire;function trimDots(ary){var i,part;for(i=0;ary[i];i+=1){part=ary[i];if(part==="."){ary.splice(i,1);i-=1}else if(part===".."){if(i===1&&(ary[2]===".."||ary[0]==="..")){break}else if(i>0){ary.splice(i-1,2);i-=2}}}}function normalize(name,baseName){var baseParts;if(name&&name.charAt(0)==="."){if(baseName){baseParts=baseName.split("/");baseParts=baseParts.slice(0,baseParts.length-1);baseParts=baseParts.concat(name.split("/"));trimDots(baseParts);name=baseParts.join("/")}}return name}function makeNormalize(relName){return function(name){return normalize(name,relName)}}function makeLoad(id){function load(value){loaderCache[id]=value}load.fromText=function(id,text){throw new Error("amdefine does not implement load.fromText")};return load}makeRequire=function(systemRequire,exports,module,relId){function amdRequire(deps,callback){if(typeof deps==="string"){return stringRequire(systemRequire,exports,module,deps,relId)}else{deps=deps.map(function(depName){return stringRequire(systemRequire,exports,module,depName,relId)});process.nextTick(function(){callback.apply(null,deps)})}}amdRequire.toUrl=function(filePath){if(filePath.indexOf(".")===0){return normalize(filePath,path.dirname(module.filename))}else{return filePath}};return amdRequire};requireFn=requireFn||function req(){return module.require.apply(module,arguments)};function runFactory(id,deps,factory){var r,e,m,result;if(id){e=loaderCache[id]={};m={id:id,uri:__filename,exports:e};r=makeRequire(requireFn,e,m,id)}else{if(alreadyCalled){throw new Error("amdefine with no module ID cannot be called more than once per file.")}alreadyCalled=true;e=module.exports;m=module;r=makeRequire(requireFn,e,m,module.id)}if(deps){deps=deps.map(function(depName){return r(depName)})}if(typeof factory==="function"){result=factory.apply(m.exports,deps)}else{result=factory}if(result!==undefined){m.exports=result;if(id){loaderCache[id]=m.exports}}}stringRequire=function(systemRequire,exports,module,id,relId){var index=id.indexOf("!"),originalId=id,prefix,plugin;if(index===-1){id=normalize(id,relId);if(id==="require"){return makeRequire(systemRequire,exports,module,relId)}else if(id==="exports"){return exports}else if(id==="module"){return module}else if(loaderCache.hasOwnProperty(id)){return loaderCache[id]}else if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}else{if(systemRequire){return systemRequire(originalId)}else{throw new Error("No module with ID: "+id)}}}else{prefix=id.substring(0,index);id=id.substring(index+1,id.length);plugin=stringRequire(systemRequire,exports,module,prefix,relId);if(plugin.normalize){id=plugin.normalize(id,makeNormalize(relId))}else{id=normalize(id,relId)}if(loaderCache[id]){return loaderCache[id]}else{plugin.load(id,makeRequire(systemRequire,exports,module,relId),makeLoad(id),{});return loaderCache[id]}}};function define(id,deps,factory){if(Array.isArray(id)){factory=deps;deps=id;id=undefined}else if(typeof id!=="string"){factory=id;id=deps=undefined}if(deps&&!Array.isArray(deps)){factory=deps;deps=undefined}if(!deps){deps=["require","exports","module"]}if(id){defineCache[id]=[id,deps,factory]}else{runFactory(id,deps,factory)}}define.require=function(id){if(loaderCache[id]){return loaderCache[id]}if(defineCache[id]){runFactory.apply(null,defineCache[id]);return loaderCache[id]}};define.amd={};return define}module.exports=amdefine}).call(this,require("_process"),"/node_modules/source-map/node_modules/amdefine/amdefine.js")},{_process:100,path:99}],126:[function(require,module,exports){module.exports={"abstract-expression-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-delete":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceDelete"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-get":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceGet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"abstract-expression-set":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"PROPERTY"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"referenceSet"},computed:false},computed:true},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"VALUE"}]}}]},"apply-constructor":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"Constructor"},{type:"Identifier",name:"args"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"instance"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"prototype"},computed:false}]}}],kind:"var"},{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"result"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Constructor"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"Identifier",name:"instance"},{type:"Identifier",name:"args"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"Identifier",name:"result"},operator:"!=",right:{type:"Literal",value:null}},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"object"}},operator:"||",right:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"result"}},operator:"==",right:{type:"Literal",value:"function"}}}}},consequent:{type:"Identifier",name:"result"},alternate:{type:"Identifier",name:"instance"}}}]},expression:false}}}]},"array-comprehension-container":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"KEY"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[]}}]},"array-comprehension-for-each":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"forEach"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}]}}]},"array-expression-comprehension-filter":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"filter"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"FILTER"}}]},expression:false}]},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-expression-comprehension-map":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ARRAY"},property:{type:"Identifier",name:"map"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"STATEMENT"}}]},expression:false}]}}]},"array-from":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}]},call:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"CONTEXT"}]}}]},"class-props":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"},{type:"Identifier",name:"instanceProps"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"Identifier",name:"staticProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"child"},{type:"Identifier",name:"staticProps"}]}},alternate:null},{type:"IfStatement",test:{type:"Identifier",name:"instanceProps"},consequent:{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"Identifier",name:"instanceProps"}]}},alternate:null}]},expression:false}}}]},"class-super-constructor-call":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"SUPER_NAME"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}]},"class":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"CLASS_NAME"},init:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[]},expression:false}}],kind:"var"},{type:"ReturnStatement",argument:{type:"Identifier",name:"CLASS_NAME"}}]},expression:false}},arguments:[]}}]},"exports-assign-key":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"VARIABLE_NAME"},computed:false},right:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"Identifier",name:"KEY"},computed:false}}}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"default"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-wildcard":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"extends":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"child"},{type:"Identifier",name:"parent"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"prototype"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"create"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"parent"},property:{type:"Identifier",name:"prototype"},computed:false},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"constructor"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"child"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:false},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"}]},kind:"init"}]}]}}},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"child"},property:{type:"Identifier",name:"__proto__"},computed:false},right:{type:"Identifier",name:"parent"}}}]},expression:false}}}]},"for-of":{type:"Program",body:[{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"ITERATOR_KEY"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"OBJECT"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"STEP_KEY"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"ParenthesizedExpression",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"STEP_KEY"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"ITERATOR_KEY"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[]}}]},"function-return-obj":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"has-own":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false}}]},"if-undefined-set-to":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"Identifier",name:"VARIABLE"},operator:"===",right:{type:"Identifier",name:"undefined"}},consequent:{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"VARIABLE"},right:{type:"Identifier",name:"DEFAULT"}}},alternate:null}]},"interop-require":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"LogicalExpression",left:{type:"Identifier",name:"obj"},operator:"&&",right:{type:"ParenthesizedExpression",expression:{type:"LogicalExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Literal",value:"default"},computed:true},operator:"||",right:{type:"Identifier",name:"obj"}}}}}]},expression:false}}}]},"let-scoping-return":{type:"Program",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"RETURN"}},operator:"===",right:{type:"Literal",value:"object"}},consequent:{type:"ReturnStatement",argument:{type:"MemberExpression",object:{type:"Identifier",name:"RETURN"},property:{type:"Identifier",name:"v"},computed:false}},alternate:null}]},"object-define-properties-closure":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"KEY"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"Identifier",name:"CONTENT"}},{type:"ReturnStatement",argument:{type:"Identifier",name:"KEY"}}]},expression:false}},arguments:[{type:"Identifier",name:"OBJECT"}]}}]},"object-define-properties":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"OBJECT"},{type:"Identifier",name:"PROPS"}]}}]},"object-spread":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"keys"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"target"},init:{type:"ObjectExpression",properties:[]}}],kind:"var"},{type:"ForInStatement",left:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"i"},init:null}],kind:"var"},right:{type:"Identifier",name:"obj"},body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"keys"},property:{type:"Identifier",name:"indexOf"},computed:false},arguments:[{type:"Identifier",name:"i"}]},operator:">=",right:{type:"Literal",value:0}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"IfStatement",test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"hasOwnProperty"},computed:false},property:{type:"Identifier",name:"call"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"i"}]}},consequent:{type:"ContinueStatement",label:null},alternate:null},{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"target"},property:{type:"Identifier",name:"i"},computed:true},right:{type:"MemberExpression",object:{type:"Identifier",name:"obj"},property:{type:"Identifier",name:"i"},computed:true}}}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"target"}}]},expression:false}}}]},"prototype-identifier":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"Identifier",name:"CLASS_NAME"},property:{type:"Identifier",name:"prototype"},computed:false}}]},register:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"System"},property:{type:"Identifier",name:"register"},computed:false},arguments:[{type:"Identifier",name:"MODULE_NAME"},{type:"Identifier",name:"MODULE_DEPENDENCIES"},{type:"Identifier",name:"MODULE_BODY"}]}}]},"require-assign-key":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]},property:{type:"Identifier",name:"KEY"},computed:false}}],kind:"var"}]},"require-assign":{type:"Program",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"VARIABLE_NAME"},init:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}],kind:"var"}]},require:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"require"},arguments:[{type:"Identifier",name:"MODULE_NAME"}]}}]},"self-global":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ConditionalExpression",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"global"}},operator:"===",right:{type:"Literal",value:"undefined"}},consequent:{type:"Identifier",name:"self"},alternate:{type:"Identifier",name:"global"}}}]},slice:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"prototype"},computed:false},property:{type:"Identifier",name:"slice"},computed:false}}]},"tagged-template-literal":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"strings"},{type:"Identifier",name:"raw"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperties"},computed:false},arguments:[{type:"Identifier",name:"strings"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"raw"},value:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"raw"},kind:"init"}]},kind:"init"}]}]}}]},expression:false}}}]},"to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ConditionalExpression",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"Identifier",name:"arr"},alternate:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"arr"}]}}}]},expression:false}}}]},"umd-runner-body":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"ParenthesizedExpression",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"factory"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"define"}},operator:"===",right:{type:"Literal",value:"function"}},operator:"&&",right:{type:"MemberExpression",object:{type:"Identifier",name:"define"},property:{type:"Identifier",name:"amd"},computed:false}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"define"},arguments:[{type:"Identifier",name:"AMD_ARGUMENTS"},{type:"Identifier",name:"factory"}]}}]},alternate:{type:"IfStatement",test:{type:"BinaryExpression",left:{type:"UnaryExpression",operator:"typeof",prefix:true,argument:{type:"Identifier",name:"exports"}},operator:"!==",right:{type:"Literal",value:"undefined"}},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"factory"},arguments:[{type:"Identifier",name:"exports"},{type:"Identifier",name:"COMMON_ARGUMENTS"}]}}]},alternate:null}}]},expression:false}}}]}} },{}]},{},[1])(1)});
src/javascript/index.js
knowbody/redux-react-router-example-app
import 'babel/polyfill'; import React from 'react'; import { render } from 'react-dom'; import injectTapEventPlugin from 'react-tap-event-plugin'; import createHashHistory from 'history/lib/createHashHistory'; import Root from './Root'; /* Needed for onTouchTap Can go away when react 1.0 release Check this repo: https://github.com/zilverline/react-tap-event-plugin */ injectTapEventPlugin(); render(<Root />, document.getElementById('root'));
node_modules/react-navigation/src/routers/__tests__/validateRouteConfigMap-test.js
RahulDesai92/PHR
/* @flow */ import React from 'react'; import validateRouteConfigMap from '../validateRouteConfigMap'; import StackRouter from '../StackRouter'; const ListScreen = () => <div />; const ProfileNavigator = () => <div />; ProfileNavigator.router = StackRouter({ list: { screen: ListScreen, }, }); describe('validateRouteConfigMap', () => { test('Fails on empty config', () => { const invalidMap = {}; expect(() => validateRouteConfigMap(invalidMap)).toThrow(); }); test('Fails on bad object', () => { const invalidMap = { // @todo fix flow, this should error as no screen/getScreen // provided Home: { foo: 'bar', }, }; expect(() => validateRouteConfigMap(invalidMap)).toThrow(); }); test('Fails if both screen and getScreen are defined', () => { const invalidMap = { Home: { screen: ListScreen, getScreen: () => ListScreen, }, }; expect(() => validateRouteConfigMap(invalidMap)).toThrow(); }); test('Succeeds on a valid config', () => { const invalidMap = { Home: { screen: ProfileNavigator, }, Chat: { screen: ListScreen, }, }; validateRouteConfigMap(invalidMap); }); });
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/node_modules/material-ui/svg-icons/av/new-releases.js
bhathiya/test
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var AvNewReleases = function AvNewReleases(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M23 12l-2.44-2.78.34-3.68-3.61-.82-1.89-3.18L12 3 8.6 1.54 6.71 4.72l-3.61.81.34 3.68L1 12l2.44 2.78-.34 3.69 3.61.82 1.89 3.18L12 21l3.4 1.46 1.89-3.18 3.61-.82-.34-3.68L23 12zm-10 5h-2v-2h2v2zm0-4h-2V7h2v6z' }) ); }; AvNewReleases = (0, _pure2.default)(AvNewReleases); AvNewReleases.displayName = 'AvNewReleases'; AvNewReleases.muiName = 'SvgIcon'; exports.default = AvNewReleases;
app/components/Notes/AddNote.js
vandosant/react-notetaker
import React from 'react'; class AddNote extends React.Component { handleSubmit() { var newNote = this.refs.note.getDOMNode().value; this.refs.note.getDOMNode().value = ''; this.props.addNote(newNote); } render() { return ( <div className="input-group"> <input type="text" className="form-control" ref="note" placeholder="Add New Note"/> <span className="input-group-btn"> <button className="btn btn-default" type="button" onClick={this.handleSubmit.bind(this)}>Submit</button> </span> </div> ) } } AddNote.propTypes = { username: React.PropTypes.string.isRequired, addNote: React.PropTypes.func.isRequired }; export default AddNote;
ajax/libs/react-data-grid/0.14.26/react-data-grid-with-addons.js
Piicksarn/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["ReactDataGrid"] = factory(require("react"), require("react-dom")); else root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) { 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'; module.exports = __webpack_require__(1); module.exports.Editors = __webpack_require__(40); module.exports.Formatters = __webpack_require__(44); module.exports.Toolbar = __webpack_require__(46); module.exports.Row = __webpack_require__(24); /***/ }, /* 1 */ /***/ 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; }; 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; } var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var BaseGrid = __webpack_require__(4); var Row = __webpack_require__(24); var ExcelColumn = __webpack_require__(15); var KeyboardHandlerMixin = __webpack_require__(27); var CheckboxEditor = __webpack_require__(36); var DOMMetrics = __webpack_require__(34); var ColumnMetricsMixin = __webpack_require__(37); var RowUtils = __webpack_require__(39); var ColumnUtils = __webpack_require__(10); if (!Object.assign) { Object.assign = __webpack_require__(38); } var ReactDataGrid = React.createClass({ displayName: 'ReactDataGrid', mixins: [ColumnMetricsMixin, DOMMetrics.MetricsComputatorMixin, KeyboardHandlerMixin], propTypes: { rowHeight: React.PropTypes.number.isRequired, headerRowHeight: React.PropTypes.number, minHeight: React.PropTypes.number.isRequired, minWidth: React.PropTypes.number, enableRowSelect: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.string]), onRowUpdated: React.PropTypes.func, rowGetter: React.PropTypes.func.isRequired, rowsCount: React.PropTypes.number.isRequired, toolbar: React.PropTypes.element, enableCellSelect: React.PropTypes.bool, columns: React.PropTypes.oneOfType([React.PropTypes.object, React.PropTypes.array]).isRequired, onFilter: React.PropTypes.func, onCellCopyPaste: React.PropTypes.func, onCellsDragged: React.PropTypes.func, onAddFilter: React.PropTypes.func, onGridSort: React.PropTypes.func, onDragHandleDoubleClick: React.PropTypes.func, onGridRowsUpdated: React.PropTypes.func, onRowSelect: React.PropTypes.func, rowKey: React.PropTypes.string, rowScrollTimeout: React.PropTypes.number, onClearFilters: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { enableCellSelect: false, tabIndex: -1, rowHeight: 35, enableRowSelect: false, minHeight: 350, rowKey: 'id', rowScrollTimeout: 0 }; }, getInitialState: function getInitialState() { var columnMetrics = this.createColumnMetrics(); var initialState = { columnMetrics: columnMetrics, selectedRows: [], copied: null, expandedRows: [], canFilter: false, columnFilters: {}, sortDirection: null, sortColumn: null, dragged: null, scrollOffset: 0 }; if (this.props.enableCellSelect) { initialState.selected = { rowIdx: 0, idx: 0 }; } else { initialState.selected = { rowIdx: -1, idx: -1 }; } return initialState; }, onSelect: function onSelect(selected) { if (this.props.enableCellSelect) { if (this.state.selected.rowIdx !== selected.rowIdx || this.state.selected.idx !== selected.idx || this.state.selected.active === false) { var _idx = selected.idx; var _rowIdx = selected.rowIdx; if (_idx >= 0 && _rowIdx >= 0 && _idx < ColumnUtils.getSize(this.state.columnMetrics.columns) && _rowIdx < this.props.rowsCount) { this.setState({ selected: selected }); } } } }, onCellClick: function onCellClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); }, onCellDoubleClick: function onCellDoubleClick(cell) { this.onSelect({ rowIdx: cell.rowIdx, idx: cell.idx }); this.setActive('Enter'); }, onViewportDoubleClick: function onViewportDoubleClick() { this.setActive(); }, onPressArrowUp: function onPressArrowUp(e) { this.moveSelectedCell(e, -1, 0); }, onPressArrowDown: function onPressArrowDown(e) { this.moveSelectedCell(e, 1, 0); }, onPressArrowLeft: function onPressArrowLeft(e) { this.moveSelectedCell(e, 0, -1); }, onPressArrowRight: function onPressArrowRight(e) { this.moveSelectedCell(e, 0, 1); }, onPressTab: function onPressTab(e) { this.moveSelectedCell(e, 0, e.shiftKey ? -1 : 1); }, onPressEnter: function onPressEnter(e) { this.setActive(e.key); }, onPressDelete: function onPressDelete(e) { this.setActive(e.key); }, onPressEscape: function onPressEscape(e) { this.setInactive(e.key); }, onPressBackspace: function onPressBackspace(e) { this.setActive(e.key); }, onPressChar: function onPressChar(e) { if (this.isKeyPrintable(e.keyCode)) { this.setActive(e.keyCode); } }, onPressKeyWithCtrl: function onPressKeyWithCtrl(e) { var keys = { KeyCode_c: 99, KeyCode_C: 67, KeyCode_V: 86, KeyCode_v: 118 }; var idx = this.state.selected.idx; if (this.canEdit(idx)) { if (e.keyCode === keys.KeyCode_c || e.keyCode === keys.KeyCode_C) { var _value = this.getSelectedValue(); this.handleCopy({ value: _value }); } else if (e.keyCode === keys.KeyCode_v || e.keyCode === keys.KeyCode_V) { this.handlePaste(); } } }, onCellCommit: function onCellCommit(commit) { var selected = Object.assign({}, this.state.selected); selected.active = false; if (commit.key === 'Tab') { selected.idx += 1; } var expandedRows = this.state.expandedRows; // if(commit.changed && commit.changed.expandedHeight){ // expandedRows = this.expandRow(commit.rowIdx, commit.changed.expandedHeight); // } this.setState({ selected: selected, expandedRows: expandedRows }); if (this.props.onRowUpdated) { this.props.onRowUpdated(commit); } var targetRow = commit.rowIdx; if (this.props.onGridRowsUpdated) { this.props.onGridRowsUpdated({ cellKey: commit.cellKey, fromRow: targetRow, toRow: targetRow, updated: commit.updated, action: 'cellUpdate' }); } }, onDragStart: function onDragStart(e) { var value = this.getSelectedValue(); this.handleDragStart({ idx: this.state.selected.idx, rowIdx: this.state.selected.rowIdx, value: value }); // need to set dummy data for FF if (e && e.dataTransfer) { if (e.dataTransfer.setData) { e.dataTransfer.dropEffect = 'move'; e.dataTransfer.effectAllowed = 'move'; e.dataTransfer.setData('text/plain', 'dummy'); } } }, onToggleFilter: function onToggleFilter() { this.setState({ canFilter: !this.state.canFilter }); if (this.state.canFilter === false && this.props.onClearFilters) { this.props.onClearFilters(); } }, onDragHandleDoubleClick: function onDragHandleDoubleClick(e) { if (this.props.onDragHandleDoubleClick) { this.props.onDragHandleDoubleClick(e); } if (this.props.onGridRowsUpdated) { var cellKey = this.getColumn(e.idx).key; var updated = _defineProperty({}, cellKey, e.rowData[cellKey]); this.props.onGridRowsUpdated({ cellKey: cellKey, fromRow: e.rowIdx, toRow: this.props.rowsCount - 1, updated: updated, action: 'columnFill' }); } }, handleDragStart: function handleDragStart(dragged) { if (!this.dragEnabled()) { return; } var idx = dragged.idx; var rowIdx = dragged.rowIdx; if (idx >= 0 && rowIdx >= 0 && idx < this.getSize() && rowIdx < this.props.rowsCount) { this.setState({ dragged: dragged }); } }, handleDragEnd: function handleDragEnd() { if (!this.dragEnabled()) { return; } var fromRow = void 0; var toRow = void 0; var selected = this.state.selected; var dragged = this.state.dragged; var cellKey = this.getColumn(this.state.selected.idx).key; fromRow = selected.rowIdx < dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; toRow = selected.rowIdx > dragged.overRowIdx ? selected.rowIdx : dragged.overRowIdx; if (this.props.onCellsDragged) { this.props.onCellsDragged({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, value: dragged.value }); } if (this.props.onGridRowsUpdated) { var updated = _defineProperty({}, cellKey, dragged.value); this.props.onGridRowsUpdated({ cellKey: cellKey, fromRow: fromRow, toRow: toRow, updated: updated, action: 'cellDrag' }); } this.setState({ dragged: { complete: true } }); }, handleDragEnter: function handleDragEnter(row) { if (!this.dragEnabled()) { return; } var dragged = this.state.dragged; dragged.overRowIdx = row; this.setState({ dragged: dragged }); }, handleTerminateDrag: function handleTerminateDrag() { if (!this.dragEnabled()) { return; } this.setState({ dragged: null }); }, handlePaste: function handlePaste() { if (!this.copyPasteEnabled()) { return; } var selected = this.state.selected; var cellKey = this.getColumn(this.state.selected.idx).key; var textToCopy = this.state.textToCopy; var toRow = selected.rowIdx; if (this.props.onCellCopyPaste) { this.props.onCellCopyPaste({ cellKey: cellKey, rowIdx: toRow, value: textToCopy, fromRow: this.state.copied.rowIdx, toRow: toRow }); } if (this.props.onGridRowsUpdated) { var updated = _defineProperty({}, cellKey, textToCopy); this.props.onGridRowsUpdated({ cellKey: cellKey, fromRow: toRow, toRow: toRow, updated: updated, action: 'copyPaste' }); } this.setState({ copied: null }); }, handleCopy: function handleCopy(args) { if (!this.copyPasteEnabled()) { return; } var textToCopy = args.value; var selected = this.state.selected; var copied = { idx: selected.idx, rowIdx: selected.rowIdx }; this.setState({ textToCopy: textToCopy, copied: copied }); }, handleSort: function handleSort(columnKey, direction) { this.setState({ sortDirection: direction, sortColumn: columnKey }, function () { this.props.onGridSort(columnKey, direction); }); }, getSelectedRow: function getSelectedRow(rows, key) { var _this = this; var selectedRow = rows.filter(function (r) { if (r[_this.props.rowKey] === key) { return true; } return false; }); if (selectedRow.length > 0) { return selectedRow[0]; } }, // columnKey not used here as this function will select the whole row, // but needed to match the function signature in the CheckboxEditor handleRowSelect: function handleRowSelect(rowIdx, columnKey, rowData, e) { e.stopPropagation(); var selectedRows = this.props.enableRowSelect === 'single' ? [] : this.state.selectedRows.slice(0); var selectedRow = this.getSelectedRow(selectedRows, rowData[this.props.rowKey]); if (selectedRow) { selectedRow.isSelected = !selectedRow.isSelected; } else { rowData.isSelected = true; selectedRows.push(rowData); } this.setState({ selectedRows: selectedRows, selected: { rowIdx: rowIdx, idx: 0 } }); if (this.props.onRowSelect) { this.props.onRowSelect(selectedRows.filter(function (r) { return r.isSelected === true; })); } }, handleCheckboxChange: function handleCheckboxChange(e) { var allRowsSelected = void 0; if (e.currentTarget instanceof HTMLInputElement && e.currentTarget.checked === true) { allRowsSelected = true; } else { allRowsSelected = false; } var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { var row = Object.assign({}, this.props.rowGetter(i), { isSelected: allRowsSelected }); selectedRows.push(row); } this.setState({ selectedRows: selectedRows }); if (typeof this.props.onRowSelect === 'function') { this.props.onRowSelect(selectedRows.filter(function (r) { return r.isSelected === true; })); } }, getScrollOffSet: function getScrollOffSet() { var scrollOffset = 0; var canvas = ReactDOM.findDOMNode(this).querySelector('.react-grid-Canvas'); if (canvas) { scrollOffset = canvas.offsetWidth - canvas.clientWidth; } this.setState({ scrollOffset: scrollOffset }); }, getRowOffsetHeight: function getRowOffsetHeight() { var offsetHeight = 0; this.getHeaderRows().forEach(function (row) { return offsetHeight += parseFloat(row.height, 10); }); return offsetHeight; }, getHeaderRows: function getHeaderRows() { var rows = [{ ref: 'row', height: this.props.headerRowHeight || this.props.rowHeight }]; if (this.state.canFilter === true) { rows.push({ ref: 'filterRow', filterable: true, onFilterChange: this.props.onAddFilter, height: 45 }); } return rows; }, getInitialSelectedRows: function getInitialSelectedRows() { var selectedRows = []; for (var i = 0; i < this.props.rowsCount; i++) { selectedRows.push(false); } return selectedRows; }, getSelectedValue: function getSelectedValue() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; var cellKey = this.getColumn(idx).key; var row = this.props.rowGetter(rowIdx); return RowUtils.get(row, cellKey); }, moveSelectedCell: function moveSelectedCell(e, rowDelta, cellDelta) { // we need to prevent default as we control grid scroll // otherwise it moves every time you left/right which is janky e.preventDefault(); var rowIdx = this.state.selected.rowIdx + rowDelta; var idx = this.state.selected.idx + cellDelta; this.onSelect({ idx: idx, rowIdx: rowIdx }); }, setActive: function setActive(keyPressed) { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && !this.isActive()) { var _selected = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: true, initialKeyCode: keyPressed }); this.setState({ selected: _selected }); } }, setInactive: function setInactive() { var rowIdx = this.state.selected.rowIdx; var idx = this.state.selected.idx; if (this.canEdit(idx) && this.isActive()) { var _selected2 = Object.assign(this.state.selected, { idx: idx, rowIdx: rowIdx, active: false }); this.setState({ selected: _selected2 }); } }, canEdit: function canEdit(idx) { var col = this.getColumn(idx); return this.props.enableCellSelect === true && (col.editor != null || col.editable); }, isActive: function isActive() { return this.state.selected.active === true; }, setupGridColumns: function setupGridColumns() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var cols = props.columns.slice(0); var unshiftedCols = {}; if (props.enableRowSelect) { var headerRenderer = props.enableRowSelect === 'single' ? null : React.createElement( 'div', { className: 'react-grid-checkbox-container' }, React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: 'select-all-checkbox', onChange: this.handleCheckboxChange }), React.createElement('label', { htmlFor: 'select-all-checkbox', className: 'react-grid-checkbox-label' }) ); var selectColumn = { key: 'select-row', name: '', formatter: React.createElement(CheckboxEditor, null), onCellChange: this.handleRowSelect, filterable: false, headerRenderer: headerRenderer, width: 60, locked: true, getRowMetaData: function getRowMetaData(rowData) { return rowData; } }; unshiftedCols = cols.unshift(selectColumn); cols = unshiftedCols > 0 ? cols : unshiftedCols; } return cols; }, copyPasteEnabled: function copyPasteEnabled() { return this.props.onCellCopyPaste !== null; }, dragEnabled: function dragEnabled() { return this.props.onCellsDragged !== null; }, renderToolbar: function renderToolbar() { var Toolbar = this.props.toolbar; if (React.isValidElement(Toolbar)) { return React.cloneElement(Toolbar, { onToggleFilter: this.onToggleFilter, numberOfRows: this.props.rowsCount }); } }, render: function render() { var cellMetaData = { selected: this.state.selected, dragged: this.state.dragged, onCellClick: this.onCellClick, onCellDoubleClick: this.onCellDoubleClick, onCommit: this.onCellCommit, onCommitCancel: this.setInactive, copied: this.state.copied, handleDragEnterRow: this.handleDragEnter, handleTerminateDrag: this.handleTerminateDrag, onDragHandleDoubleClick: this.onDragHandleDoubleClick }; var toolbar = this.renderToolbar(); var containerWidth = this.props.minWidth || this.DOMMetrics.gridWidth(); var gridWidth = containerWidth - this.state.scrollOffset; // depending on the current lifecycle stage, gridWidth() may not initialize correctly // this also handles cases where it always returns undefined -- such as when inside a div with display:none // eg Bootstrap tabs and collapses if (typeof containerWidth === 'undefined' || isNaN(containerWidth) || containerWidth === 0) { containerWidth = '100%'; } if (typeof gridWidth === 'undefined' || isNaN(gridWidth) || gridWidth === 0) { gridWidth = '100%'; } return React.createElement( 'div', { className: 'react-grid-Container', style: { width: containerWidth } }, toolbar, React.createElement( 'div', { className: 'react-grid-Main' }, React.createElement(BaseGrid, _extends({ ref: 'base' }, this.props, { rowKey: this.props.rowKey, headerRows: this.getHeaderRows(), columnMetrics: this.state.columnMetrics, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, rowHeight: this.props.rowHeight, cellMetaData: cellMetaData, selectedRows: this.state.selectedRows.filter(function (r) { return r.isSelected === true; }), expandedRows: this.state.expandedRows, rowOffsetHeight: this.getRowOffsetHeight(), sortColumn: this.state.sortColumn, sortDirection: this.state.sortDirection, onSort: this.handleSort, minHeight: this.props.minHeight, totalWidth: gridWidth, onViewportKeydown: this.onKeyDown, onViewportDragStart: this.onDragStart, onViewportDragEnd: this.handleDragEnd, onViewportDoubleClick: this.onViewportDoubleClick, onColumnResize: this.onColumnResize, rowScrollTimeout: this.props.rowScrollTimeout })) ) ); } }); module.exports = ReactDataGrid; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ 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 React = __webpack_require__(2); var PropTypes = React.PropTypes; var Header = __webpack_require__(5); var Viewport = __webpack_require__(21); var GridScrollMixin = __webpack_require__(35); var DOMMetrics = __webpack_require__(34); var cellMetaDataShape = __webpack_require__(31); var Grid = React.createClass({ displayName: 'Grid', propTypes: { rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), columnMetrics: PropTypes.object, minHeight: PropTypes.number, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), headerRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowHeight: PropTypes.number, rowRenderer: PropTypes.func, emptyRowsView: PropTypes.func, expandedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), selectedRows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]), rowsCount: PropTypes.number, onRows: PropTypes.func, sortColumn: React.PropTypes.string, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']), rowOffsetHeight: PropTypes.number.isRequired, onViewportKeydown: PropTypes.func.isRequired, onViewportDragStart: PropTypes.func.isRequired, onViewportDragEnd: PropTypes.func.isRequired, onViewportDoubleClick: PropTypes.func.isRequired, onColumnResize: PropTypes.func, onSort: PropTypes.func, cellMetaData: PropTypes.shape(cellMetaDataShape), rowKey: PropTypes.string.isRequired, rowScrollTimeout: PropTypes.number }, mixins: [GridScrollMixin, DOMMetrics.MetricsComputatorMixin], getDefaultProps: function getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; }, getStyle: function getStyle() { return { overflow: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight }; }, render: function render() { var headerRows = this.props.headerRows || [{ ref: 'row' }]; var EmptyRowsView = this.props.emptyRowsView; return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: 'react-grid-Grid' }), React.createElement(Header, { ref: 'header', columnMetrics: this.props.columnMetrics, onColumnResize: this.props.onColumnResize, height: this.props.rowHeight, totalWidth: this.props.totalWidth, headerRows: headerRows, sortColumn: this.props.sortColumn, sortDirection: this.props.sortDirection, onSort: this.props.onSort, onScroll: this.onHeaderScroll }), this.props.rowsCount >= 1 || this.props.rowsCount === 0 && !this.props.emptyRowsView ? React.createElement( 'div', { ref: 'viewPortContainer', onKeyDown: this.props.onViewportKeydown, onDoubleClick: this.props.onViewportDoubleClick, onDragStart: this.props.onViewportDragStart, onDragEnd: this.props.onViewportDragEnd }, React.createElement(Viewport, { ref: 'viewport', rowKey: this.props.rowKey, width: this.props.columnMetrics.width, rowHeight: this.props.rowHeight, rowRenderer: this.props.rowRenderer, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columnMetrics: this.props.columnMetrics, totalWidth: this.props.totalWidth, onScroll: this.onScroll, onRows: this.props.onRows, cellMetaData: this.props.cellMetaData, rowOffsetHeight: this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length, minHeight: this.props.minHeight, rowScrollTimeout: this.props.rowScrollTimeout }) ) : React.createElement( 'div', { ref: 'emptyView', className: 'react-grid-Empty' }, React.createElement(EmptyRowsView, null) ) ); } }); module.exports = Grid; /***/ }, /* 5 */ /***/ 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 React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var shallowCloneObject = __webpack_require__(7); var ColumnMetrics = __webpack_require__(8); var ColumnUtils = __webpack_require__(10); var HeaderRow = __webpack_require__(12); var PropTypes = React.PropTypes; var Header = React.createClass({ displayName: 'Header', propTypes: { columnMetrics: PropTypes.shape({ width: PropTypes.number.isRequired, columns: PropTypes.any }).isRequired, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, headerRows: PropTypes.array.isRequired, sortColumn: PropTypes.string, sortDirection: PropTypes.oneOf(['ASC', 'DESC', 'NONE']), onSort: PropTypes.func, onColumnResize: PropTypes.func, onScroll: PropTypes.func }, getInitialState: function getInitialState() { return { resizing: null }; }, componentWillReceiveProps: function componentWillReceiveProps() { this.setState({ resizing: null }); }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { var update = !ColumnMetrics.sameColumns(this.props.columnMetrics.columns, nextProps.columnMetrics.columns, ColumnMetrics.sameColumn) || this.props.totalWidth !== nextProps.totalWidth || this.props.headerRows.length !== nextProps.headerRows.length || this.state.resizing !== nextState.resizing || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection; return update; }, onColumnResize: function onColumnResize(column, width) { var state = this.state.resizing || this.props; var pos = this.getColumnPosition(column); if (pos != null) { var _resizing = { columnMetrics: shallowCloneObject(state.columnMetrics) }; _resizing.columnMetrics = ColumnMetrics.resizeColumn(_resizing.columnMetrics, pos, width); // we don't want to influence scrollLeft while resizing if (_resizing.columnMetrics.totalWidth < state.columnMetrics.totalWidth) { _resizing.columnMetrics.totalWidth = state.columnMetrics.totalWidth; } _resizing.column = ColumnUtils.getColumn(_resizing.columnMetrics.columns, pos); this.setState({ resizing: _resizing }); } }, onColumnResizeEnd: function onColumnResizeEnd(column, width) { var pos = this.getColumnPosition(column); if (pos !== null && this.props.onColumnResize) { this.props.onColumnResize(pos, width || column.width); } }, getHeaderRows: function getHeaderRows() { var _this = this; var columnMetrics = this.getColumnMetrics(); var resizeColumn = void 0; if (this.state.resizing) { resizeColumn = this.state.resizing.column; } var headerRows = []; this.props.headerRows.forEach(function (row, index) { var headerRowStyle = { position: 'absolute', top: _this.getCombinedHeaderHeights(index), left: 0, width: _this.props.totalWidth, overflow: 'hidden' }; headerRows.push(React.createElement(HeaderRow, { key: row.ref, ref: row.ref, style: headerRowStyle, onColumnResize: _this.onColumnResize, onColumnResizeEnd: _this.onColumnResizeEnd, width: columnMetrics.width, height: row.height || _this.props.height, columns: columnMetrics.columns, resizing: resizeColumn, filterable: row.filterable, onFilterChange: row.onFilterChange, sortColumn: _this.props.sortColumn, sortDirection: _this.props.sortDirection, onSort: _this.props.onSort, onScroll: _this.props.onScroll })); }); return headerRows; }, getColumnMetrics: function getColumnMetrics() { var columnMetrics = void 0; if (this.state.resizing) { columnMetrics = this.state.resizing.columnMetrics; } else { columnMetrics = this.props.columnMetrics; } return columnMetrics; }, getColumnPosition: function getColumnPosition(column) { var columnMetrics = this.getColumnMetrics(); var pos = -1; columnMetrics.columns.forEach(function (c, idx) { if (c.key === column.key) { pos = idx; } }); return pos === -1 ? null : pos; }, getCombinedHeaderHeights: function getCombinedHeaderHeights(until) { var stopAt = this.props.headerRows.length; if (typeof until !== 'undefined') { stopAt = until; } var height = 0; for (var index = 0; index < stopAt; index++) { height += this.props.headerRows[index].height || this.props.height; } return height; }, getStyle: function getStyle() { return { position: 'relative', height: this.getCombinedHeaderHeights(), overflow: 'hidden' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = ReactDOM.findDOMNode(this.refs.row); node.scrollLeft = scrollLeft; this.refs.row.setScrollLeft(scrollLeft); if (this.refs.filterRow) { var nodeFilters = ReactDOM.findDOMNode(this.refs.filterRow); nodeFilters.scrollLeft = scrollLeft; this.refs.filterRow.setScrollLeft(scrollLeft); } }, render: function render() { var className = joinClasses({ 'react-grid-Header': true, 'react-grid-Header--resizing': !!this.state.resizing }); var headerRows = this.getHeaderRows(); return React.createElement( 'div', _extends({}, this.props, { style: this.getStyle(), className: className }), headerRows ); } }); module.exports = Header; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__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__)); } /***/ }, /* 7 */ /***/ function(module, exports) { "use strict"; function shallowCloneObject(obj) { var result = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } return result; } module.exports = shallowCloneObject; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var shallowCloneObject = __webpack_require__(7); var sameColumn = __webpack_require__(9); var ColumnUtils = __webpack_require__(10); var getScrollbarSize = __webpack_require__(11); function setColumnWidths(columns, totalWidth) { return columns.map(function (column) { var colInfo = Object.assign({}, column); if (column.width) { if (/^([0-9]+)%$/.exec(column.width.toString())) { colInfo.width = Math.floor(column.width / 100 * totalWidth); } } return colInfo; }); } function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) { var defferedColumns = columns.filter(function (c) { return !c.width; }); return columns.map(function (column) { if (!column.width) { if (unallocatedWidth <= 0) { column.width = minColumnWidth; } else { column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns)); } } return column; }); } function setColumnOffsets(columns) { var left = 0; return columns.map(function (column) { column.left = left; left += column.width; return column; }); } /** * Update column metrics calculation. * * @param {ColumnMetricsType} metrics */ function recalculate(metrics) { // compute width for columns which specify width var columns = setColumnWidths(metrics.columns, metrics.totalWidth); var unallocatedWidth = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w - column.width; }, metrics.totalWidth); unallocatedWidth -= getScrollbarSize(); var width = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w + column.width; }, 0); // compute width for columns which doesn't specify width columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth); // compute left offset columns = setColumnOffsets(columns); return { columns: columns, width: width, totalWidth: metrics.totalWidth, minColumnWidth: metrics.minColumnWidth }; } /** * Update column metrics calculation by resizing a column. * * @param {ColumnMetricsType} metrics * @param {Column} column * @param {number} width */ function resizeColumn(metrics, index, width) { var column = ColumnUtils.getColumn(metrics.columns, index); var metricsClone = shallowCloneObject(metrics); metricsClone.columns = metrics.columns.slice(0); var updatedColumn = shallowCloneObject(column); updatedColumn.width = Math.max(width, metricsClone.minColumnWidth); metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn); return recalculate(metricsClone); } function areColumnsImmutable(prevColumns, nextColumns) { return typeof Immutable !== 'undefined' && prevColumns instanceof Immutable.List && nextColumns instanceof Immutable.List; } function compareEachColumn(prevColumns, nextColumns, isSameColumn) { var i = void 0; var len = void 0; var column = void 0; var prevColumnsByKey = {}; var nextColumnsByKey = {}; if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) { return false; } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; prevColumnsByKey[column.key] = column; } for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) { column = nextColumns[i]; nextColumnsByKey[column.key] = column; var prevColumn = prevColumnsByKey[column.key]; if (prevColumn === undefined || !isSameColumn(prevColumn, column)) { return false; } } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; var nextColumn = nextColumnsByKey[column.key]; if (nextColumn === undefined) { return false; } } return true; } function sameColumns(prevColumns, nextColumns, isSameColumn) { if (areColumnsImmutable(prevColumns, nextColumns)) { return prevColumns === nextColumns; } return compareEachColumn(prevColumns, nextColumns, isSameColumn); } module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isValidElement = __webpack_require__(2).isValidElement; module.exports = function sameColumn(a, b) { var k = void 0; for (k in a) { if (a.hasOwnProperty(k)) { if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) { continue; } if (!b.hasOwnProperty(k) || a[k] !== b[k]) { return false; } } } for (k in b) { if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) { return false; } } return true; }; /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; module.exports = { getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, spliceColumn: function spliceColumn(metrics, idx, column) { if (Array.isArray(metrics.columns)) { metrics.columns.splice(idx, 1, column); } else if (typeof Immutable !== 'undefined') { metrics.columns = metrics.columns.splice(idx, 1, column); } return metrics; }, getSize: function getSize(columns) { if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } } }; /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict'; var size = void 0; function getScrollbarSize() { if (size === undefined) { var outer = document.createElement('div'); outer.style.width = '50px'; outer.style.height = '50px'; outer.style.position = 'absolute'; outer.style.top = '-200px'; outer.style.left = '-200px'; var inner = document.createElement('div'); inner.style.height = '100px'; inner.style.width = '100%'; outer.appendChild(inner); document.body.appendChild(outer); var outerWidth = outer.clientWidth; outer.style.overflowY = 'scroll'; var innerWidth = inner.clientWidth; document.body.removeChild(outer); size = outerWidth - innerWidth; } return size; } module.exports = getScrollbarSize; /***/ }, /* 12 */ /***/ 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 React = __webpack_require__(2); var shallowEqual = __webpack_require__(13); var HeaderCell = __webpack_require__(14); var getScrollbarSize = __webpack_require__(11); var ExcelColumn = __webpack_require__(15); var ColumnUtilsMixin = __webpack_require__(10); var SortableHeaderCell = __webpack_require__(18); var FilterableHeaderCell = __webpack_require__(19); var HeaderCellType = __webpack_require__(20); var PropTypes = React.PropTypes; var HeaderRowStyle = { overflow: React.PropTypes.string, width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: React.PropTypes.number, position: React.PropTypes.string }; var DEFINE_SORT = ['ASC', 'DESC', 'NONE']; var HeaderRow = React.createClass({ displayName: 'HeaderRow', propTypes: { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.array, PropTypes.object]), onColumnResize: PropTypes.func, onSort: PropTypes.func.isRequired, onColumnResizeEnd: PropTypes.func, style: PropTypes.shape(HeaderRowStyle), sortColumn: PropTypes.string, sortDirection: React.PropTypes.oneOf(DEFINE_SORT), cellRenderer: PropTypes.func, headerCellRenderer: PropTypes.func, filterable: PropTypes.bool, onFilterChange: PropTypes.func, resizing: PropTypes.func, onScroll: PropTypes.func }, mixins: [ColumnUtilsMixin], shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.width !== this.props.width || nextProps.height !== this.props.height || nextProps.columns !== this.props.columns || !shallowEqual(nextProps.style, this.props.style) || this.props.sortColumn !== nextProps.sortColumn || this.props.sortDirection !== nextProps.sortDirection; }, getHeaderCellType: function getHeaderCellType(column) { if (column.filterable) { if (this.props.filterable) return HeaderCellType.FILTERABLE; } if (column.sortable) return HeaderCellType.SORTABLE; return HeaderCellType.NONE; }, getFilterableHeaderCell: function getFilterableHeaderCell() { return React.createElement(FilterableHeaderCell, { onChange: this.props.onFilterChange }); }, getSortableHeaderCell: function getSortableHeaderCell(column) { var sortDirection = this.props.sortColumn === column.key ? this.props.sortDirection : DEFINE_SORT.NONE; return React.createElement(SortableHeaderCell, { columnKey: column.key, onSort: this.props.onSort, sortDirection: sortDirection }); }, getHeaderRenderer: function getHeaderRenderer(column) { var renderer = void 0; if (column.headerRenderer) { renderer = column.headerRenderer; } else { var headerCellType = this.getHeaderCellType(column); switch (headerCellType) { case HeaderCellType.SORTABLE: renderer = this.getSortableHeaderCell(column); break; case HeaderCellType.FILTERABLE: renderer = this.getFilterableHeaderCell(); break; default: break; } } return renderer; }, getStyle: function getStyle() { return { overflow: 'hidden', width: '100%', height: this.props.height, position: 'absolute' }; }, getCells: function getCells() { var cells = []; var lockedCells = []; for (var i = 0, len = this.getSize(this.props.columns); i < len; i++) { var column = this.getColumn(this.props.columns, i); var cell = React.createElement(HeaderCell, { ref: i, key: i, height: this.props.height, column: column, renderer: this.getHeaderRenderer(column), resizing: this.props.resizing === column, onResize: this.props.onColumnResize, onResizeEnd: this.props.onColumnResizeEnd }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } } return cells.concat(lockedCells); }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this = this; this.props.columns.forEach(function (column, i) { if (column.locked) { _this.refs[i].setScrollLeft(scrollLeft); } }); }, render: function render() { var cellsStyle = { width: this.props.width ? this.props.width + getScrollbarSize() : '100%', height: this.props.height, whiteSpace: 'nowrap', overflowX: 'hidden', overflowY: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: 'react-grid-HeaderRow', onScroll: this.props.onScroll }), React.createElement( 'div', { style: cellsStyle }, cells ) ); } }); module.exports = HeaderRow; /***/ }, /* 13 */ /***/ 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 shallowEqual * @typechecks * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var ExcelColumn = __webpack_require__(15); var ResizeHandle = __webpack_require__(16); var PropTypes = React.PropTypes; function simpleCellRenderer(objArgs) { return React.createElement( 'div', { className: 'widget-HeaderCell__value' }, objArgs.column.name ); } var HeaderCell = React.createClass({ displayName: 'HeaderCell', propTypes: { renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired, column: PropTypes.shape(ExcelColumn).isRequired, onResize: PropTypes.func.isRequired, height: PropTypes.number.isRequired, onResizeEnd: PropTypes.func.isRequired, className: PropTypes.string }, getDefaultProps: function getDefaultProps() { return { renderer: simpleCellRenderer }; }, getInitialState: function getInitialState() { return { resizing: false }; }, onDragStart: function onDragStart(e) { this.setState({ resizing: true }); // need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onDrag: function onDrag(e) { var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct if (resize) { var _width = this.getWidthFromMouseEvent(e); if (_width > 0) { resize(this.props.column, _width); } } }, onDragEnd: function onDragEnd(e) { var width = this.getWidthFromMouseEvent(e); this.props.onResizeEnd(this.props.column, width); this.setState({ resizing: false }); }, getWidthFromMouseEvent: function getWidthFromMouseEvent(e) { var right = e.pageX; var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left; return right - left; }, getCell: function getCell() { if (React.isValidElement(this.props.renderer)) { return React.cloneElement(this.props.renderer, { column: this.props.column }); } return this.props.renderer({ column: this.props.column }); }, getStyle: function getStyle() { return { width: this.props.column.width, left: this.props.column.left, display: 'inline-block', position: 'absolute', overflow: 'hidden', height: this.props.height, margin: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = ReactDOM.findDOMNode(this); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }, render: function render() { var resizeHandle = void 0; if (this.props.column.resizable) { resizeHandle = React.createElement(ResizeHandle, { onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd }); } var className = joinClasses({ 'react-grid-HeaderCell': true, 'react-grid-HeaderCell--resizing': this.state.resizing, 'react-grid-HeaderCell--locked': this.props.column.locked }); className = joinClasses(className, this.props.className, this.props.column.cellClass); var cell = this.getCell(); return React.createElement( 'div', { className: className, style: this.getStyle() }, cell, resizeHandle ); } }); module.exports = HeaderCell; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ExcelColumnShape = { name: React.PropTypes.node.isRequired, key: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired, filterable: React.PropTypes.bool }; module.exports = ExcelColumnShape; /***/ }, /* 16 */ /***/ 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 React = __webpack_require__(2); var Draggable = __webpack_require__(17); var ResizeHandle = React.createClass({ displayName: 'ResizeHandle', style: { position: 'absolute', top: 0, right: 0, width: 6, height: '100%' }, render: function render() { return React.createElement(Draggable, _extends({}, this.props, { className: 'react-grid-HeaderCell__resizeHandle', style: this.style })); } }); module.exports = ResizeHandle; /***/ }, /* 17 */ /***/ 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 React = __webpack_require__(2); var PropTypes = React.PropTypes; var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]) }, getDefaultProps: function getDefaultProps() { return { onDragStart: function onDragStart() { return true; }, onDragEnd: function onDragEnd() {}, onDrag: function onDrag() {} }; }, getInitialState: function getInitialState() { return { drag: null }; }, componentWillUnmount: function componentWillUnmount() { this.cleanUp(); }, onMouseDown: function onMouseDown(e) { var drag = this.props.onDragStart(e); if (drag === null && e.button !== 0) { return; } window.addEventListener('mouseup', this.onMouseUp); window.addEventListener('mousemove', this.onMouseMove); this.setState({ drag: drag }); }, onMouseMove: function onMouseMove(e) { if (this.state.drag === null) { return; } if (e.preventDefault) { e.preventDefault(); } this.props.onDrag(e); }, onMouseUp: function onMouseUp(e) { this.cleanUp(); this.props.onDragEnd(e, this.state.drag); this.setState({ drag: null }); }, cleanUp: function cleanUp() { window.removeEventListener('mouseup', this.onMouseUp); window.removeEventListener('mousemove', this.onMouseMove); }, render: function render() { return React.createElement('div', _extends({}, this.props, { onMouseDown: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); } }); module.exports = Draggable; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var joinClasses = __webpack_require__(6); var DEFINE_SORT = { ASC: 'ASC', DESC: 'DESC', NONE: 'NONE' }; var SortableHeaderCell = React.createClass({ displayName: 'SortableHeaderCell', propTypes: { columnKey: React.PropTypes.string.isRequired, column: React.PropTypes.shape({ name: React.PropTypes.node }), onSort: React.PropTypes.func.isRequired, sortDirection: React.PropTypes.oneOf(['ASC', 'DESC', 'NONE']) }, onClick: function onClick() { var direction = void 0; switch (this.props.sortDirection) { default: case null: case undefined: case DEFINE_SORT.NONE: direction = DEFINE_SORT.ASC; break; case DEFINE_SORT.ASC: direction = DEFINE_SORT.DESC; break; case DEFINE_SORT.DESC: direction = DEFINE_SORT.NONE; break; } this.props.onSort(this.props.columnKey, direction); }, getSortByText: function getSortByText() { var unicodeKeys = { ASC: '9650', DESC: '9660', NONE: '' }; return String.fromCharCode(unicodeKeys[this.props.sortDirection]); }, render: function render() { var className = joinClasses({ 'react-grid-HeaderCell-sortable': true, 'react-grid-HeaderCell-sortable--ascending': this.props.sortDirection === 'ASC', 'react-grid-HeaderCell-sortable--descending': this.props.sortDirection === 'DESC' }); return React.createElement( 'div', { className: className, onClick: this.onClick, style: { cursor: 'pointer' } }, this.props.column.name, React.createElement( 'span', { className: 'pull-right' }, this.getSortByText() ) ); } }); module.exports = SortableHeaderCell; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ExcelColumn = __webpack_require__(15); var FilterableHeaderCell = React.createClass({ displayName: 'FilterableHeaderCell', propTypes: { onChange: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn) }, getInitialState: function getInitialState() { return { filterTerm: '' }; }, handleChange: function handleChange(e) { var val = e.target.value; this.setState({ filterTerm: val }); this.props.onChange({ filterTerm: val, columnKey: this.props.column.key }); }, renderInput: function renderInput() { if (this.props.column.filterable === false) { return React.createElement('span', null); } var inputKey = 'header-filter-' + this.props.column.key; return React.createElement('input', { key: inputKey, type: 'text', className: 'form-control input-sm', placeholder: 'Search', value: this.state.filterTerm, onChange: this.handleChange }); }, render: function render() { return React.createElement( 'div', null, React.createElement( 'div', { className: 'form-group' }, this.renderInput() ) ); } }); module.exports = FilterableHeaderCell; /***/ }, /* 20 */ /***/ function(module, exports) { "use strict"; var HeaderCellType = { SORTABLE: 0, FILTERABLE: 1, NONE: 2, CHECKBOX: 3 }; module.exports = HeaderCellType; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var Canvas = __webpack_require__(22); var ViewportScroll = __webpack_require__(33); var cellMetaDataShape = __webpack_require__(31); var PropTypes = React.PropTypes; var Viewport = React.createClass({ displayName: 'Viewport', mixins: [ViewportScroll], propTypes: { rowOffsetHeight: PropTypes.number.isRequired, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]).isRequired, columnMetrics: PropTypes.object.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, selectedRows: PropTypes.array, expandedRows: PropTypes.array, rowRenderer: PropTypes.func, rowsCount: PropTypes.number.isRequired, rowHeight: PropTypes.number.isRequired, onRows: PropTypes.func, onScroll: PropTypes.func, minHeight: PropTypes.number, cellMetaData: PropTypes.shape(cellMetaDataShape), rowKey: PropTypes.string.isRequired, rowScrollTimeout: PropTypes.number }, onScroll: function onScroll(scroll) { this.updateScroll(scroll.scrollTop, scroll.scrollLeft, this.state.height, this.props.rowHeight, this.props.rowsCount); if (this.props.onScroll) { this.props.onScroll({ scrollTop: scroll.scrollTop, scrollLeft: scroll.scrollLeft }); } }, getScroll: function getScroll() { return this.refs.canvas.getScroll(); }, setScrollLeft: function setScrollLeft(scrollLeft) { this.refs.canvas.setScrollLeft(scrollLeft); }, render: function render() { var style = { padding: 0, bottom: 0, left: 0, right: 0, overflow: 'hidden', position: 'absolute', top: this.props.rowOffsetHeight }; return React.createElement( 'div', { className: 'react-grid-Viewport', style: style }, React.createElement(Canvas, { ref: 'canvas', rowKey: this.props.rowKey, totalWidth: this.props.totalWidth, width: this.props.columnMetrics.width, rowGetter: this.props.rowGetter, rowsCount: this.props.rowsCount, selectedRows: this.props.selectedRows, expandedRows: this.props.expandedRows, columns: this.props.columnMetrics.columns, rowRenderer: this.props.rowRenderer, displayStart: this.state.displayStart, displayEnd: this.state.displayEnd, cellMetaData: this.props.cellMetaData, height: this.state.height, rowHeight: this.props.rowHeight, onScroll: this.onScroll, onRows: this.props.onRows, rowScrollTimeout: this.props.rowScrollTimeout }) ); } }); module.exports = Viewport; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _shallowEqual = __webpack_require__(13); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var PropTypes = React.PropTypes; var ScrollShim = __webpack_require__(23); var Row = __webpack_require__(24); var cellMetaDataShape = __webpack_require__(31); var Canvas = React.createClass({ displayName: 'Canvas', mixins: [ScrollShim], propTypes: { rowRenderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]), rowHeight: PropTypes.number.isRequired, height: PropTypes.number.isRequired, width: PropTypes.number, totalWidth: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), style: PropTypes.string, className: PropTypes.string, displayStart: PropTypes.number.isRequired, displayEnd: PropTypes.number.isRequired, rowsCount: PropTypes.number.isRequired, rowGetter: PropTypes.oneOfType([PropTypes.func.isRequired, PropTypes.array.isRequired]), expandedRows: PropTypes.array, onRows: PropTypes.func, onScroll: PropTypes.func, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, cellMetaData: PropTypes.shape(cellMetaDataShape).isRequired, selectedRows: PropTypes.array, rowKey: React.PropTypes.string, rowScrollTimeout: React.PropTypes.number }, getDefaultProps: function getDefaultProps() { return { rowRenderer: Row, onRows: function onRows() {}, selectedRows: [], rowScrollTimeout: 0 }; }, getInitialState: function getInitialState() { return { displayStart: this.props.displayStart, displayEnd: this.props.displayEnd, scrollingTimeout: null }; }, componentWillMount: function componentWillMount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidMount: function componentDidMount() { this.onRows(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.displayStart !== this.state.displayStart || nextProps.displayEnd !== this.state.displayEnd) { this.setState({ displayStart: nextProps.displayStart, displayEnd: nextProps.displayEnd }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { var shouldUpdate = nextState.displayStart !== this.state.displayStart || nextState.displayEnd !== this.state.displayEnd || nextState.scrollingTimeout !== this.state.scrollingTimeout || nextProps.rowsCount !== this.props.rowsCount || nextProps.rowHeight !== this.props.rowHeight || nextProps.columns !== this.props.columns || nextProps.width !== this.props.width || nextProps.cellMetaData !== this.props.cellMetaData || !(0, _shallowEqual2['default'])(nextProps.style, this.props.style); return shouldUpdate; }, componentWillUnmount: function componentWillUnmount() { this._currentRowsLength = 0; this._currentRowsRange = { start: 0, end: 0 }; this._scroll = { scrollTop: 0, scrollLeft: 0 }; }, componentDidUpdate: function componentDidUpdate() { if (this._scroll.scrollTop !== 0 && this._scroll.scrollLeft !== 0) { this.setScrollLeft(this._scroll.scrollLeft); } this.onRows(); }, onRows: function onRows() { if (this._currentRowsRange !== { start: 0, end: 0 }) { this.props.onRows(this._currentRowsRange); this._currentRowsRange = { start: 0, end: 0 }; } }, onScroll: function onScroll(e) { var _this = this; if (this.getDOMNode() !== e.target) { return; } this.appendScrollShim(); var scrollLeft = e.target.scrollLeft; var scrollTop = e.target.scrollTop || this._scroll.scrollTop; var scroll = { scrollTop: scrollTop, scrollLeft: scrollLeft }; // check how far we have scrolled, and if this means we are being taken out of range var scrollYRange = Math.abs(this._scroll.scrollTop - scroll.scrollTop) / this.props.rowHeight; var scrolledOutOfRange = scrollYRange > this.props.displayEnd - this.props.displayStart; this._scroll = scroll; this.props.onScroll(scroll); // if we go out of range, we queue the actual render, just rendering cheap placeholders // avoiding rendering anything expensive while a user scrolls down if (scrolledOutOfRange && this.props.rowScrollTimeout > 0) { var scrollTO = this.state.scrollingTimeout; if (scrollTO) { clearTimeout(scrollTO); } // queue up, and set state to clear the TO so we render the rows (not placeholders) scrollTO = setTimeout(function () { if (_this.state.scrollingTimeout !== null) { _this.setState({ scrollingTimeout: null }); } }, this.props.rowScrollTimeout); this.setState({ scrollingTimeout: scrollTO }); } }, getRows: function getRows(displayStart, displayEnd) { this._currentRowsRange = { start: displayStart, end: displayEnd }; if (Array.isArray(this.props.rowGetter)) { return this.props.rowGetter.slice(displayStart, displayEnd); } var rows = []; for (var i = displayStart; i < displayEnd; i++) { rows.push(this.props.rowGetter(i)); } return rows; }, getScrollbarWidth: function getScrollbarWidth() { var scrollbarWidth = 0; // Get the scrollbar width var canvas = ReactDOM.findDOMNode(this); scrollbarWidth = canvas.offsetWidth - canvas.clientWidth; return scrollbarWidth; }, getScroll: function getScroll() { var _ReactDOM$findDOMNode = ReactDOM.findDOMNode(this); var scrollTop = _ReactDOM$findDOMNode.scrollTop; var scrollLeft = _ReactDOM$findDOMNode.scrollLeft; return { scrollTop: scrollTop, scrollLeft: scrollLeft }; }, isRowSelected: function isRowSelected(row) { var _this2 = this; var selectedRows = this.props.selectedRows.filter(function (r) { var rowKeyValue = row.get ? row.get(_this2.props.rowKey) : row[_this2.props.rowKey]; return r[_this2.props.rowKey] === rowKeyValue; }); return selectedRows.length > 0 && selectedRows[0].isSelected; }, _currentRowsLength: 0, _currentRowsRange: { start: 0, end: 0 }, _scroll: { scrollTop: 0, scrollLeft: 0 }, setScrollLeft: function setScrollLeft(scrollLeft) { if (this._currentRowsLength !== 0) { if (!this.refs) return; for (var i = 0, len = this._currentRowsLength; i < len; i++) { if (this.refs[i] && this.refs[i].setScrollLeft) { this.refs[i].setScrollLeft(scrollLeft); } } } }, renderRow: function renderRow(props) { if (this.state.scrollingTimeout !== null) { // in the midst of a rapid scroll, so we render placeholders // the actual render is then queued (through a timeout) // this avoids us redering a bunch of rows that a user is trying to scroll past return this.renderScrollingPlaceholder(props); } var RowsRenderer = this.props.rowRenderer; if (typeof RowsRenderer === 'function') { return React.createElement(RowsRenderer, props); } if (React.isValidElement(this.props.rowRenderer)) { return React.cloneElement(this.props.rowRenderer, props); } }, renderScrollingPlaceholder: function renderScrollingPlaceholder(props) { // here we are just rendering empty cells // we may want to allow a user to inject this, and/or just render the cells that are in view // for now though we essentially are doing a (very lightweight) row + cell with empty content var styles = { row: { height: props.height, overflow: 'hidden' }, cell: { height: props.height, position: 'absolute' }, placeholder: { backgroundColor: 'rgba(211, 211, 211, 0.45)', width: '60%', height: Math.floor(props.height * 0.3) } }; return React.createElement( 'div', { key: props.key, style: styles.row, className: 'react-grid-Row' }, this.props.columns.map(function (col, idx) { return React.createElement( 'div', { style: Object.assign(styles.cell, { width: col.width, left: col.left }), key: idx, className: 'react-grid-Cell' }, React.createElement('div', { style: Object.assign(styles.placeholder, { width: Math.floor(col.width * 0.6) }) }) ); }) ); }, renderPlaceholder: function renderPlaceholder(key, height) { // just renders empty cells // if we wanted to show gridlines, we'd need classes and position as with renderScrollingPlaceholder return React.createElement( 'div', { key: key, style: { height: height } }, this.props.columns.map(function (column, idx) { return React.createElement('div', { style: { width: column.width }, key: idx }); }) ); }, render: function render() { var _this3 = this; var displayStart = this.state.displayStart; var displayEnd = this.state.displayEnd; var rowHeight = this.props.rowHeight; var length = this.props.rowsCount; var rows = this.getRows(displayStart, displayEnd).map(function (row, idx) { return _this3.renderRow({ key: displayStart + idx, ref: idx, idx: displayStart + idx, row: row, height: rowHeight, columns: _this3.props.columns, isSelected: _this3.isRowSelected(row), expandedRows: _this3.props.expandedRows, cellMetaData: _this3.props.cellMetaData }); }); this._currentRowsLength = rows.length; if (displayStart > 0) { rows.unshift(this.renderPlaceholder('top', displayStart * rowHeight)); } if (length - displayEnd > 0) { rows.push(this.renderPlaceholder('bottom', (length - displayEnd) * rowHeight)); } var style = { position: 'absolute', top: 0, left: 0, overflowX: 'auto', overflowY: 'scroll', width: this.props.totalWidth, height: this.props.height, transform: 'translate3d(0, 0, 0)' }; return React.createElement( 'div', { style: style, onScroll: this.onScroll, className: joinClasses('react-grid-Canvas', this.props.className, { opaque: this.props.cellMetaData.selected && this.props.cellMetaData.selected.active }) }, React.createElement( 'div', { style: { width: this.props.width, overflow: 'hidden' } }, rows ) ); } }); module.exports = Canvas; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var ScrollShim = { appendScrollShim: function appendScrollShim() { if (!this._scrollShim) { var size = this._scrollShimSize(); var shim = document.createElement('div'); if (shim.classList) { shim.classList.add('react-grid-ScrollShim'); // flow - not compatible with HTMLElement } else { shim.className += ' react-grid-ScrollShim'; } shim.style.position = 'absolute'; shim.style.top = 0; shim.style.left = 0; shim.style.width = size.width + 'px'; shim.style.height = size.height + 'px'; _reactDom2['default'].findDOMNode(this).appendChild(shim); this._scrollShim = shim; } this._scheduleRemoveScrollShim(); }, _scrollShimSize: function _scrollShimSize() { return { width: this.props.width, height: this.props.length * this.props.rowHeight }; }, _scheduleRemoveScrollShim: function _scheduleRemoveScrollShim() { if (this._scheduleRemoveScrollShimTimer) { clearTimeout(this._scheduleRemoveScrollShimTimer); } this._scheduleRemoveScrollShimTimer = setTimeout(this._removeScrollShim, 200); }, _removeScrollShim: function _removeScrollShim() { if (this._scrollShim) { this._scrollShim.parentNode.removeChild(this._scrollShim); this._scrollShim = undefined; } } }; module.exports = ScrollShim; /***/ }, /* 24 */ /***/ 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 React = __webpack_require__(2); var joinClasses = __webpack_require__(6); var Cell = __webpack_require__(25); var ColumnMetrics = __webpack_require__(8); var ColumnUtilsMixin = __webpack_require__(10); var cellMetaDataShape = __webpack_require__(31); var PropTypes = React.PropTypes; var Row = React.createClass({ displayName: 'Row', propTypes: { height: PropTypes.number.isRequired, columns: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired, row: PropTypes.any.isRequired, cellRenderer: PropTypes.func, cellMetaData: PropTypes.shape(cellMetaDataShape), isSelected: PropTypes.bool, idx: PropTypes.number.isRequired, key: PropTypes.string, expandedRows: PropTypes.arrayOf(PropTypes.object) }, mixins: [ColumnUtilsMixin], getDefaultProps: function getDefaultProps() { return { cellRenderer: Cell, isSelected: false, height: 35 }; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return !ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, ColumnMetrics.sameColumn) || this.doesRowContainSelectedCell(this.props) || this.doesRowContainSelectedCell(nextProps) || this.willRowBeDraggedOver(nextProps) || nextProps.row !== this.props.row || this.hasRowBeenCopied() || this.props.isSelected !== nextProps.isSelected || nextProps.height !== this.props.height; }, handleDragEnter: function handleDragEnter() { var handleDragEnterRow = this.props.cellMetaData.handleDragEnterRow; if (handleDragEnterRow) { handleDragEnterRow(this.props.idx); } }, getSelectedColumn: function getSelectedColumn() { var selected = this.props.cellMetaData.selected; if (selected && selected.idx) { return this.getColumn(this.props.columns, selected.idx); } }, getCells: function getCells() { var _this = this; var cells = []; var lockedCells = []; var selectedColumn = this.getSelectedColumn(); this.props.columns.forEach(function (column, i) { var CellRenderer = _this.props.cellRenderer; var cell = React.createElement(CellRenderer, { ref: i, key: column.key + '-' + i, idx: i, rowIdx: _this.props.idx, value: _this.getCellValue(column.key || i), column: column, height: _this.getRowHeight(), formatter: column.formatter, cellMetaData: _this.props.cellMetaData, rowData: _this.props.row, selectedColumn: selectedColumn, isRowSelected: _this.props.isSelected }); if (column.locked) { lockedCells.push(cell); } else { cells.push(cell); } }); return cells.concat(lockedCells); }, getRowHeight: function getRowHeight() { var rows = this.props.expandedRows || null; if (rows && this.props.key) { var row = rows[this.props.key] || null; if (row) { return row.height; } } return this.props.height; }, getCellValue: function getCellValue(key) { var val = void 0; if (key === 'select-row') { return this.props.isSelected; } else if (typeof this.props.row.get === 'function') { val = this.props.row.get(key); } else { val = this.props.row[key]; } return val; }, setScrollLeft: function setScrollLeft(scrollLeft) { var _this2 = this; this.props.columns.forEach(function (column, i) { if (column.locked) { if (!_this2.refs[i]) return; _this2.refs[i].setScrollLeft(scrollLeft); } }); }, doesRowContainSelectedCell: function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } return false; }, willRowBeDraggedOver: function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); }, hasRowBeenCopied: function hasRowBeenCopied() { var copied = this.props.cellMetaData.copied; return copied != null && copied.rowIdx === this.props.idx; }, renderCell: function renderCell(props) { if (typeof this.props.cellRenderer === 'function') { this.props.cellRenderer.call(this, props); } if (React.isValidElement(this.props.cellRenderer)) { return React.cloneElement(this.props.cellRenderer, props); } return this.props.cellRenderer(props); }, render: function render() { var className = joinClasses('react-grid-Row', 'react-grid-Row--' + (this.props.idx % 2 === 0 ? 'even' : 'odd'), { 'row-selected': this.props.isSelected }); var style = { height: this.getRowHeight(this.props), overflow: 'hidden' }; var cells = this.getCells(); return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onDragEnter: this.handleDragEnter }), React.isValidElement(this.props.row) ? this.props.row : cells ); } }); module.exports = Row; /***/ }, /* 25 */ /***/ 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 React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var joinClasses = __webpack_require__(6); var EditorContainer = __webpack_require__(26); var ExcelColumn = __webpack_require__(15); var isFunction = __webpack_require__(30); var CellMetaDataShape = __webpack_require__(31); var SimpleCellFormatter = __webpack_require__(32); var Cell = React.createClass({ displayName: 'Cell', propTypes: { rowIdx: React.PropTypes.number.isRequired, idx: React.PropTypes.number.isRequired, selected: React.PropTypes.shape({ idx: React.PropTypes.number.isRequired }), selectedColumn: React.PropTypes.object, height: React.PropTypes.number, tabIndex: React.PropTypes.number, ref: React.PropTypes.string, column: React.PropTypes.shape(ExcelColumn).isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, isExpanded: React.PropTypes.bool, isRowSelected: React.PropTypes.bool, cellMetaData: React.PropTypes.shape(CellMetaDataShape).isRequired, handleDragStart: React.PropTypes.func, className: React.PropTypes.string, cellControls: React.PropTypes.any, rowData: React.PropTypes.object.isRequired }, getDefaultProps: function getDefaultProps() { return { tabIndex: -1, ref: 'cell', isExpanded: false }; }, getInitialState: function getInitialState() { return { isRowChanging: false, isCellValueChanging: false }; }, componentDidMount: function componentDidMount() { this.checkFocus(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { this.setState({ isRowChanging: this.props.rowData !== nextProps.rowData, isCellValueChanging: this.props.value !== nextProps.value }); }, componentDidUpdate: function componentDidUpdate() { this.checkFocus(); var dragged = this.props.cellMetaData.dragged; if (dragged && dragged.complete === true) { this.props.cellMetaData.handleTerminateDrag(); } if (this.state.isRowChanging && this.props.selectedColumn != null) { this.applyUpdateClass(); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.column.width !== nextProps.column.width || this.props.column.left !== nextProps.column.left || this.props.rowData !== nextProps.rowData || this.props.height !== nextProps.height || this.props.rowIdx !== nextProps.rowIdx || this.isCellSelectionChanging(nextProps) || this.isDraggedCellChanging(nextProps) || this.isCopyCellChanging(nextProps) || this.props.isRowSelected !== nextProps.isRowSelected || this.isSelected() || this.props.value !== nextProps.value; }, onCellClick: function onCellClick() { var meta = this.props.cellMetaData; if (meta != null && meta.onCellClick != null) { meta.onCellClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onCellDoubleClick: function onCellDoubleClick() { var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onCellDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx }); } }, onDragHandleDoubleClick: function onDragHandleDoubleClick(e) { e.stopPropagation(); var meta = this.props.cellMetaData; if (meta != null && meta.onCellDoubleClick != null) { meta.onDragHandleDoubleClick({ rowIdx: this.props.rowIdx, idx: this.props.idx, rowData: this.getRowData() }); } }, onDragOver: function onDragOver(e) { e.preventDefault(); }, getStyle: function getStyle() { var style = { position: 'absolute', width: this.props.column.width, height: this.props.height, left: this.props.column.left }; return style; }, getFormatter: function getFormatter() { var col = this.props.column; if (this.isActive()) { return React.createElement(EditorContainer, { rowData: this.getRowData(), rowIdx: this.props.rowIdx, idx: this.props.idx, cellMetaData: this.props.cellMetaData, column: col, height: this.props.height }); } return this.props.column.formatter; }, getRowData: function getRowData() { return this.props.rowData.toJSON ? this.props.rowData.toJSON() : this.props.rowData; }, getFormatterDependencies: function getFormatterDependencies() { // convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.getRowData(), this.props.column); } }, getCellClass: function getCellClass() { var className = joinClasses(this.props.column.cellClass, 'react-grid-Cell', this.props.className, this.props.column.locked ? 'react-grid-Cell--locked' : null); var extraClasses = joinClasses({ 'row-selected': this.props.isRowSelected, selected: this.isSelected() && !this.isActive(), editing: this.isActive(), copied: this.isCopied() || this.wasDraggedOver() || this.isDraggedOverUpwards() || this.isDraggedOverDownwards(), 'active-drag-cell': this.isSelected() || this.isDraggedOver(), 'is-dragged-over-up': this.isDraggedOverUpwards(), 'is-dragged-over-down': this.isDraggedOverDownwards(), 'was-dragged-over': this.wasDraggedOver() }); return joinClasses(className, extraClasses); }, getUpdateCellClass: function getUpdateCellClass() { return this.props.column.getUpdateCellClass ? this.props.column.getUpdateCellClass(this.props.selectedColumn, this.props.column, this.state.isCellValueChanging) : ''; }, isColumnSelected: function isColumnSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.idx === this.props.idx; }, isSelected: function isSelected() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return meta.selected && meta.selected.rowIdx === this.props.rowIdx && meta.selected.idx === this.props.idx; }, isActive: function isActive() { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } return this.isSelected() && meta.selected.active === true; }, isCellSelectionChanging: function isCellSelectionChanging(nextProps) { var meta = this.props.cellMetaData; if (meta == null || meta.selected == null) { return false; } var nextSelected = nextProps.cellMetaData.selected; if (meta.selected && nextSelected) { return this.props.idx === nextSelected.idx || this.props.idx === meta.selected.idx; } return true; }, applyUpdateClass: function applyUpdateClass() { var updateCellClass = this.getUpdateCellClass(); // -> removing the class if (updateCellClass != null && updateCellClass !== '') { var cellDOMNode = ReactDOM.findDOMNode(this); if (cellDOMNode.classList) { cellDOMNode.classList.remove(updateCellClass); // -> and re-adding the class cellDOMNode.classList.add(updateCellClass); } else if (cellDOMNode.className.indexOf(updateCellClass) === -1) { // IE9 doesn't support classList, nor (I think) altering element.className // without replacing it wholesale. cellDOMNode.className = cellDOMNode.className + ' ' + updateCellClass; } } }, setScrollLeft: function setScrollLeft(scrollLeft) { var ctrl = this; // flow on windows has an outdated react declaration, once that gets updated, we can remove this if (ctrl.isMounted()) { var node = ReactDOM.findDOMNode(this); var transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.webkitTransform = transform; node.style.transform = transform; } }, isCopied: function isCopied() { var copied = this.props.cellMetaData.copied; return copied && copied.rowIdx === this.props.rowIdx && copied.idx === this.props.idx; }, isDraggedOver: function isDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && dragged.overRowIdx === this.props.rowIdx && dragged.idx === this.props.idx; }, wasDraggedOver: function wasDraggedOver() { var dragged = this.props.cellMetaData.dragged; return dragged && (dragged.overRowIdx < this.props.rowIdx && this.props.rowIdx < dragged.rowIdx || dragged.overRowIdx > this.props.rowIdx && this.props.rowIdx > dragged.rowIdx) && dragged.idx === this.props.idx; }, isDraggedCellChanging: function isDraggedCellChanging(nextProps) { var isChanging = void 0; var dragged = this.props.cellMetaData.dragged; var nextDragged = nextProps.cellMetaData.dragged; if (dragged) { isChanging = nextDragged && this.props.idx === nextDragged.idx || dragged && this.props.idx === dragged.idx; return isChanging; } return false; }, isCopyCellChanging: function isCopyCellChanging(nextProps) { var isChanging = void 0; var copied = this.props.cellMetaData.copied; var nextCopied = nextProps.cellMetaData.copied; if (copied) { isChanging = nextCopied && this.props.idx === nextCopied.idx || copied && this.props.idx === copied.idx; return isChanging; } return false; }, isDraggedOverUpwards: function isDraggedOverUpwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx < dragged.rowIdx; }, isDraggedOverDownwards: function isDraggedOverDownwards() { var dragged = this.props.cellMetaData.dragged; return !this.isSelected() && this.isDraggedOver() && this.props.rowIdx > dragged.rowIdx; }, checkFocus: function checkFocus() { if (this.isSelected() && !this.isActive()) { // determine the parent viewport element of this cell var parentViewport = ReactDOM.findDOMNode(this); while (parentViewport != null && parentViewport.className.indexOf('react-grid-Viewport') === -1) { parentViewport = parentViewport.parentElement; } var focusInGrid = false; // if the focus is on the body of the document, the user won't mind if we focus them on a cell if (document.activeElement == null || document.activeElement.nodeName && typeof document.activeElement.nodeName === 'string' && document.activeElement.nodeName.toLowerCase() === 'body') { focusInGrid = true; // otherwise } else { // only pull focus if the currently focused element is contained within the viewport if (parentViewport) { var focusedParent = document.activeElement; while (focusedParent != null) { if (focusedParent === parentViewport) { focusInGrid = true; break; } focusedParent = focusedParent.parentElement; } } } if (focusInGrid) { ReactDOM.findDOMNode(this).focus(); } } }, canEdit: function canEdit() { return this.props.column.editor != null || this.props.column.editable; }, renderCellContent: function renderCellContent(props) { var CellContent = void 0; var Formatter = this.getFormatter(); if (React.isValidElement(Formatter)) { props.dependentValues = this.getFormatterDependencies(); CellContent = React.cloneElement(Formatter, props); } else if (isFunction(Formatter)) { CellContent = React.createElement(Formatter, { value: this.props.value, dependentValues: this.getFormatterDependencies() }); } else { CellContent = React.createElement(SimpleCellFormatter, { value: this.props.value }); } return React.createElement( 'div', { ref: 'cell', className: 'react-grid-Cell__value' }, CellContent, ' ', this.props.cellControls ); }, render: function render() { var style = this.getStyle(); var className = this.getCellClass(); var cellContent = this.renderCellContent({ value: this.props.value, column: this.props.column, rowIdx: this.props.rowIdx, isExpanded: this.props.isExpanded }); var dragHandle = !this.isActive() && this.canEdit() ? React.createElement( 'div', { className: 'drag-handle', draggable: 'true', onDoubleClick: this.onDragHandleDoubleClick }, React.createElement('span', { style: { display: 'none' } }) ) : null; return React.createElement( 'div', _extends({}, this.props, { className: className, style: style, onClick: this.onCellClick, onDoubleClick: this.onCellDoubleClick, onDragOver: this.onDragOver }), cellContent, dragHandle ); } }); module.exports = Cell; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var joinClasses = __webpack_require__(6); var keyboardHandlerMixin = __webpack_require__(27); var SimpleTextEditor = __webpack_require__(28); var isFunction = __webpack_require__(30); var EditorContainer = React.createClass({ displayName: 'EditorContainer', mixins: [keyboardHandlerMixin], propTypes: { rowIdx: React.PropTypes.number, rowData: React.PropTypes.object.isRequired, value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired, cellMetaData: React.PropTypes.shape({ selected: React.PropTypes.object.isRequired, copied: React.PropTypes.object, dragged: React.PropTypes.object, onCellClick: React.PropTypes.func, onCellDoubleClick: React.PropTypes.func, onCommitCancel: React.PropTypes.func, onCommit: React.PropTypes.func }).isRequired, column: React.PropTypes.object.isRequired, height: React.PropTypes.number.isRequired }, changeCommitted: false, getInitialState: function getInitialState() { return { isInvalid: false }; }, componentDidMount: function componentDidMount() { var inputNode = this.getInputNode(); if (inputNode !== undefined) { this.setTextInputFocus(); if (!this.getEditor().disableContainerStyles) { inputNode.className += ' editor-main'; inputNode.style.height = this.props.height - 1 + 'px'; } } }, componentWillUnmount: function componentWillUnmount() { if (!this.changeCommitted && !this.hasEscapeBeenPressed()) { this.commit({ key: 'Enter' }); } }, createEditor: function createEditor() { var _this = this; var editorRef = function editorRef(c) { return _this.editor = c; }; var editorProps = { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onCommit: this.commit, rowMetaData: this.getRowMetaData(), height: this.props.height, onBlur: this.commit, onOverrideKeyDown: this.onKeyDown }; var customEditor = this.props.column.editor; if (customEditor && React.isValidElement(customEditor)) { // return custom column editor or SimpleEditor if none specified return React.cloneElement(customEditor, editorProps); } return React.createElement(SimpleTextEditor, { ref: editorRef, column: this.props.column, value: this.getInitialValue(), onBlur: this.commit, rowMetaData: this.getRowMetaData(), onKeyDown: function onKeyDown() {}, commit: function commit() {} }); }, onPressEnter: function onPressEnter() { this.commit({ key: 'Enter' }); }, onPressTab: function onPressTab() { this.commit({ key: 'Tab' }); }, onPressEscape: function onPressEscape(e) { if (!this.editorIsSelectOpen()) { this.props.cellMetaData.onCommitCancel(); } else { // prevent event from bubbling if editor has results to select e.stopPropagation(); } }, onPressArrowDown: function onPressArrowDown(e) { if (this.editorHasResults()) { // dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowUp: function onPressArrowUp(e) { if (this.editorHasResults()) { // dont want to propogate as that then moves us round the grid e.stopPropagation(); } else { this.commit(e); } }, onPressArrowLeft: function onPressArrowLeft(e) { // prevent event propogation. this disables left cell navigation if (!this.isCaretAtBeginningOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, onPressArrowRight: function onPressArrowRight(e) { // prevent event propogation. this disables right cell navigation if (!this.isCaretAtEndOfInput()) { e.stopPropagation(); } else { this.commit(e); } }, editorHasResults: function editorHasResults() { if (isFunction(this.getEditor().hasResults)) { return this.getEditor().hasResults(); } return false; }, editorIsSelectOpen: function editorIsSelectOpen() { if (isFunction(this.getEditor().isSelectOpen)) { return this.getEditor().isSelectOpen(); } return false; }, getRowMetaData: function getRowMetaData() { // clone row data so editor cannot actually change this // convention based method to get corresponding Id or Name of any Name or Id property if (typeof this.props.column.getRowMetaData === 'function') { return this.props.column.getRowMetaData(this.props.rowData, this.props.column); } }, getEditor: function getEditor() { return this.editor; }, getInputNode: function getInputNode() { return this.getEditor().getInputNode(); }, getInitialValue: function getInitialValue() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; if (keyCode === 'Delete' || keyCode === 'Backspace') { return ''; } else if (keyCode === 'Enter') { return this.props.value; } var text = keyCode ? String.fromCharCode(keyCode) : this.props.value; return text; }, getContainerClass: function getContainerClass() { return joinClasses({ 'has-error': this.state.isInvalid === true }); }, commit: function commit(args) { var opts = args || {}; var updated = this.getEditor().getValue(); if (this.isNewValueValid(updated)) { this.changeCommitted = true; var cellKey = this.props.column.key; this.props.cellMetaData.onCommit({ cellKey: cellKey, rowIdx: this.props.rowIdx, updated: updated, key: opts.key }); } }, isNewValueValid: function isNewValueValid(value) { if (isFunction(this.getEditor().validate)) { var isValid = this.getEditor().validate(value); this.setState({ isInvalid: !isValid }); return isValid; } return true; }, setCaretAtEndOfInput: function setCaretAtEndOfInput() { var input = this.getInputNode(); // taken from http://stackoverflow.com/questions/511088/use-javascript-to-place-cursor-at-end-of-text-in-text-input-element var txtLength = input.value.length; if (input.setSelectionRange) { input.setSelectionRange(txtLength, txtLength); } else if (input.createTextRange) { var fieldRange = input.createTextRange(); fieldRange.moveStart('character', txtLength); fieldRange.collapse(); fieldRange.select(); } }, isCaretAtBeginningOfInput: function isCaretAtBeginningOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.selectionEnd && inputNode.selectionStart === 0; }, isCaretAtEndOfInput: function isCaretAtEndOfInput() { var inputNode = this.getInputNode(); return inputNode.selectionStart === inputNode.value.length; }, setTextInputFocus: function setTextInputFocus() { var selected = this.props.cellMetaData.selected; var keyCode = selected.initialKeyCode; var inputNode = this.getInputNode(); inputNode.focus(); if (inputNode.tagName === 'INPUT') { if (!this.isKeyPrintable(keyCode)) { inputNode.focus(); inputNode.select(); } else { inputNode.select(); } } }, hasEscapeBeenPressed: function hasEscapeBeenPressed() { var pressed = false; var escapeKey = 27; if (window.event) { if (window.event.keyCode === escapeKey) { pressed = true; } else if (window.event.which === escapeKey) { pressed = true; } } return pressed; }, renderStatusIcon: function renderStatusIcon() { if (this.state.isInvalid === true) { return React.createElement('span', { className: 'glyphicon glyphicon-remove form-control-feedback' }); } }, render: function render() { return React.createElement( 'div', { className: this.getContainerClass(), onKeyDown: this.onKeyDown, commit: this.commit }, this.createEditor(), this.renderStatusIcon() ); } }); module.exports = EditorContainer; /***/ }, /* 27 */ /***/ function(module, exports) { 'use strict'; var KeyboardHandlerMixin = { onKeyDown: function onKeyDown(e) { if (this.isCtrlKeyHeldDown(e)) { this.checkAndCall('onPressKeyWithCtrl', e); } else if (this.isKeyExplicitlyHandled(e.key)) { // break up individual keyPress events to have their own specific callbacks // this allows multiple mixins to listen to onKeyDown events and somewhat reduces methodName clashing var callBack = 'onPress' + e.key; this.checkAndCall(callBack, e); } else if (this.isKeyPrintable(e.keyCode)) { this.checkAndCall('onPressChar', e); } }, // taken from http://stackoverflow.com/questions/12467240/determine-if-javascript-e-keycode-is-a-printable-non-control-character isKeyPrintable: function isKeyPrintable(keycode) { var valid = keycode > 47 && keycode < 58 || // number keys keycode === 32 || keycode === 13 || // spacebar & return key(s) (if you want to allow carriage returns) keycode > 64 && keycode < 91 || // letter keys keycode > 95 && keycode < 112 || // numpad keys keycode > 185 && keycode < 193 || // ;=,-./` (in order) keycode > 218 && keycode < 223; // [\]' (in order) return valid; }, isKeyExplicitlyHandled: function isKeyExplicitlyHandled(key) { return typeof this['onPress' + key] === 'function'; }, isCtrlKeyHeldDown: function isCtrlKeyHeldDown(e) { return e.ctrlKey === true && e.key !== 'Control'; }, checkAndCall: function checkAndCall(methodName, args) { if (typeof this[methodName] === 'function') { this[methodName](args); } } }; module.exports = KeyboardHandlerMixin; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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 _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 React = __webpack_require__(2); var EditorBase = __webpack_require__(29); var SimpleTextEditor = function (_EditorBase) { _inherits(SimpleTextEditor, _EditorBase); function SimpleTextEditor() { _classCallCheck(this, SimpleTextEditor); return _possibleConstructorReturn(this, Object.getPrototypeOf(SimpleTextEditor).apply(this, arguments)); } _createClass(SimpleTextEditor, [{ key: 'render', value: function render() { return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value }); } }]); return SimpleTextEditor; }(EditorBase); module.exports = SimpleTextEditor; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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 _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 React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var ExcelColumn = __webpack_require__(15); var EditorBase = function (_React$Component) { _inherits(EditorBase, _React$Component); function EditorBase() { _classCallCheck(this, EditorBase); return _possibleConstructorReturn(this, Object.getPrototypeOf(EditorBase).apply(this, arguments)); } _createClass(EditorBase, [{ key: 'getStyle', value: function getStyle() { return { width: '100%' }; } }, { key: 'getValue', value: function getValue() { var updated = {}; updated[this.props.column.key] = this.getInputNode().value; return updated; } }, { key: 'getInputNode', value: function getInputNode() { var domNode = ReactDOM.findDOMNode(this); if (domNode.tagName === 'INPUT') { return domNode; } return domNode.querySelector('input:not([type=hidden])'); } }, { key: 'inheritContainerStyles', value: function inheritContainerStyles() { return true; } }]); return EditorBase; }(React.Component); EditorBase.propTypes = { onKeyDown: React.PropTypes.func.isRequired, value: React.PropTypes.any.isRequired, onBlur: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired, commit: React.PropTypes.func.isRequired }; module.exports = EditorBase; /***/ }, /* 30 */ /***/ function(module, exports) { 'use strict'; var isFunction = function isFunction(functionToCheck) { var getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; }; module.exports = isFunction; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var PropTypes = __webpack_require__(2).PropTypes; module.exports = { selected: PropTypes.object.isRequired, copied: PropTypes.object, dragged: PropTypes.object, onCellClick: PropTypes.func.isRequired, onCellDoubleClick: PropTypes.func.isRequired, onCommit: PropTypes.func.isRequired, onCommitCancel: PropTypes.func.isRequired, handleDragEnterRow: PropTypes.func.isRequired, handleTerminateDrag: PropTypes.func.isRequired }; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var SimpleCellFormatter = React.createClass({ displayName: 'SimpleCellFormatter', propTypes: { value: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number, React.PropTypes.object, React.PropTypes.bool]).isRequired }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value; }, render: function render() { return React.createElement( 'div', { title: this.props.value }, this.props.value ); } }); module.exports = SimpleCellFormatter; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var DOMMetrics = __webpack_require__(34); var min = Math.min; var max = Math.max; var floor = Math.floor; var ceil = Math.ceil; module.exports = { mixins: [DOMMetrics.MetricsMixin], DOMMetrics: { viewportHeight: function viewportHeight() { return ReactDOM.findDOMNode(this).offsetHeight; } }, propTypes: { rowHeight: React.PropTypes.number, rowsCount: React.PropTypes.number.isRequired }, getDefaultProps: function getDefaultProps() { return { rowHeight: 30 }; }, getInitialState: function getInitialState() { return this.getGridState(this.props); }, getGridState: function getGridState(props) { var renderedRowsCount = ceil((props.minHeight - props.rowHeight) / props.rowHeight); var totalRowCount = min(renderedRowsCount * 2, props.rowsCount); return { displayStart: 0, displayEnd: totalRowCount, height: props.minHeight, scrollTop: 0, scrollLeft: 0 }; }, updateScroll: function updateScroll(scrollTop, scrollLeft, height, rowHeight, length) { var renderedRowsCount = ceil(height / rowHeight); var visibleStart = floor(scrollTop / rowHeight); var visibleEnd = min(visibleStart + renderedRowsCount, length); var displayStart = max(0, visibleStart - renderedRowsCount * 2); var displayEnd = min(visibleStart + renderedRowsCount * 2, length); var nextScrollState = { visibleStart: visibleStart, visibleEnd: visibleEnd, displayStart: displayStart, displayEnd: displayEnd, height: height, scrollTop: scrollTop, scrollLeft: scrollLeft }; this.setState(nextScrollState); }, metricsUpdated: function metricsUpdated() { var height = this.DOMMetrics.viewportHeight(); if (height) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, height, this.props.rowHeight, this.props.rowsCount); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.rowHeight !== nextProps.rowHeight || this.props.minHeight !== nextProps.minHeight) { this.setState(this.getGridState(nextProps)); } else if (this.props.rowsCount !== nextProps.rowsCount) { this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height, nextProps.rowHeight, nextProps.rowsCount); // Added to fix the hiding of the bottom scrollbar when showing the filters. } else if (this.props.rowOffsetHeight !== nextProps.rowOffsetHeight) { // The value of height can be positive or negative and will be added to the current height to cater for changes in the header height (due to the filer) var _height = this.props.rowOffsetHeight - nextProps.rowOffsetHeight; this.updateScroll(this.state.scrollTop, this.state.scrollLeft, this.state.height + _height, nextProps.rowHeight, nextProps.rowsCount); } } }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var shallowCloneObject = __webpack_require__(7); var contextTypes = { metricsComputator: React.PropTypes.object }; var MetricsComputatorMixin = { childContextTypes: contextTypes, getChildContext: function getChildContext() { return { metricsComputator: this }; }, getMetricImpl: function getMetricImpl(name) { return this._DOMMetrics.metrics[name].value; }, registerMetricsImpl: function registerMetricsImpl(component, metrics) { var getters = {}; var s = this._DOMMetrics; for (var name in metrics) { if (s.metrics[name] !== undefined) { throw new Error('DOM metric ' + name + ' is already defined'); } s.metrics[name] = { component: component, computator: metrics[name].bind(component) }; getters[name] = this.getMetricImpl.bind(null, name); } if (s.components.indexOf(component) === -1) { s.components.push(component); } return getters; }, unregisterMetricsFor: function unregisterMetricsFor(component) { var s = this._DOMMetrics; var idx = s.components.indexOf(component); if (idx > -1) { s.components.splice(idx, 1); var name = void 0; var metricsToDelete = {}; for (name in s.metrics) { if (s.metrics[name].component === component) { metricsToDelete[name] = true; } } for (name in metricsToDelete) { if (metricsToDelete.hasOwnProperty(name)) { delete s.metrics[name]; } } } }, updateMetrics: function updateMetrics() { var s = this._DOMMetrics; var needUpdate = false; for (var name in s.metrics) { if (!s.metrics.hasOwnProperty(name)) continue; var newMetric = s.metrics[name].computator(); if (newMetric !== s.metrics[name].value) { needUpdate = true; } s.metrics[name].value = newMetric; } if (needUpdate) { for (var i = 0, len = s.components.length; i < len; i++) { if (s.components[i].metricsUpdated) { s.components[i].metricsUpdated(); } } } }, componentWillMount: function componentWillMount() { this._DOMMetrics = { metrics: {}, components: [] }; }, componentDidMount: function componentDidMount() { if (window.addEventListener) { window.addEventListener('resize', this.updateMetrics); } else { window.attachEvent('resize', this.updateMetrics); } this.updateMetrics(); }, componentWillUnmount: function componentWillUnmount() { window.removeEventListener('resize', this.updateMetrics); } }; var MetricsMixin = { contextTypes: contextTypes, componentWillMount: function componentWillMount() { if (this.DOMMetrics) { this._DOMMetricsDefs = shallowCloneObject(this.DOMMetrics); this.DOMMetrics = {}; for (var name in this._DOMMetricsDefs) { if (!this._DOMMetricsDefs.hasOwnProperty(name)) continue; this.DOMMetrics[name] = function () {}; } } }, componentDidMount: function componentDidMount() { if (this.DOMMetrics) { this.DOMMetrics = this.registerMetrics(this._DOMMetricsDefs); } }, componentWillUnmount: function componentWillUnmount() { if (!this.registerMetricsImpl) { return this.context.metricsComputator.unregisterMetricsFor(this); } if (this.hasOwnProperty('DOMMetrics')) { delete this.DOMMetrics; } }, registerMetrics: function registerMetrics(metrics) { if (this.registerMetricsImpl) { return this.registerMetricsImpl(this, metrics); } return this.context.metricsComputator.registerMetricsImpl(this, metrics); }, getMetric: function getMetric(name) { if (this.getMetricImpl) { return this.getMetricImpl(name); } return this.context.metricsComputator.getMetricImpl(name); } }; module.exports = { MetricsComputatorMixin: MetricsComputatorMixin, MetricsMixin: MetricsMixin }; /***/ }, /* 35 */ /***/ function(module, exports) { "use strict"; module.exports = { componentDidMount: function componentDidMount() { this._scrollLeft = this.refs.viewport ? this.refs.viewport.getScroll().scrollLeft : 0; this._onScroll(); }, componentDidUpdate: function componentDidUpdate() { this._onScroll(); }, componentWillMount: function componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount: function componentWillUnmount() { this._scrollLeft = undefined; }, onScroll: function onScroll(props) { if (this._scrollLeft !== props.scrollLeft) { this._scrollLeft = props.scrollLeft; this._onScroll(); } }, onHeaderScroll: function onHeaderScroll(e) { var scrollLeft = e.target.scrollLeft; if (this._scrollLeft !== scrollLeft) { this._scrollLeft = scrollLeft; this.refs.header.setScrollLeft(scrollLeft); var canvas = ReactDOM.findDOMNode(this.refs.viewport.refs.canvas); canvas.scrollLeft = scrollLeft; this.refs.viewport.refs.canvas.setScrollLeft(scrollLeft); } }, _onScroll: function _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); if (this.refs.viewport) { this.refs.viewport.setScrollLeft(this._scrollLeft); } } } }; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var CheckboxEditor = React.createClass({ displayName: 'CheckboxEditor', propTypes: { value: React.PropTypes.bool, rowIdx: React.PropTypes.number, column: React.PropTypes.shape({ key: React.PropTypes.string, onCellChange: React.PropTypes.func }), dependentValues: React.PropTypes.object }, handleChange: function handleChange(e) { this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e); }, render: function render() { var checked = this.props.value != null ? this.props.value : false; var checkboxName = 'checkbox' + this.props.rowIdx; return React.createElement( 'div', { className: 'react-grid-checkbox-container', onClick: this.handleChange }, React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }), React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' }) ); } }); module.exports = CheckboxEditor; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); 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 ColumnMetrics = __webpack_require__(8); var DOMMetrics = __webpack_require__(34); Object.assign = __webpack_require__(38); var PropTypes = __webpack_require__(2).PropTypes; var ColumnUtils = __webpack_require__(10); var Column = function Column() { _classCallCheck(this, Column); }; module.exports = { mixins: [DOMMetrics.MetricsMixin], propTypes: { columns: PropTypes.arrayOf(Column), minColumnWidth: PropTypes.number, columnEquality: PropTypes.func }, DOMMetrics: { gridWidth: function gridWidth() { return _reactDom2['default'].findDOMNode(this).parentElement.offsetWidth; } }, getDefaultProps: function getDefaultProps() { return { minColumnWidth: 80, columnEquality: ColumnMetrics.sameColumn }; }, componentWillMount: function componentWillMount() { this._mounted = true; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.columns) { if (!ColumnMetrics.sameColumns(this.props.columns, nextProps.columns, this.props.columnEquality) || nextProps.minWidth !== this.props.minWidth) { var columnMetrics = this.createColumnMetrics(nextProps); this.setState({ columnMetrics: columnMetrics }); } } }, getTotalWidth: function getTotalWidth() { var totalWidth = 0; if (this._mounted) { totalWidth = this.DOMMetrics.gridWidth(); } else { totalWidth = ColumnUtils.getSize(this.props.columns) * this.props.minColumnWidth; } return totalWidth; }, getColumnMetricsType: function getColumnMetricsType(metrics) { var totalWidth = metrics.totalWidth || this.getTotalWidth(); var currentMetrics = { columns: metrics.columns, totalWidth: totalWidth, minColumnWidth: metrics.minColumnWidth }; var updatedMetrics = ColumnMetrics.recalculate(currentMetrics); return updatedMetrics; }, getColumn: function getColumn(idx) { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, getSize: function getSize() { var columns = this.state.columnMetrics.columns; if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } }, metricsUpdated: function metricsUpdated() { var columnMetrics = this.createColumnMetrics(); this.setState({ columnMetrics: columnMetrics }); }, createColumnMetrics: function createColumnMetrics() { var props = arguments.length <= 0 || arguments[0] === undefined ? this.props : arguments[0]; var gridColumns = this.setupGridColumns(props); return this.getColumnMetricsType({ columns: gridColumns, minColumnWidth: this.props.minColumnWidth, totalWidth: props.minWidth }); }, onColumnResize: function onColumnResize(index, width) { var columnMetrics = ColumnMetrics.resizeColumn(this.state.columnMetrics, index, width); this.setState({ columnMetrics: columnMetrics }); } }; /***/ }, /* 38 */ /***/ function(module, exports) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 39 */ /***/ function(module, exports) { 'use strict'; var RowUtils = { get: function get(row, property) { if (typeof row.get === 'function') { return row.get(property); } return row[property]; } }; module.exports = RowUtils; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Editors = { AutoComplete: __webpack_require__(41), DropDownEditor: __webpack_require__(43), SimpleTextEditor: __webpack_require__(28), CheckboxEditor: __webpack_require__(36) }; module.exports = Editors; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var ReactDOM = __webpack_require__(3); var ReactAutocomplete = __webpack_require__(42); var ExcelColumn = __webpack_require__(15); var optionPropType = React.PropTypes.shape({ id: React.PropTypes.required, title: React.PropTypes.string }); var AutoCompleteEditor = React.createClass({ displayName: 'AutoCompleteEditor', propTypes: { onCommit: React.PropTypes.func, options: React.PropTypes.arrayOf(optionPropType), label: React.PropTypes.any, value: React.PropTypes.any, height: React.PropTypes.number, valueParams: React.PropTypes.arrayOf(React.PropTypes.string), column: React.PropTypes.shape(ExcelColumn), resultIdentifier: React.PropTypes.string, search: React.PropTypes.string, onKeyDown: React.PropTypes.func, onFocus: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { resultIdentifier: 'id' }; }, handleChange: function handleChange() { this.props.onCommit(); }, getValue: function getValue() { var value = void 0; var updated = {}; if (this.hasResults() && this.isFocusedOnSuggestion()) { value = this.getLabel(this.refs.autoComplete.state.focusedValue); if (this.props.valueParams) { value = this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue, this.props.valueParams); } } else { value = this.refs.autoComplete.state.searchTerm; } updated[this.props.column.key] = value; return updated; }, getInputNode: function getInputNode() { return ReactDOM.findDOMNode(this).getElementsByTagName('input')[0]; }, getLabel: function getLabel(item) { var label = this.props.label != null ? this.props.label : 'title'; if (typeof label === 'function') { return label(item); } else if (typeof label === 'string') { return item[label]; } }, hasResults: function hasResults() { return this.refs.autoComplete.state.results.length > 0; }, isFocusedOnSuggestion: function isFocusedOnSuggestion() { var autoComplete = this.refs.autoComplete; return autoComplete.state.focusedValue != null; }, constuctValueFromParams: function constuctValueFromParams(obj, props) { if (!props) { return ''; } var ret = []; for (var i = 0, ii = props.length; i < ii; i++) { ret.push(obj[props[i]]); } return ret.join('|'); }, render: function render() { var label = this.props.label != null ? this.props.label : 'title'; return React.createElement( 'div', { height: this.props.height, onKeyDown: this.props.onKeyDown }, React.createElement(ReactAutocomplete, { search: this.props.search, ref: 'autoComplete', label: label, onChange: this.handleChange, onFocus: this.props.onFocus, resultIdentifier: this.props.resultIdentifier, options: this.props.options, value: { title: this.props.value } }) ); } }); module.exports = AutoCompleteEditor; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__webpack_require__(2)); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactAutocomplete"] = factory(require("react")); else root["ReactAutocomplete"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { 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"; var React = __webpack_require__(1); var joinClasses = __webpack_require__(2); var Autocomplete = React.createClass({ displayName: "Autocomplete", propTypes: { options: React.PropTypes.any, search: React.PropTypes.func, resultRenderer: React.PropTypes.oneOfType([React.PropTypes.component, React.PropTypes.func]), value: React.PropTypes.object, onChange: React.PropTypes.func, onError: React.PropTypes.func, onFocus: React.PropTypes.func }, getDefaultProps: function () { return { search: searchArray }; }, getInitialState: function () { var searchTerm = this.props.searchTerm ? this.props.searchTerm : this.props.value ? this.props.value.title : ""; return { results: [], showResults: false, showResultsInProgress: false, searchTerm: searchTerm, focusedValue: null }; }, getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var className = joinClasses(this.props.className, "react-autocomplete-Autocomplete", this.state.showResults ? "react-autocomplete-Autocomplete--resultsShown" : undefined); var style = { position: "relative", outline: "none" }; return React.createElement("div", { tabIndex: "1", className: className, onFocus: this.onFocus, onBlur: this.onBlur, style: style }, React.createElement("input", { ref: "search", className: "react-autocomplete-Autocomplete__search", style: { width: "100%" }, onClick: this.showAllResults, onChange: this.onQueryChange, onFocus: this.onSearchInputFocus, onBlur: this.onQueryBlur, onKeyDown: this.onQueryKeyDown, value: this.state.searchTerm }), React.createElement(Results, { className: "react-autocomplete-Autocomplete__results", onSelect: this.onValueChange, onFocus: this.onValueFocus, results: this.state.results, focusedValue: this.state.focusedValue, show: this.state.showResults, renderer: this.props.resultRenderer, label: this.props.label, resultIdentifier: this.props.resultIdentifier })); }, componentWillReceiveProps: function (nextProps) { var searchTerm = nextProps.searchTerm ? nextProps.searchTerm : nextProps.value ? nextProps.value.title : ""; this.setState({ searchTerm: searchTerm }); }, componentWillMount: function () { this.blurTimer = null; }, /** * Show results for a search term value. * * This method doesn't update search term value itself. * * @param {Search} searchTerm */ showResults: function (searchTerm) { this.setState({ showResultsInProgress: true }); this.props.search(this.props.options, searchTerm.trim(), this.onSearchComplete); }, showAllResults: function () { if (!this.state.showResultsInProgress && !this.state.showResults) { this.showResults(""); } }, onValueChange: function (value) { var state = { value: value, showResults: false }; if (value) { state.searchTerm = value.title; } this.setState(state); if (this.props.onChange) { this.props.onChange(value); } }, onSearchComplete: function (err, results) { if (err) { if (this.props.onError) { this.props.onError(err); } else { throw err; } } this.setState({ showResultsInProgress: false, showResults: true, results: results }); }, onValueFocus: function (value) { this.setState({ focusedValue: value }); }, onQueryChange: function (e) { var searchTerm = e.target.value; this.setState({ searchTerm: searchTerm, focusedValue: null }); this.showResults(searchTerm); }, onFocus: function () { if (this.blurTimer) { clearTimeout(this.blurTimer); this.blurTimer = null; } this.refs.search.getDOMNode().focus(); }, onSearchInputFocus: function () { if (this.props.onFocus) { this.props.onFocus(); } this.showAllResults(); }, onBlur: function () { // wrap in setTimeout so we can catch a click on results this.blurTimer = setTimeout((function () { if (this.isMounted()) { this.setState({ showResults: false }); } }).bind(this), 100); }, onQueryKeyDown: function (e) { if (e.key === "Enter") { e.preventDefault(); if (this.state.focusedValue) { this.onValueChange(this.state.focusedValue); } } else if (e.key === "ArrowUp" && this.state.showResults) { e.preventDefault(); var prevIdx = Math.max(this.focusedValueIndex() - 1, 0); this.setState({ focusedValue: this.state.results[prevIdx] }); } else if (e.key === "ArrowDown") { e.preventDefault(); if (this.state.showResults) { var nextIdx = Math.min(this.focusedValueIndex() + (this.state.showResults ? 1 : 0), this.state.results.length - 1); this.setState({ showResults: true, focusedValue: this.state.results[nextIdx] }); } else { this.showAllResults(); } } }, focusedValueIndex: function () { if (!this.state.focusedValue) { return -1; } for (var i = 0, len = this.state.results.length; i < len; i++) { if (this.getResultIdentifier(this.state.results[i]) === this.getResultIdentifier(this.state.focusedValue)) { return i; } } return -1; } }); var Results = React.createClass({ displayName: "Results", getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { if (!result.id) { throw "id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component"; } return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var style = { display: this.props.show ? "block" : "none", position: "absolute", listStyleType: "none" }; var $__0 = this.props, className = $__0.className, props = (function (source, exclusion) { var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) { throw new TypeError(); }for (var key in source) { if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) { rest[key] = source[key]; } }return rest; })($__0, { className: 1 }); return React.createElement("ul", React.__spread({}, props, { style: style, className: className + " react-autocomplete-Results" }), this.props.results.map(this.renderResult)); }, renderResult: function (result) { var focused = this.props.focusedValue && this.getResultIdentifier(this.props.focusedValue) === this.getResultIdentifier(result); var Renderer = this.props.renderer || Result; return React.createElement(Renderer, { ref: focused ? "focused" : undefined, key: this.getResultIdentifier(result), result: result, focused: focused, onMouseEnter: this.onMouseEnterResult, onClick: this.props.onSelect, label: this.props.label }); }, componentDidUpdate: function () { this.scrollToFocused(); }, componentDidMount: function () { this.scrollToFocused(); }, componentWillMount: function () { this.ignoreFocus = false; }, scrollToFocused: function () { var focused = this.refs && this.refs.focused; if (focused) { var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = focused.getDOMNode(); var top = node.offsetTop; var bottom = top + node.offsetHeight; // we update ignoreFocus to true if we change the scroll position so // the mouseover event triggered because of that won't have an // effect if (top < scroll) { this.ignoreFocus = true; containerNode.scrollTop = top; } else if (bottom - scroll > height) { this.ignoreFocus = true; containerNode.scrollTop = bottom - height; } } }, onMouseEnterResult: function (e, result) { // check if we need to prevent the next onFocus event because it was // probably caused by a mouseover due to scroll position change if (this.ignoreFocus) { this.ignoreFocus = false; } else { // we need to make sure focused node is visible // for some reason mouse events fire on visible nodes due to // box-shadow var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = e.target; var top = node.offsetTop; var bottom = top + node.offsetHeight; if (bottom > scroll && top < scroll + height) { this.props.onFocus(result); } } } }); var Result = React.createClass({ displayName: "Result", getDefaultProps: function () { return { label: function (result) { return result.title; } }; }, getLabel: function (result) { if (typeof this.props.label === "function") { return this.props.label(result); } else if (typeof this.props.label === "string") { return result[this.props.label]; } }, render: function () { var className = joinClasses({ "react-autocomplete-Result": true, "react-autocomplete-Result--active": this.props.focused }); return React.createElement("li", { style: { listStyleType: "none" }, className: className, onClick: this.onClick, onMouseEnter: this.onMouseEnter }, React.createElement("a", null, this.getLabel(this.props.result))); }, onClick: function () { this.props.onClick(this.props.result); }, onMouseEnter: function (e) { if (this.props.onMouseEnter) { this.props.onMouseEnter(e, this.props.result); } }, shouldComponentUpdate: function (nextProps) { return nextProps.result.id !== this.props.result.id || nextProps.focused !== this.props.focused; } }); /** * Search options using specified search term treating options as an array * of candidates. * * @param {Array.<Object>} options * @param {String} searchTerm * @param {Callback} cb */ function searchArray(options, searchTerm, cb) { if (!options) { return cb(null, []); } searchTerm = new RegExp(searchTerm, "i"); var results = []; for (var i = 0, len = options.length; i < len; i++) { if (searchTerm.exec(options[i].title)) { results.push(options[i]); } } cb(null, results); } module.exports = Autocomplete; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__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__)); } /***/ } /******/ ]) }); ; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; 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 _reactDom = __webpack_require__(3); var _reactDom2 = _interopRequireDefault(_reactDom); 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 _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 React = __webpack_require__(2); var EditorBase = __webpack_require__(29); var DropDownEditor = function (_EditorBase) { _inherits(DropDownEditor, _EditorBase); function DropDownEditor() { _classCallCheck(this, DropDownEditor); return _possibleConstructorReturn(this, Object.getPrototypeOf(DropDownEditor).apply(this, arguments)); } _createClass(DropDownEditor, [{ key: 'getInputNode', value: function getInputNode() { return _reactDom2['default'].findDOMNode(this); } }, { key: 'onClick', value: function onClick() { this.getInputNode().focus(); } }, { key: 'onDoubleClick', value: function onDoubleClick() { this.getInputNode().focus(); } }, { key: 'render', value: function render() { return React.createElement( 'select', { style: this.getStyle(), defaultValue: this.props.value, onBlur: this.props.onBlur, onChange: this.onChange }, this.renderOptions() ); } }, { key: 'renderOptions', value: function renderOptions() { var options = []; this.props.options.forEach(function (name) { if (typeof name === 'string') { options.push(React.createElement( 'option', { key: name, value: name }, name )); } else { options.push(React.createElement( 'option', { key: name.id, value: name.value, title: name.title }, name.value )); } }, this); return options; } }]); return DropDownEditor; }(EditorBase); DropDownEditor.propTypes = { options: React.PropTypes.arrayOf(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.objectOf({ id: React.PropTypes.string, title: React.PropTypes.string, meta: React.PropTypes.string })])).isRequired }; module.exports = DropDownEditor; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // not including this // it currently requires the whole of moment, which we dont want to take as a dependency var ImageFormatter = __webpack_require__(45); var Formatters = { ImageFormatter: ImageFormatter }; module.exports = Formatters; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(2); var PendingPool = {}; var ReadyPool = {}; var ImageFormatter = React.createClass({ displayName: 'ImageFormatter', propTypes: { value: React.PropTypes.string.isRequired }, getInitialState: function getInitialState() { return { ready: false }; }, componentWillMount: function componentWillMount() { this._load(this.props.value); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState({ value: null }); this._load(nextProps.value); } }, _load: function _load(src) { var imageSrc = src; if (ReadyPool[imageSrc]) { this.setState({ value: imageSrc }); return; } if (PendingPool[imageSrc]) { PendingPool[imageSrc].push(this._onLoad); return; } PendingPool[imageSrc] = [this._onLoad]; var img = new Image(); img.onload = function () { PendingPool[imageSrc].forEach(function (callback) { callback(imageSrc); }); delete PendingPool[imageSrc]; img.onload = null; imageSrc = undefined; }; img.src = imageSrc; }, _onLoad: function _onLoad(src) { if (this.isMounted() && src === this.props.value) { this.setState({ value: src }); } }, render: function render() { var style = this.state.value ? { backgroundImage: 'url(' + this.state.value + ')' } : undefined; return React.createElement('div', { className: 'react-grid-image', style: style }); } }); module.exports = ImageFormatter; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(2); var Toolbar = React.createClass({ displayName: "Toolbar", propTypes: { onAddRow: React.PropTypes.func, onToggleFilter: React.PropTypes.func, enableFilter: React.PropTypes.bool, numberOfRows: React.PropTypes.number }, onAddRow: function onAddRow() { if (this.props.onAddRow !== null && this.props.onAddRow instanceof Function) { this.props.onAddRow({ newRowIndex: this.props.numberOfRows }); } }, getDefaultProps: function getDefaultProps() { return { enableAddRow: true }; }, renderAddRowButton: function renderAddRowButton() { if (this.props.onAddRow) { return React.createElement( "button", { type: "button", className: "btn", onClick: this.onAddRow }, "Add Row" ); } }, renderToggleFilterButton: function renderToggleFilterButton() { if (this.props.enableFilter) { return React.createElement( "button", { type: "button", className: "btn", onClick: this.props.onToggleFilter }, "Filter Rows" ); } }, render: function render() { return React.createElement( "div", { className: "react-grid-Toolbar" }, React.createElement( "div", { className: "tools" }, this.renderAddRowButton(), this.renderToggleFilterButton() ) ); } }); module.exports = Toolbar; /***/ } /******/ ]) }); ;
ajax/libs/react-bootstrap/0.23.0/react-bootstrap.js
dhenson02/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactBootstrap"] = factory(require("react")); else root["ReactBootstrap"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__) { 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 _Accordion = __webpack_require__(1); var _Accordion2 = _interopRequireDefault(_Accordion); var _Affix = __webpack_require__(9); var _Affix2 = _interopRequireDefault(_Affix); var _AffixMixin = __webpack_require__(10); var _AffixMixin2 = _interopRequireDefault(_AffixMixin); var _Alert = __webpack_require__(13); var _Alert2 = _interopRequireDefault(_Alert); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _Badge = __webpack_require__(14); var _Badge2 = _interopRequireDefault(_Badge); var _Button = __webpack_require__(15); var _Button2 = _interopRequireDefault(_Button); var _ButtonGroup = __webpack_require__(16); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _ButtonInput = __webpack_require__(17); var _ButtonInput2 = _interopRequireDefault(_ButtonInput); var _ButtonToolbar = __webpack_require__(21); var _ButtonToolbar2 = _interopRequireDefault(_ButtonToolbar); var _CollapsibleNav = __webpack_require__(22); var _CollapsibleNav2 = _interopRequireDefault(_CollapsibleNav); var _Carousel = __webpack_require__(26); var _Carousel2 = _interopRequireDefault(_Carousel); var _CarouselItem = __webpack_require__(27); var _CarouselItem2 = _interopRequireDefault(_CarouselItem); var _Col = __webpack_require__(28); var _Col2 = _interopRequireDefault(_Col); var _CollapsibleMixin = __webpack_require__(23); var _CollapsibleMixin2 = _interopRequireDefault(_CollapsibleMixin); var _DropdownButton = __webpack_require__(29); var _DropdownButton2 = _interopRequireDefault(_DropdownButton); var _DropdownMenu = __webpack_require__(31); var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu); var _DropdownStateMixin = __webpack_require__(30); var _DropdownStateMixin2 = _interopRequireDefault(_DropdownStateMixin); var _FadeMixin = __webpack_require__(32); var _FadeMixin2 = _interopRequireDefault(_FadeMixin); var _FormControls = __webpack_require__(33); var _FormControls2 = _interopRequireDefault(_FormControls); var _Glyphicon = __webpack_require__(35); var _Glyphicon2 = _interopRequireDefault(_Glyphicon); var _Grid = __webpack_require__(36); var _Grid2 = _interopRequireDefault(_Grid); var _Input = __webpack_require__(37); var _Input2 = _interopRequireDefault(_Input); var _Interpolate = __webpack_require__(39); var _Interpolate2 = _interopRequireDefault(_Interpolate); var _Jumbotron = __webpack_require__(41); var _Jumbotron2 = _interopRequireDefault(_Jumbotron); var _Label = __webpack_require__(42); var _Label2 = _interopRequireDefault(_Label); var _ListGroup = __webpack_require__(43); var _ListGroup2 = _interopRequireDefault(_ListGroup); var _ListGroupItem = __webpack_require__(44); var _ListGroupItem2 = _interopRequireDefault(_ListGroupItem); var _MenuItem = __webpack_require__(45); var _MenuItem2 = _interopRequireDefault(_MenuItem); var _Modal = __webpack_require__(46); var _Modal2 = _interopRequireDefault(_Modal); var _Nav = __webpack_require__(47); var _Nav2 = _interopRequireDefault(_Nav); var _Navbar = __webpack_require__(48); var _Navbar2 = _interopRequireDefault(_Navbar); var _NavItem = __webpack_require__(49); var _NavItem2 = _interopRequireDefault(_NavItem); var _ModalTrigger = __webpack_require__(50); var _ModalTrigger2 = _interopRequireDefault(_ModalTrigger); var _OverlayTrigger = __webpack_require__(53); var _OverlayTrigger2 = _interopRequireDefault(_OverlayTrigger); var _OverlayMixin = __webpack_require__(51); var _OverlayMixin2 = _interopRequireDefault(_OverlayMixin); var _PageHeader = __webpack_require__(55); var _PageHeader2 = _interopRequireDefault(_PageHeader); var _Panel = __webpack_require__(56); var _Panel2 = _interopRequireDefault(_Panel); var _PanelGroup = __webpack_require__(3); var _PanelGroup2 = _interopRequireDefault(_PanelGroup); var _PageItem = __webpack_require__(57); var _PageItem2 = _interopRequireDefault(_PageItem); var _Pager = __webpack_require__(58); var _Pager2 = _interopRequireDefault(_Pager); var _Popover = __webpack_require__(59); var _Popover2 = _interopRequireDefault(_Popover); var _ProgressBar = __webpack_require__(60); var _ProgressBar2 = _interopRequireDefault(_ProgressBar); var _Row = __webpack_require__(61); var _Row2 = _interopRequireDefault(_Row); var _SplitButton = __webpack_require__(62); var _SplitButton2 = _interopRequireDefault(_SplitButton); var _SubNav = __webpack_require__(63); var _SubNav2 = _interopRequireDefault(_SubNav); var _TabbedArea = __webpack_require__(64); var _TabbedArea2 = _interopRequireDefault(_TabbedArea); var _Table = __webpack_require__(65); var _Table2 = _interopRequireDefault(_Table); var _TabPane = __webpack_require__(66); var _TabPane2 = _interopRequireDefault(_TabPane); var _Thumbnail = __webpack_require__(67); var _Thumbnail2 = _interopRequireDefault(_Thumbnail); var _Tooltip = __webpack_require__(68); var _Tooltip2 = _interopRequireDefault(_Tooltip); var _Well = __webpack_require__(69); var _Well2 = _interopRequireDefault(_Well); var _styleMaps = __webpack_require__(6); var _styleMaps2 = _interopRequireDefault(_styleMaps); exports['default'] = { Accordion: _Accordion2['default'], Affix: _Affix2['default'], AffixMixin: _AffixMixin2['default'], Alert: _Alert2['default'], BootstrapMixin: _BootstrapMixin2['default'], Badge: _Badge2['default'], Button: _Button2['default'], ButtonGroup: _ButtonGroup2['default'], ButtonInput: _ButtonInput2['default'], ButtonToolbar: _ButtonToolbar2['default'], CollapsibleNav: _CollapsibleNav2['default'], Carousel: _Carousel2['default'], CarouselItem: _CarouselItem2['default'], Col: _Col2['default'], CollapsibleMixin: _CollapsibleMixin2['default'], DropdownButton: _DropdownButton2['default'], DropdownMenu: _DropdownMenu2['default'], DropdownStateMixin: _DropdownStateMixin2['default'], FadeMixin: _FadeMixin2['default'], FormControls: _FormControls2['default'], Glyphicon: _Glyphicon2['default'], Grid: _Grid2['default'], Input: _Input2['default'], Interpolate: _Interpolate2['default'], Jumbotron: _Jumbotron2['default'], Label: _Label2['default'], ListGroup: _ListGroup2['default'], ListGroupItem: _ListGroupItem2['default'], MenuItem: _MenuItem2['default'], Modal: _Modal2['default'], Nav: _Nav2['default'], Navbar: _Navbar2['default'], NavItem: _NavItem2['default'], ModalTrigger: _ModalTrigger2['default'], OverlayTrigger: _OverlayTrigger2['default'], OverlayMixin: _OverlayMixin2['default'], PageHeader: _PageHeader2['default'], Panel: _Panel2['default'], PanelGroup: _PanelGroup2['default'], PageItem: _PageItem2['default'], Pager: _Pager2['default'], Popover: _Popover2['default'], ProgressBar: _ProgressBar2['default'], Row: _Row2['default'], SplitButton: _SplitButton2['default'], SubNav: _SubNav2['default'], TabbedArea: _TabbedArea2['default'], Table: _Table2['default'], TabPane: _TabPane2['default'], Thumbnail: _Thumbnail2['default'], Tooltip: _Tooltip2['default'], Well: _Well2['default'], styleMaps: _styleMaps2['default'] }; module.exports = exports['default']; /***/ }, /* 1 */ /***/ 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 _PanelGroup = __webpack_require__(3); var _PanelGroup2 = _interopRequireDefault(_PanelGroup); var Accordion = _react2['default'].createClass({ displayName: 'Accordion', render: function render() { return _react2['default'].createElement( _PanelGroup2['default'], _extends({}, this.props, { accordion: true }), this.props.children ); } }); exports['default'] = Accordion; module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { /* eslint react/prop-types: [1, {ignore: ["children", "className", "bsStyle"]}]*/ /* BootstrapMixin contains `bsStyle` type validation */ '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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var PanelGroup = _react2['default'].createClass({ displayName: 'PanelGroup', mixins: [_BootstrapMixin2['default']], propTypes: { accordion: _react2['default'].PropTypes.bool, activeKey: _react2['default'].PropTypes.any, defaultActiveKey: _react2['default'].PropTypes.any, onSelect: _react2['default'].PropTypes.func }, getDefaultProps: function getDefaultProps() { return { bsClass: 'panel-group' }; }, getInitialState: function getInitialState() { var defaultActiveKey = this.props.defaultActiveKey; return { activeKey: defaultActiveKey }; }, render: function render() { var classes = this.getBsClassSet(); return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), onSelect: null }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderPanel) ); }, renderPanel: function renderPanel(child, index) { var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey; var props = { bsStyle: child.props.bsStyle || this.props.bsStyle, key: child.key ? child.key : index, ref: child.ref }; if (this.props.accordion) { props.collapsible = true; props.expanded = child.props.eventKey === activeKey; props.onSelect = this.handleSelect; } return (0, _react.cloneElement)(child, props); }, shouldComponentUpdate: function shouldComponentUpdate() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleSelect: function handleSelect(e, key) { e.preventDefault(); if (this.props.onSelect) { this._isChanging = true; this.props.onSelect(key); this._isChanging = false; } if (this.state.activeKey === key) { key = null; } this.setState({ activeKey: key }); } }); exports['default'] = PanelGroup; module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames () { 'use strict'; var classes = ''; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if ('string' === argType || 'number' === argType) { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames.apply(null, arg); } else if ('object' === argType) { for (var key in arg) { if (arg.hasOwnProperty(key) && arg[key]) { classes += ' ' + key; } } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } /* global define */ // safely export classNames for RequireJS if (true) { !(__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__)); } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _styleMaps = __webpack_require__(6); var _styleMaps2 = _interopRequireDefault(_styleMaps); var _utilsCustomPropTypes = __webpack_require__(7); var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes); var BootstrapMixin = { propTypes: { bsClass: _utilsCustomPropTypes2['default'].keyOf(_styleMaps2['default'].CLASSES), bsStyle: _utilsCustomPropTypes2['default'].keyOf(_styleMaps2['default'].STYLES), bsSize: _utilsCustomPropTypes2['default'].keyOf(_styleMaps2['default'].SIZES) }, getBsClassSet: function getBsClassSet() { var classes = {}; var bsClass = this.props.bsClass && _styleMaps2['default'].CLASSES[this.props.bsClass]; if (bsClass) { classes[bsClass] = true; var prefix = bsClass + '-'; var bsSize = this.props.bsSize && _styleMaps2['default'].SIZES[this.props.bsSize]; if (bsSize) { classes[prefix + bsSize] = true; } var bsStyle = this.props.bsStyle && _styleMaps2['default'].STYLES[this.props.bsStyle]; if (this.props.bsStyle) { classes[prefix + bsStyle] = true; } } return classes; }, prefixClass: function prefixClass(subClass) { return _styleMaps2['default'].CLASSES[this.props.bsClass] + '-' + subClass; } }; exports['default'] = BootstrapMixin; module.exports = exports['default']; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var styleMaps = { CLASSES: { 'alert': 'alert', 'button': 'btn', 'button-group': 'btn-group', 'button-toolbar': 'btn-toolbar', 'column': 'col', 'input-group': 'input-group', 'form': 'form', 'glyphicon': 'glyphicon', 'label': 'label', 'thumbnail': 'thumbnail', 'list-group-item': 'list-group-item', 'panel': 'panel', 'panel-group': 'panel-group', 'progress-bar': 'progress-bar', 'nav': 'nav', 'navbar': 'navbar', 'modal': 'modal', 'row': 'row', 'well': 'well' }, STYLES: { 'default': 'default', 'primary': 'primary', 'success': 'success', 'info': 'info', 'warning': 'warning', 'danger': 'danger', 'link': 'link', 'inline': 'inline', 'tabs': 'tabs', 'pills': 'pills' }, addStyle: function addStyle(name) { styleMaps.STYLES[name] = name; }, SIZES: { 'large': 'lg', 'medium': 'md', 'small': 'sm', 'xsmall': 'xs' }, GLYPHS: ['asterisk', 'plus', 'euro', 'eur', 'minus', 'cloud', 'envelope', 'pencil', 'glass', 'music', 'search', 'heart', 'star', 'star-empty', 'user', 'film', 'th-large', 'th', 'th-list', 'ok', 'remove', 'zoom-in', 'zoom-out', 'off', 'signal', 'cog', 'trash', 'home', 'file', 'time', 'road', 'download-alt', 'download', 'upload', 'inbox', 'play-circle', 'repeat', 'refresh', 'list-alt', 'lock', 'flag', 'headphones', 'volume-off', 'volume-down', 'volume-up', 'qrcode', 'barcode', 'tag', 'tags', 'book', 'bookmark', 'print', 'camera', 'font', 'bold', 'italic', 'text-height', 'text-width', 'align-left', 'align-center', 'align-right', 'align-justify', 'list', 'indent-left', 'indent-right', 'facetime-video', 'picture', 'map-marker', 'adjust', 'tint', 'edit', 'share', 'check', 'move', 'step-backward', 'fast-backward', 'backward', 'play', 'pause', 'stop', 'forward', 'fast-forward', 'step-forward', 'eject', 'chevron-left', 'chevron-right', 'plus-sign', 'minus-sign', 'remove-sign', 'ok-sign', 'question-sign', 'info-sign', 'screenshot', 'remove-circle', 'ok-circle', 'ban-circle', 'arrow-left', 'arrow-right', 'arrow-up', 'arrow-down', 'share-alt', 'resize-full', 'resize-small', 'exclamation-sign', 'gift', 'leaf', 'fire', 'eye-open', 'eye-close', 'warning-sign', 'plane', 'calendar', 'random', 'comment', 'magnet', 'chevron-up', 'chevron-down', 'retweet', 'shopping-cart', 'folder-close', 'folder-open', 'resize-vertical', 'resize-horizontal', 'hdd', 'bullhorn', 'bell', 'certificate', 'thumbs-up', 'thumbs-down', 'hand-right', 'hand-left', 'hand-up', 'hand-down', 'circle-arrow-right', 'circle-arrow-left', 'circle-arrow-up', 'circle-arrow-down', 'globe', 'wrench', 'tasks', 'filter', 'briefcase', 'fullscreen', 'dashboard', 'paperclip', 'heart-empty', 'link', 'phone', 'pushpin', 'usd', 'gbp', 'sort', 'sort-by-alphabet', 'sort-by-alphabet-alt', 'sort-by-order', 'sort-by-order-alt', 'sort-by-attributes', 'sort-by-attributes-alt', 'unchecked', 'expand', 'collapse-down', 'collapse-up', 'log-in', 'flash', 'log-out', 'new-window', 'record', 'save', 'open', 'saved', 'import', 'export', 'send', 'floppy-disk', 'floppy-saved', 'floppy-remove', 'floppy-save', 'floppy-open', 'credit-card', 'transfer', 'cutlery', 'header', 'compressed', 'earphone', 'phone-alt', 'tower', 'stats', 'sd-video', 'hd-video', 'subtitles', 'sound-stereo', 'sound-dolby', 'sound-5-1', 'sound-6-1', 'sound-7-1', 'copyright-mark', 'registration-mark', 'cloud-download', 'cloud-upload', 'tree-conifer', 'tree-deciduous', 'cd', 'save-file', 'open-file', 'level-up', 'copy', 'paste', 'alert', 'equalizer', 'king', 'queen', 'pawn', 'bishop', 'knight', 'baby-formula', 'tent', 'blackboard', 'bed', 'apple', 'erase', 'hourglass', 'lamp', 'duplicate', 'piggy-bank', 'scissors', 'bitcoin', 'yen', 'ruble', 'scale', 'ice-lolly', 'ice-lolly-tasted', 'education', 'option-horizontal', 'option-vertical', 'menu-hamburger', 'modal-window', 'oil', 'grain', 'sunglasses', 'text-size', 'text-color', 'text-background', 'object-align-top', 'object-align-bottom', 'object-align-horizontal', 'object-align-left', 'object-align-vertical', 'object-align-right', 'triangle-right', 'triangle-left', 'triangle-bottom', 'triangle-top', 'console', 'superscript', 'subscript', 'menu-left', 'menu-right', 'menu-down', 'menu-up'] }; exports['default'] = styleMaps; module.exports = exports['default']; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _toArray(arr) { return Array.isArray(arr) ? arr : Array.from(arr); } var ANONYMOUS = '<<anonymous>>'; var CustomPropTypes = { /** * Checks whether a prop provides a DOM element * * The element can be provided in two forms: * - Directly passed * - Or passed an object which has a `getDOMNode` method which will return the required DOM element * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ mountable: createMountableChecker(), /** * Checks whether a prop matches a key of an associated object * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ keyOf: createKeyOfChecker, /** * Checks if only one of the listed properties is in use. An error is given * if multiple have a value * * @param props * @param propName * @param componentName * @returns {Error|undefined} */ singlePropFrom: createSinglePropFromChecker }; /** * Create chain-able isRequired validator * * Largely copied directly from: * https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94 */ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName) { componentName = componentName || ANONYMOUS; if (props[propName] == null) { if (isRequired) { return new Error('Required prop `' + propName + '` was not specified in ' + '`' + componentName + '`.'); } } else { return validate(props, propName, componentName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createMountableChecker() { function validate(props, propName, componentName) { if (typeof props[propName] !== 'object' || typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) { return new Error('Invalid prop `' + propName + '` supplied to ' + '`' + componentName + '`, expected a DOM element or an object that has a `render` method'); } } return createChainableTypeChecker(validate); } function createKeyOfChecker(obj) { function validate(props, propName, componentName) { var propValue = props[propName]; if (!obj.hasOwnProperty(propValue)) { var valuesString = JSON.stringify(Object.keys(obj)); return new Error('Invalid prop \'' + propName + '\' of value \'' + propValue + '\' ' + ('supplied to \'' + componentName + '\', expected one of ' + valuesString + '.')); } } return createChainableTypeChecker(validate); } function createSinglePropFromChecker(arrOfProps) { function validate(props, propName, componentName) { var usedPropCount = arrOfProps.map(function (listedProp) { return props[listedProp]; }).reduce(function (acc, curr) { return acc + (curr !== undefined ? 1 : 0); }, 0); if (usedPropCount > 1) { var _arrOfProps = _toArray(arrOfProps); var first = _arrOfProps[0]; var others = _arrOfProps.slice(1); var message = '' + others.join(', ') + ' and ' + first; return new Error('Invalid prop \'' + propName + '\', only one of the following ' + ('may be provided: ' + message)); } } return validate; } exports['default'] = CustomPropTypes; module.exports = exports['default']; /***/ }, /* 8 */ /***/ 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); /** * Maps children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The mapFunction provided index will be normalised to the components mapped, * so an invalid component would not increase the index. * * @param {?*} children Children tree container. * @param {function(*, int)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { var index = 0; return _react2['default'].Children.map(children, function (child) { if (_react2['default'].isValidElement(child)) { var lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through children that are typically specified as `props.children`, * but only iterates over children that are "valid components". * * The provided forEachFunc(child, index) will be called for each * leaf child with the index reflecting the position relative to "valid components". * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { var index = 0; return _react2['default'].Children.forEach(children, function (child) { if (_react2['default'].isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { var count = 0; _react2['default'].Children.forEach(children, function (child) { if (_react2['default'].isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { var hasValid = false; _react2['default'].Children.forEach(children, function (child) { if (!hasValid && _react2['default'].isValidElement(child)) { hasValid = true; } }); return hasValid; } exports['default'] = { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, hasValidComponent: hasValidComponent }; 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; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _AffixMixin = __webpack_require__(10); var _AffixMixin2 = _interopRequireDefault(_AffixMixin); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var Affix = _react2['default'].createClass({ displayName: 'Affix', statics: { domUtils: _utilsDomUtils2['default'] }, mixins: [_AffixMixin2['default']], render: function render() { var holderStyle = { top: this.state.affixPositionTop }; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, this.state.affixClass), style: holderStyle }), this.props.children ); } }); exports['default'] = Affix; module.exports = exports['default']; /***/ }, /* 10 */ /***/ 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 _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsEventListener = __webpack_require__(12); var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener); var AffixMixin = { propTypes: { offset: _react2['default'].PropTypes.number, offsetTop: _react2['default'].PropTypes.number, offsetBottom: _react2['default'].PropTypes.number }, getInitialState: function getInitialState() { return { affixClass: 'affix-top' }; }, getPinnedOffset: function getPinnedOffset(DOMNode) { if (this.pinnedOffset) { return this.pinnedOffset; } DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, ''); DOMNode.className += DOMNode.className.length ? ' affix' : 'affix'; this.pinnedOffset = _utilsDomUtils2['default'].getOffset(DOMNode).top - window.pageYOffset; return this.pinnedOffset; }, checkPosition: function checkPosition() { var DOMNode = undefined, scrollHeight = undefined, scrollTop = undefined, position = undefined, offsetTop = undefined, offsetBottom = undefined, affix = undefined, affixType = undefined, affixPositionTop = undefined; // TODO: or not visible if (!this.isMounted()) { return; } DOMNode = _react2['default'].findDOMNode(this); scrollHeight = document.documentElement.offsetHeight; scrollTop = window.pageYOffset; position = _utilsDomUtils2['default'].getOffset(DOMNode); if (this.affixed === 'top') { position.top += scrollTop; } offsetTop = this.props.offsetTop != null ? this.props.offsetTop : this.props.offset; offsetBottom = this.props.offsetBottom != null ? this.props.offsetBottom : this.props.offset; if (offsetTop == null && offsetBottom == null) { return; } if (offsetTop == null) { offsetTop = 0; } if (offsetBottom == null) { offsetBottom = 0; } if (this.unpin != null && scrollTop + this.unpin <= position.top) { affix = false; } else if (offsetBottom != null && position.top + DOMNode.offsetHeight >= scrollHeight - offsetBottom) { affix = 'bottom'; } else if (offsetTop != null && scrollTop <= offsetTop) { affix = 'top'; } else { affix = false; } if (this.affixed === affix) { return; } if (this.unpin != null) { DOMNode.style.top = ''; } affixType = 'affix' + (affix ? '-' + affix : ''); this.affixed = affix; this.unpin = affix === 'bottom' ? this.getPinnedOffset(DOMNode) : null; if (affix === 'bottom') { DOMNode.className = DOMNode.className.replace(/affix-top|affix-bottom|affix/, 'affix-bottom'); affixPositionTop = scrollHeight - offsetBottom - DOMNode.offsetHeight - _utilsDomUtils2['default'].getOffset(DOMNode).top; } this.setState({ affixClass: affixType, affixPositionTop: affixPositionTop }); }, checkPositionWithEventLoop: function checkPositionWithEventLoop() { setTimeout(this.checkPosition, 0); }, componentDidMount: function componentDidMount() { this._onWindowScrollListener = _utilsEventListener2['default'].listen(window, 'scroll', this.checkPosition); this._onDocumentClickListener = _utilsEventListener2['default'].listen(_utilsDomUtils2['default'].ownerDocument(this), 'click', this.checkPositionWithEventLoop); }, componentWillUnmount: function componentWillUnmount() { if (this._onWindowScrollListener) { this._onWindowScrollListener.remove(); } if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { if (prevState.affixClass === this.state.affixClass) { this.checkPositionWithEventLoop(); } } }; exports['default'] = AffixMixin; module.exports = exports['default']; /***/ }, /* 11 */ /***/ 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); /** * Get elements owner document * * @param {ReactComponent|HTMLElement} componentOrElement * @returns {HTMLElement} */ function ownerDocument(componentOrElement) { var elem = _react2['default'].findDOMNode(componentOrElement); return elem && elem.ownerDocument || document; } /** * Shortcut to compute element style * * @param {HTMLElement} elem * @returns {CssStyle} */ function getComputedStyles(elem) { return ownerDocument(elem).defaultView.getComputedStyle(elem, null); } /** * Get elements offset * * TODO: REMOVE JQUERY! * * @param {HTMLElement} DOMNode * @returns {{top: number, left: number}} */ function getOffset(DOMNode) { if (window.jQuery) { return window.jQuery(DOMNode).offset(); } var docElem = ownerDocument(DOMNode).documentElement; var box = { top: 0, left: 0 }; // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if (typeof DOMNode.getBoundingClientRect !== 'undefined') { box = DOMNode.getBoundingClientRect(); } return { top: box.top + window.pageYOffset - docElem.clientTop, left: box.left + window.pageXOffset - docElem.clientLeft }; } /** * Get elements position * * TODO: REMOVE JQUERY! * * @param {HTMLElement} elem * @param {HTMLElement?} offsetParent * @returns {{top: number, left: number}} */ function getPosition(elem, offsetParent) { if (window.jQuery) { return window.jQuery(elem).position(); } var offset = undefined, parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent if (getComputedStyles(elem).position === 'fixed') { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { if (!offsetParent) { // Get *real* offsetParent offsetParent = offsetParentFunc(elem); } // Get correct offsets offset = getOffset(elem); if (offsetParent.nodeName !== 'HTML') { parentOffset = getOffset(offsetParent); } // Add offsetParent borders parentOffset.top += parseInt(getComputedStyles(offsetParent).borderTopWidth, 10); parentOffset.left += parseInt(getComputedStyles(offsetParent).borderLeftWidth, 10); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - parseInt(getComputedStyles(elem).marginTop, 10), left: offset.left - parentOffset.left - parseInt(getComputedStyles(elem).marginLeft, 10) }; } /** * Get parent element * * @param {HTMLElement?} elem * @returns {HTMLElement} */ function offsetParentFunc(elem) { var docElem = ownerDocument(elem).documentElement; var offsetParent = elem.offsetParent || docElem; while (offsetParent && (offsetParent.nodeName !== 'HTML' && getComputedStyles(offsetParent).position === 'static')) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; } exports['default'] = { ownerDocument: ownerDocument, getComputedStyles: getComputedStyles, getOffset: getOffset, getPosition: getPosition, offsetParent: offsetParentFunc }; module.exports = exports['default']; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2014 Facebook, Inc. * * This file contains a modified version of: * https://github.com/facebook/react/blob/v0.12.0/src/vendor/stubs/EventListener.js * * 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. * * TODO: remove in favour of solution provided by: * https://github.com/facebook/react/issues/285 */ /** * Does not take into account specific nature of platform. */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function listen(target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } } }; exports['default'] = EventListener; module.exports = exports['default']; /***/ }, /* 13 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var Alert = _react2['default'].createClass({ displayName: 'Alert', mixins: [_BootstrapMixin2['default']], propTypes: { onDismiss: _react2['default'].PropTypes.func, dismissAfter: _react2['default'].PropTypes.number }, getDefaultProps: function getDefaultProps() { return { bsClass: 'alert', bsStyle: 'info' }; }, renderDismissButton: function renderDismissButton() { return _react2['default'].createElement( 'button', { type: 'button', className: 'close', onClick: this.props.onDismiss, 'aria-hidden': 'true' }, '×' ); }, render: function render() { var classes = this.getBsClassSet(); var isDismissable = !!this.props.onDismiss; classes['alert-dismissable'] = isDismissable; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), isDismissable ? this.renderDismissButton() : null, this.props.children ); }, componentDidMount: function componentDidMount() { if (this.props.dismissAfter && this.props.onDismiss) { this.dismissTimer = setTimeout(this.props.onDismiss, this.props.dismissAfter); } }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this.dismissTimer); } }); exports['default'] = Alert; module.exports = exports['default']; /***/ }, /* 14 */ /***/ 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 _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var Badge = _react2['default'].createClass({ displayName: 'Badge', propTypes: { pullRight: _react2['default'].PropTypes.bool }, hasContent: function hasContent() { return _utilsValidComponentChildren2['default'].hasValidComponent(this.props.children) || _react2['default'].Children.count(this.props.children) > 1 || typeof this.props.children === 'string' || typeof this.props.children === 'number'; }, render: function render() { var classes = { 'pull-right': this.props.pullRight, 'badge': this.hasContent() }; return _react2['default'].createElement( 'span', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = Badge; module.exports = exports['default']; /***/ }, /* 15 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var Button = _react2['default'].createClass({ displayName: 'Button', mixins: [_BootstrapMixin2['default']], propTypes: { active: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, block: _react2['default'].PropTypes.bool, navItem: _react2['default'].PropTypes.bool, navDropdown: _react2['default'].PropTypes.bool, componentClass: _react2['default'].PropTypes.node, href: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { bsClass: 'button', bsStyle: 'default', type: 'button' }; }, render: function render() { var classes = this.props.navDropdown ? {} : this.getBsClassSet(); var renderFuncName = undefined; classes = _extends({ active: this.props.active, 'btn-block': this.props.block }, classes); if (this.props.navItem) { return this.renderNavItem(classes); } renderFuncName = this.props.href || this.props.target || this.props.navDropdown ? 'renderAnchor' : 'renderButton'; return this[renderFuncName](classes); }, renderAnchor: function renderAnchor(classes) { var Component = this.props.componentClass || 'a'; var href = this.props.href || '#'; classes.disabled = this.props.disabled; return _react2['default'].createElement( Component, _extends({}, this.props, { href: href, className: (0, _classnames2['default'])(this.props.className, classes), role: 'button' }), this.props.children ); }, renderButton: function renderButton(classes) { var Component = this.props.componentClass || 'button'; return _react2['default'].createElement( Component, _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); }, renderNavItem: function renderNavItem(classes) { var liClasses = { active: this.props.active }; return _react2['default'].createElement( 'li', { className: (0, _classnames2['default'])(liClasses) }, this.renderAnchor(classes) ); } }); exports['default'] = Button; module.exports = exports['default']; // eslint-disable-line object-shorthand /***/ }, /* 16 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var ButtonGroup = _react2['default'].createClass({ displayName: 'ButtonGroup', mixins: [_BootstrapMixin2['default']], propTypes: { vertical: _react2['default'].PropTypes.bool, justified: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { bsClass: 'button-group' }; }, render: function render() { var classes = this.getBsClassSet(); classes['btn-group'] = !this.props.vertical; classes['btn-group-vertical'] = this.props.vertical; classes['btn-group-justified'] = this.props.justified; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = ButtonGroup; module.exports = exports['default']; /***/ }, /* 17 */ /***/ 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; }; })(); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _Button = __webpack_require__(15); var _Button2 = _interopRequireDefault(_Button); var _FormGroup = __webpack_require__(18); var _FormGroup2 = _interopRequireDefault(_FormGroup); var _InputBase2 = __webpack_require__(19); var _InputBase3 = _interopRequireDefault(_InputBase2); var _utilsChildrenValueInputValidation = __webpack_require__(20); var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation); var ButtonInput = (function (_InputBase) { function ButtonInput() { _classCallCheck(this, ButtonInput); if (_InputBase != null) { _InputBase.apply(this, arguments); } } _inherits(ButtonInput, _InputBase); _createClass(ButtonInput, [{ key: 'renderFormGroup', value: function renderFormGroup(children) { var _props = this.props; var bsStyle = _props.bsStyle; var value = _props.value; var other = _objectWithoutProperties(_props, ['bsStyle', 'value']); // eslint-disable-line object-shorthand, no-unused-vars return _react2['default'].createElement( _FormGroup2['default'], other, children ); } }, { key: 'renderInput', value: function renderInput() { var _props2 = this.props; var children = _props2.children; var value = _props2.value; var other = _objectWithoutProperties(_props2, ['children', 'value']); // eslint-disable-line object-shorthand var val = children ? children : value; return _react2['default'].createElement(_Button2['default'], _extends({}, other, { componentClass: 'input', ref: 'input', key: 'input', value: val })); } }]); return ButtonInput; })(_InputBase3['default']); ButtonInput.types = ['button', 'reset', 'submit']; ButtonInput.defaultProps = { type: 'button' }; ButtonInput.propTypes = { type: _react2['default'].PropTypes.oneOf(ButtonInput.types), bsStyle: function bsStyle(props) { //defer to Button propTypes of bsStyle return null; }, children: _utilsChildrenValueInputValidation2['default'], value: _utilsChildrenValueInputValidation2['default'] }; exports['default'] = ButtonInput; module.exports = exports['default']; /***/ }, /* 18 */ /***/ 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; }; })(); 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var FormGroup = (function (_React$Component) { function FormGroup() { _classCallCheck(this, FormGroup); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(FormGroup, _React$Component); _createClass(FormGroup, [{ key: 'render', value: function render() { var classes = { 'form-group': !this.props.standalone, 'form-group-lg': !this.props.standalone && this.props.bsSize === 'large', 'form-group-sm': !this.props.standalone && this.props.bsSize === 'small', 'has-feedback': this.props.hasFeedback, 'has-success': this.props.bsStyle === 'success', 'has-warning': this.props.bsStyle === 'warning', 'has-error': this.props.bsStyle === 'error' }; return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(classes, this.props.groupClassName) }, this.props.children ); } }]); return FormGroup; })(_react2['default'].Component); FormGroup.defaultProps = { standalone: false }; FormGroup.propTypes = { standalone: _react2['default'].PropTypes.bool, hasFeedback: _react2['default'].PropTypes.bool, bsSize: function bsSize(props) { if (props.standalone && props.bsSize !== undefined) { return new Error('bsSize will not be used when `standalone` is set.'); } return _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']).apply(null, arguments); }, bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']), groupClassName: _react2['default'].PropTypes.string }; exports['default'] = FormGroup; module.exports = exports['default']; /***/ }, /* 19 */ /***/ 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; }; })(); 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _FormGroup = __webpack_require__(18); var _FormGroup2 = _interopRequireDefault(_FormGroup); var InputBase = (function (_React$Component) { function InputBase() { _classCallCheck(this, InputBase); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(InputBase, _React$Component); _createClass(InputBase, [{ key: 'getInputDOMNode', value: function getInputDOMNode() { return _react2['default'].findDOMNode(this.refs.input); } }, { key: 'getValue', value: function getValue() { if (this.props.type === 'static') { return this.props.value; } else if (this.props.type) { if (this.props.type === 'select' && this.props.multiple) { return this.getSelectedOptions(); } else { return this.getInputDOMNode().value; } } else { throw 'Cannot use getValue without specifying input type.'; } } }, { key: 'getChecked', value: function getChecked() { return this.getInputDOMNode().checked; } }, { key: 'getSelectedOptions', value: function getSelectedOptions() { var values = []; Array.prototype.forEach.call(this.getInputDOMNode().getElementsByTagName('option'), function (option) { if (option.selected) { var value = option.getAttribute('value') || option.innerHtml; values.push(value); } }); return values; } }, { key: 'isCheckboxOrRadio', value: function isCheckboxOrRadio() { return this.props.type === 'checkbox' || this.props.type === 'radio'; } }, { key: 'isFile', value: function isFile() { return this.props.type === 'file'; } }, { key: 'renderInputGroup', value: function renderInputGroup(children) { var addonBefore = this.props.addonBefore ? _react2['default'].createElement( 'span', { className: 'input-group-addon', key: 'addonBefore' }, this.props.addonBefore ) : null; var addonAfter = this.props.addonAfter ? _react2['default'].createElement( 'span', { className: 'input-group-addon', key: 'addonAfter' }, this.props.addonAfter ) : null; var buttonBefore = this.props.buttonBefore ? _react2['default'].createElement( 'span', { className: 'input-group-btn' }, this.props.buttonBefore ) : null; var buttonAfter = this.props.buttonAfter ? _react2['default'].createElement( 'span', { className: 'input-group-btn' }, this.props.buttonAfter ) : null; var inputGroupClassName = undefined; switch (this.props.bsSize) { case 'small': inputGroupClassName = 'input-group-sm';break; case 'large': inputGroupClassName = 'input-group-lg';break; } return addonBefore || addonAfter || buttonBefore || buttonAfter ? _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(inputGroupClassName, 'input-group'), key: 'input-group' }, addonBefore, buttonBefore, children, addonAfter, buttonAfter ) : children; } }, { key: 'renderIcon', value: function renderIcon() { var classes = { 'glyphicon': true, 'form-control-feedback': true, 'glyphicon-ok': this.props.bsStyle === 'success', 'glyphicon-warning-sign': this.props.bsStyle === 'warning', 'glyphicon-remove': this.props.bsStyle === 'error' }; return this.props.hasFeedback ? _react2['default'].createElement('span', { className: (0, _classnames2['default'])(classes), key: 'icon' }) : null; } }, { key: 'renderHelp', value: function renderHelp() { return this.props.help ? _react2['default'].createElement( 'span', { className: 'help-block', key: 'help' }, this.props.help ) : null; } }, { key: 'renderCheckboxAndRadioWrapper', value: function renderCheckboxAndRadioWrapper(children) { var classes = { 'checkbox': this.props.type === 'checkbox', 'radio': this.props.type === 'radio' }; return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(classes), key: 'checkboxRadioWrapper' }, children ); } }, { key: 'renderWrapper', value: function renderWrapper(children) { return this.props.wrapperClassName ? _react2['default'].createElement( 'div', { className: this.props.wrapperClassName, key: 'wrapper' }, children ) : children; } }, { key: 'renderLabel', value: function renderLabel(children) { var classes = { 'control-label': !this.isCheckboxOrRadio() }; classes[this.props.labelClassName] = this.props.labelClassName; return this.props.label ? _react2['default'].createElement( 'label', { htmlFor: this.props.id, className: (0, _classnames2['default'])(classes), key: 'label' }, children, this.props.label ) : children; } }, { key: 'renderInput', value: function renderInput() { if (!this.props.type) { return this.props.children; } switch (this.props.type) { case 'select': return _react2['default'].createElement( 'select', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control'), ref: 'input', key: 'input' }), this.props.children ); case 'textarea': return _react2['default'].createElement('textarea', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control'), ref: 'input', key: 'input' })); case 'static': return _react2['default'].createElement( 'p', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control-static'), ref: 'input', key: 'input' }), this.props.value ); } var className = this.isCheckboxOrRadio() || this.isFile() ? '' : 'form-control'; return _react2['default'].createElement('input', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, className), ref: 'input', key: 'input' })); } }, { key: 'renderFormGroup', value: function renderFormGroup(children) { return _react2['default'].createElement( _FormGroup2['default'], this.props, children ); } }, { key: 'renderChildren', value: function renderChildren() { return !this.isCheckboxOrRadio() ? [this.renderLabel(), this.renderWrapper([this.renderInputGroup(this.renderInput()), this.renderIcon(), this.renderHelp()])] : this.renderWrapper([this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())), this.renderHelp()]); } }, { key: 'render', value: function render() { var children = this.renderChildren(); return this.renderFormGroup(children); } }]); return InputBase; })(_react2['default'].Component); InputBase.propTypes = { type: _react2['default'].PropTypes.string, label: _react2['default'].PropTypes.node, help: _react2['default'].PropTypes.node, addonBefore: _react2['default'].PropTypes.node, addonAfter: _react2['default'].PropTypes.node, buttonBefore: _react2['default'].PropTypes.node, buttonAfter: _react2['default'].PropTypes.node, bsSize: _react2['default'].PropTypes.oneOf(['small', 'medium', 'large']), bsStyle: _react2['default'].PropTypes.oneOf(['success', 'warning', 'error']), hasFeedback: _react2['default'].PropTypes.bool, id: _react2['default'].PropTypes.string, groupClassName: _react2['default'].PropTypes.string, wrapperClassName: _react2['default'].PropTypes.string, labelClassName: _react2['default'].PropTypes.string, multiple: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, value: _react2['default'].PropTypes.any }; exports['default'] = InputBase; module.exports = exports['default']; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = valueValidation; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _CustomPropTypes = __webpack_require__(7); var propList = ['children', 'value']; var typeList = [_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]; function valueValidation(props, propName, componentName) { var error = (0, _CustomPropTypes.singlePropFrom)(propList)(props, propName, componentName); if (!error) { var oneOfType = _react2['default'].PropTypes.oneOfType(typeList); error = oneOfType(props, propName, componentName); } return error; } module.exports = exports['default']; /***/ }, /* 21 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var ButtonToolbar = _react2['default'].createClass({ displayName: 'ButtonToolbar', mixins: [_BootstrapMixin2['default']], getDefaultProps: function getDefaultProps() { return { bsClass: 'button-toolbar' }; }, render: function render() { var classes = this.getBsClassSet(); return _react2['default'].createElement( 'div', _extends({}, this.props, { role: 'toolbar', className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = ButtonToolbar; module.exports = exports['default']; /***/ }, /* 22 */ /***/ 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 _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _CollapsibleMixin = __webpack_require__(23); var _CollapsibleMixin2 = _interopRequireDefault(_CollapsibleMixin); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var CollapsibleNav = _react2['default'].createClass({ displayName: 'CollapsibleNav', mixins: [_BootstrapMixin2['default'], _CollapsibleMixin2['default']], propTypes: { onSelect: _react2['default'].PropTypes.func, activeHref: _react2['default'].PropTypes.string, activeKey: _react2['default'].PropTypes.any, collapsible: _react2['default'].PropTypes.bool, expanded: _react2['default'].PropTypes.bool, eventKey: _react2['default'].PropTypes.any }, getCollapsibleDOMNode: function getCollapsibleDOMNode() { return _react2['default'].findDOMNode(this); }, getCollapsibleDimensionValue: function getCollapsibleDimensionValue() { var height = 0; var nodes = this.refs; for (var key in nodes) { if (nodes.hasOwnProperty(key)) { var n = _react2['default'].findDOMNode(nodes[key]), h = n.offsetHeight, computedStyles = _utilsDomUtils2['default'].getComputedStyles(n); height += h + parseInt(computedStyles.marginTop, 10) + parseInt(computedStyles.marginBottom, 10); } } return height; }, render: function render() { /* * this.props.collapsible is set in NavBar when an eventKey is supplied. */ var classes = this.props.collapsible ? this.getCollapsibleClassSet('navbar-collapse') : null; var renderChildren = this.props.collapsible ? this.renderCollapsibleNavChildren : this.renderChildren; return _react2['default'].createElement( 'div', { eventKey: this.props.eventKey, className: (0, _classnames2['default'])(this.props.className, classes) }, _utilsValidComponentChildren2['default'].map(this.props.children, renderChildren) ); }, getChildActiveProp: function getChildActiveProp(child) { if (child.props.active) { return true; } if (this.props.activeKey != null) { if (child.props.eventKey === this.props.activeKey) { return true; } } if (this.props.activeHref != null) { if (child.props.href === this.props.activeHref) { return true; } } return child.props.active; }, renderChildren: function renderChildren(child, index) { var key = child.key ? child.key : index; return (0, _react.cloneElement)(child, { activeKey: this.props.activeKey, activeHref: this.props.activeHref, ref: 'nocollapse_' + key, key: key, navItem: true }); }, renderCollapsibleNavChildren: function renderCollapsibleNavChildren(child, index) { var key = child.key ? child.key : index; return (0, _react.cloneElement)(child, { active: this.getChildActiveProp(child), activeKey: this.props.activeKey, activeHref: this.props.activeHref, onSelect: (0, _utilsCreateChainedFunction2['default'])(child.props.onSelect, this.props.onSelect), ref: 'collapsible_' + key, key: key, navItem: true }); } }); exports['default'] = CollapsibleNav; module.exports = exports['default']; /***/ }, /* 23 */ /***/ 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 _utilsTransitionEvents = __webpack_require__(24); var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents); var CollapsibleMixin = { propTypes: { defaultExpanded: _react2['default'].PropTypes.bool, expanded: _react2['default'].PropTypes.bool }, getInitialState: function getInitialState() { var defaultExpanded = this.props.defaultExpanded != null ? this.props.defaultExpanded : this.props.expanded != null ? this.props.expanded : false; return { expanded: defaultExpanded, collapsing: false }; }, componentWillUpdate: function componentWillUpdate(nextProps, nextState) { var willExpanded = nextProps.expanded != null ? nextProps.expanded : nextState.expanded; if (willExpanded === this.isExpanded()) { return; } // if the expanded state is being toggled, ensure node has a dimension value // this is needed for the animation to work and needs to be set before // the collapsing class is applied (after collapsing is applied the in class // is removed and the node's dimension will be wrong) var node = this.getCollapsibleDOMNode(); var dimension = this.dimension(); var value = '0'; if (!willExpanded) { value = this.getCollapsibleDimensionValue(); } node.style[dimension] = value + 'px'; this._afterWillUpdate(); }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { // check if expanded is being toggled; if so, set collapsing this._checkToggleCollapsing(prevProps, prevState); // check if collapsing was turned on; if so, start animation this._checkStartAnimation(); }, // helps enable test stubs _afterWillUpdate: function _afterWillUpdate() {}, _checkStartAnimation: function _checkStartAnimation() { if (!this.state.collapsing) { return; } var node = this.getCollapsibleDOMNode(); var dimension = this.dimension(); var value = this.getCollapsibleDimensionValue(); // setting the dimension here starts the transition animation var result = undefined; if (this.isExpanded()) { result = value + 'px'; } else { result = '0px'; } node.style[dimension] = result; }, _checkToggleCollapsing: function _checkToggleCollapsing(prevProps, prevState) { var wasExpanded = prevProps.expanded != null ? prevProps.expanded : prevState.expanded; var isExpanded = this.isExpanded(); if (wasExpanded !== isExpanded) { if (wasExpanded) { this._handleCollapse(); } else { this._handleExpand(); } } }, _handleExpand: function _handleExpand() { var _this = this; var node = this.getCollapsibleDOMNode(); var dimension = this.dimension(); var complete = function complete() { _this._removeEndEventListener(node, complete); // remove dimension value - this ensures the collapsible item can grow // in dimension after initial display (such as an image loading) node.style[dimension] = ''; _this.setState({ collapsing: false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, _handleCollapse: function _handleCollapse() { var _this2 = this; var node = this.getCollapsibleDOMNode(); var complete = function complete() { _this2._removeEndEventListener(node, complete); _this2.setState({ collapsing: false }); }; this._addEndEventListener(node, complete); this.setState({ collapsing: true }); }, // helps enable test stubs _addEndEventListener: function _addEndEventListener(node, complete) { _utilsTransitionEvents2['default'].addEndEventListener(node, complete); }, // helps enable test stubs _removeEndEventListener: function _removeEndEventListener(node, complete) { _utilsTransitionEvents2['default'].removeEndEventListener(node, complete); }, dimension: function dimension() { return typeof this.getCollapsibleDimension === 'function' ? this.getCollapsibleDimension() : 'height'; }, isExpanded: function isExpanded() { return this.props.expanded != null ? this.props.expanded : this.state.expanded; }, getCollapsibleClassSet: function getCollapsibleClassSet(className) { var classes = {}; if (typeof className === 'string') { className.split(' ').forEach(function (subClasses) { if (subClasses) { classes[subClasses] = true; } }); } classes.collapsing = this.state.collapsing; classes.collapse = !this.state.collapsing; classes['in'] = this.isExpanded() && !this.state.collapsing; return classes; } }; exports['default'] = CollapsibleMixin; module.exports = exports['default']; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This file contains a modified version of: * https://github.com/facebook/react/blob/v0.12.0/src/addons/transitions/ReactTransitionEvents.js * * This source code is licensed under the BSD-style license found here: * https://github.com/facebook/react/blob/v0.12.0/LICENSE * An additional grant of patent rights can be found here: * https://github.com/facebook/react/blob/v0.12.0/PATENTS */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * 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 (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 addEndEventListener(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 removeEndEventListener(node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; exports['default'] = ReactTransitionEvents; module.exports = exports['default']; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /** * Safe chained function * * Will only create a new function if needed, * otherwise will pass back existing functions or null. * * @param {function} one * @param {function} two * @returns {function|null} */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function createChainedFunction(one, two) { var hasOne = typeof one === 'function'; var hasTwo = typeof two === 'function'; if (!hasOne && !hasTwo) { return null; } if (!hasOne) { return two; } if (!hasTwo) { return one; } return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } exports['default'] = createChainedFunction; module.exports = exports['default']; /***/ }, /* 26 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var Carousel = _react2['default'].createClass({ displayName: 'Carousel', mixins: [_BootstrapMixin2['default']], propTypes: { slide: _react2['default'].PropTypes.bool, indicators: _react2['default'].PropTypes.bool, interval: _react2['default'].PropTypes.number, controls: _react2['default'].PropTypes.bool, pauseOnHover: _react2['default'].PropTypes.bool, wrap: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, onSlideEnd: _react2['default'].PropTypes.func, activeIndex: _react2['default'].PropTypes.number, defaultActiveIndex: _react2['default'].PropTypes.number, direction: _react2['default'].PropTypes.oneOf(['prev', 'next']) }, getDefaultProps: function getDefaultProps() { return { slide: true, interval: 5000, pauseOnHover: true, wrap: true, indicators: true, controls: true }; }, getInitialState: function getInitialState() { return { activeIndex: this.props.defaultActiveIndex == null ? 0 : this.props.defaultActiveIndex, previousActiveIndex: null, direction: null }; }, getDirection: function getDirection(prevIndex, index) { if (prevIndex === index) { return null; } return prevIndex > index ? 'prev' : 'next'; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var activeIndex = this.getActiveIndex(); if (nextProps.activeIndex != null && nextProps.activeIndex !== activeIndex) { clearTimeout(this.timeout); this.setState({ previousActiveIndex: activeIndex, direction: nextProps.direction != null ? nextProps.direction : this.getDirection(activeIndex, nextProps.activeIndex) }); } }, componentDidMount: function componentDidMount() { this.waitForNext(); }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this.timeout); }, next: function next(e) { if (e) { e.preventDefault(); } var index = this.getActiveIndex() + 1; var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children); if (index > count - 1) { if (!this.props.wrap) { return; } index = 0; } this.handleSelect(index, 'next'); }, prev: function prev(e) { if (e) { e.preventDefault(); } var index = this.getActiveIndex() - 1; if (index < 0) { if (!this.props.wrap) { return; } index = _utilsValidComponentChildren2['default'].numberOf(this.props.children) - 1; } this.handleSelect(index, 'prev'); }, pause: function pause() { this.isPaused = true; clearTimeout(this.timeout); }, play: function play() { this.isPaused = false; this.waitForNext(); }, waitForNext: function waitForNext() { if (!this.isPaused && this.props.slide && this.props.interval && this.props.activeIndex == null) { this.timeout = setTimeout(this.next, this.props.interval); } }, handleMouseOver: function handleMouseOver() { if (this.props.pauseOnHover) { this.pause(); } }, handleMouseOut: function handleMouseOut() { if (this.isPaused) { this.play(); } }, render: function render() { var classes = { carousel: true, slide: this.props.slide }; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), onMouseOver: this.handleMouseOver, onMouseOut: this.handleMouseOut }), this.props.indicators ? this.renderIndicators() : null, _react2['default'].createElement( 'div', { className: 'carousel-inner', ref: 'inner' }, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderItem) ), this.props.controls ? this.renderControls() : null ); }, renderPrev: function renderPrev() { return _react2['default'].createElement( 'a', { className: 'left carousel-control', href: '#prev', key: 0, onClick: this.prev }, _react2['default'].createElement('span', { className: 'glyphicon glyphicon-chevron-left' }) ); }, renderNext: function renderNext() { return _react2['default'].createElement( 'a', { className: 'right carousel-control', href: '#next', key: 1, onClick: this.next }, _react2['default'].createElement('span', { className: 'glyphicon glyphicon-chevron-right' }) ); }, renderControls: function renderControls() { if (!this.props.wrap) { var activeIndex = this.getActiveIndex(); var count = _utilsValidComponentChildren2['default'].numberOf(this.props.children); return [activeIndex !== 0 ? this.renderPrev() : null, activeIndex !== count - 1 ? this.renderNext() : null]; } return [this.renderPrev(), this.renderNext()]; }, renderIndicator: function renderIndicator(child, index) { var className = index === this.getActiveIndex() ? 'active' : null; return _react2['default'].createElement('li', { key: index, className: className, onClick: this.handleSelect.bind(this, index, null) }); }, renderIndicators: function renderIndicators() { var indicators = []; _utilsValidComponentChildren2['default'].forEach(this.props.children, function (child, index) { indicators.push(this.renderIndicator(child, index), // Force whitespace between indicator elements, bootstrap // requires this for correct spacing of elements. ' '); }, this); return _react2['default'].createElement( 'ol', { className: 'carousel-indicators' }, indicators ); }, getActiveIndex: function getActiveIndex() { return this.props.activeIndex != null ? this.props.activeIndex : this.state.activeIndex; }, handleItemAnimateOutEnd: function handleItemAnimateOutEnd() { this.setState({ previousActiveIndex: null, direction: null }, function () { this.waitForNext(); if (this.props.onSlideEnd) { this.props.onSlideEnd(); } }); }, renderItem: function renderItem(child, index) { var activeIndex = this.getActiveIndex(); var isActive = index === activeIndex; var isPreviousActive = this.state.previousActiveIndex != null && this.state.previousActiveIndex === index && this.props.slide; return (0, _react.cloneElement)(child, { active: isActive, ref: child.ref, key: child.key ? child.key : index, index: index, animateOut: isPreviousActive, animateIn: isActive && this.state.previousActiveIndex != null && this.props.slide, direction: this.state.direction, onAnimateOutEnd: isPreviousActive ? this.handleItemAnimateOutEnd : null }); }, handleSelect: function handleSelect(index, direction) { clearTimeout(this.timeout); var previousActiveIndex = this.getActiveIndex(); direction = direction || this.getDirection(previousActiveIndex, index); if (this.props.onSelect) { this.props.onSelect(index, direction); } if (this.props.activeIndex == null && index !== previousActiveIndex) { if (this.state.previousActiveIndex != null) { // If currently animating don't activate the new index. // TODO: look into queuing this canceled call and // animating after the current animation has ended. return; } this.setState({ activeIndex: index, previousActiveIndex: previousActiveIndex, direction: direction }); } } }); exports['default'] = Carousel; module.exports = exports['default']; /***/ }, /* 27 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsTransitionEvents = __webpack_require__(24); var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents); var CarouselItem = _react2['default'].createClass({ displayName: 'CarouselItem', propTypes: { direction: _react2['default'].PropTypes.oneOf(['prev', 'next']), onAnimateOutEnd: _react2['default'].PropTypes.func, active: _react2['default'].PropTypes.bool, animateIn: _react2['default'].PropTypes.bool, animateOut: _react2['default'].PropTypes.bool, caption: _react2['default'].PropTypes.node, index: _react2['default'].PropTypes.number }, getInitialState: function getInitialState() { return { direction: null }; }, getDefaultProps: function getDefaultProps() { return { animation: true }; }, handleAnimateOutEnd: function handleAnimateOutEnd() { if (this.props.onAnimateOutEnd && this.isMounted()) { this.props.onAnimateOutEnd(this.props.index); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.active !== nextProps.active) { this.setState({ direction: null }); } }, componentDidUpdate: function componentDidUpdate(prevProps) { if (!this.props.active && prevProps.active) { _utilsTransitionEvents2['default'].addEndEventListener(_react2['default'].findDOMNode(this), this.handleAnimateOutEnd); } if (this.props.active !== prevProps.active) { setTimeout(this.startAnimation, 20); } }, startAnimation: function startAnimation() { if (!this.isMounted()) { return; } this.setState({ direction: this.props.direction === 'prev' ? 'right' : 'left' }); }, render: function render() { var 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 _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children, this.props.caption ? this.renderCaption() : null ); }, renderCaption: function renderCaption() { return _react2['default'].createElement( 'div', { className: 'carousel-caption' }, this.props.caption ); } }); exports['default'] = CarouselItem; module.exports = exports['default']; /***/ }, /* 28 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _styleMaps = __webpack_require__(6); var _styleMaps2 = _interopRequireDefault(_styleMaps); var Col = _react2['default'].createClass({ displayName: 'Col', propTypes: { xs: _react2['default'].PropTypes.number, sm: _react2['default'].PropTypes.number, md: _react2['default'].PropTypes.number, lg: _react2['default'].PropTypes.number, xsOffset: _react2['default'].PropTypes.number, smOffset: _react2['default'].PropTypes.number, mdOffset: _react2['default'].PropTypes.number, lgOffset: _react2['default'].PropTypes.number, xsPush: _react2['default'].PropTypes.number, smPush: _react2['default'].PropTypes.number, mdPush: _react2['default'].PropTypes.number, lgPush: _react2['default'].PropTypes.number, xsPull: _react2['default'].PropTypes.number, smPull: _react2['default'].PropTypes.number, mdPull: _react2['default'].PropTypes.number, lgPull: _react2['default'].PropTypes.number, componentClass: _react2['default'].PropTypes.node.isRequired }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var ComponentClass = this.props.componentClass; var classes = {}; Object.keys(_styleMaps2['default'].SIZES).forEach(function (key) { var size = _styleMaps2['default'].SIZES[key]; var prop = size; var classPart = size + '-'; if (this.props[prop]) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Offset'; classPart = size + '-offset-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Push'; classPart = size + '-push-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } prop = size + 'Pull'; classPart = size + '-pull-'; if (this.props[prop] >= 0) { classes['col-' + classPart + this.props[prop]] = true; } }, this); return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = Col; module.exports = exports['default']; /***/ }, /* 29 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _DropdownStateMixin = __webpack_require__(30); var _DropdownStateMixin2 = _interopRequireDefault(_DropdownStateMixin); var _Button = __webpack_require__(15); var _Button2 = _interopRequireDefault(_Button); var _ButtonGroup = __webpack_require__(16); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _DropdownMenu = __webpack_require__(31); var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var DropdownButton = _react2['default'].createClass({ displayName: 'DropdownButton', mixins: [_BootstrapMixin2['default'], _DropdownStateMixin2['default']], propTypes: { pullRight: _react2['default'].PropTypes.bool, dropup: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.node, href: _react2['default'].PropTypes.string, onClick: _react2['default'].PropTypes.func, onSelect: _react2['default'].PropTypes.func, navItem: _react2['default'].PropTypes.bool, noCaret: _react2['default'].PropTypes.bool, buttonClassName: _react2['default'].PropTypes.string }, render: function render() { var renderMethod = this.props.navItem ? 'renderNavItem' : 'renderButtonGroup'; var caret = this.props.noCaret ? null : _react2['default'].createElement('span', { className: 'caret' }); return this[renderMethod]([_react2['default'].createElement( _Button2['default'], _extends({}, this.props, { ref: 'dropdownButton', className: (0, _classnames2['default'])('dropdown-toggle', this.props.buttonClassName), onClick: (0, _utilsCreateChainedFunction2['default'])(this.props.onClick, this.handleDropdownClick), key: 0, navDropdown: this.props.navItem, navItem: null, title: null, pullRight: null, dropup: null }), this.props.title, ' ', caret ), _react2['default'].createElement( _DropdownMenu2['default'], { ref: 'menu', 'aria-labelledby': this.props.id, pullRight: this.props.pullRight, key: 1 }, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderMenuItem) )]); }, renderButtonGroup: function renderButtonGroup(children) { var groupClasses = { 'open': this.state.open, 'dropup': this.props.dropup }; return _react2['default'].createElement( _ButtonGroup2['default'], { bsSize: this.props.bsSize, className: (0, _classnames2['default'])(this.props.className, groupClasses) }, children ); }, renderNavItem: function renderNavItem(children) { var classes = { 'dropdown': true, 'open': this.state.open, 'dropup': this.props.dropup }; return _react2['default'].createElement( 'li', { className: (0, _classnames2['default'])(this.props.className, classes) }, children ); }, renderMenuItem: function renderMenuItem(child, index) { // Only handle the option selection if an onSelect prop has been set on the // component or it's child, this allows a user not to pass an onSelect // handler and have the browser preform the default action. var handleOptionSelect = this.props.onSelect || child.props.onSelect ? this.handleOptionSelect : null; return (0, _react.cloneElement)(child, { // Capture onSelect events onSelect: (0, _utilsCreateChainedFunction2['default'])(child.props.onSelect, handleOptionSelect), key: child.key ? child.key : index }); }, handleDropdownClick: function handleDropdownClick(e) { e.preventDefault(); this.setDropdownState(!this.state.open); }, handleOptionSelect: function handleOptionSelect(key) { if (this.props.onSelect) { this.props.onSelect(key); } this.setDropdownState(false); } }); exports['default'] = DropdownButton; module.exports = exports['default']; /***/ }, /* 30 */ /***/ 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 _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsEventListener = __webpack_require__(12); var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener); /** * Checks whether a node is within * a root nodes tree * * @param {DOMElement} node * @param {DOMElement} root * @returns {boolean} */ function isNodeInRoot(node, root) { while (node) { if (node === root) { return true; } node = node.parentNode; } return false; } var DropdownStateMixin = { getInitialState: function getInitialState() { return { open: false }; }, setDropdownState: function setDropdownState(newState, onStateChangeComplete) { if (newState) { this.bindRootCloseHandlers(); } else { this.unbindRootCloseHandlers(); } this.setState({ open: newState }, onStateChangeComplete); }, handleDocumentKeyUp: function handleDocumentKeyUp(e) { if (e.keyCode === 27) { this.setDropdownState(false); } }, handleDocumentClick: function handleDocumentClick(e) { // If the click originated from within this component // don't do anything. if (isNodeInRoot(e.target, _react2['default'].findDOMNode(this))) { return; } this.setDropdownState(false); }, bindRootCloseHandlers: function bindRootCloseHandlers() { var doc = _utilsDomUtils2['default'].ownerDocument(this); this._onDocumentClickListener = _utilsEventListener2['default'].listen(doc, 'click', this.handleDocumentClick); this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp); }, unbindRootCloseHandlers: function unbindRootCloseHandlers() { if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } if (this._onDocumentKeyupListener) { this._onDocumentKeyupListener.remove(); } }, componentWillUnmount: function componentWillUnmount() { this.unbindRootCloseHandlers(); } }; exports['default'] = DropdownStateMixin; module.exports = exports['default']; /***/ }, /* 31 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var DropdownMenu = _react2['default'].createClass({ displayName: 'DropdownMenu', propTypes: { pullRight: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func }, render: function render() { var classes = { 'dropdown-menu': true, 'dropdown-menu-right': this.props.pullRight }; return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), role: 'menu' }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderMenuItem) ); }, renderMenuItem: function renderMenuItem(child, index) { return (0, _react.cloneElement)(child, { // Capture onSelect events onSelect: (0, _utilsCreateChainedFunction2['default'])(child.props.onSelect, this.props.onSelect), // Force special props to be transferred key: child.key ? child.key : index }); } }); exports['default'] = DropdownMenu; module.exports = exports['default']; /***/ }, /* 32 */ /***/ 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 _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); // TODO: listen for onTransitionEnd to remove el function getElementsAndSelf(root, classes) { var els = root.querySelectorAll('.' + classes.join('.')); els = [].map.call(els, function (e) { return e; }); for (var i = 0; i < classes.length; i++) { if (!root.className.match(new RegExp('\\b' + classes[i] + '\\b'))) { return els; } } els.unshift(root); return els; } exports['default'] = { _fadeIn: function _fadeIn() { var els = undefined; if (this.isMounted()) { els = getElementsAndSelf(_react2['default'].findDOMNode(this), ['fade']); if (els.length) { els.forEach(function (el) { el.className += ' in'; }); } } }, _fadeOut: function _fadeOut() { var els = getElementsAndSelf(this._fadeOutEl, ['fade', 'in']); if (els.length) { els.forEach(function (el) { el.className = el.className.replace(/\bin\b/, ''); }); } setTimeout(this._handleFadeOutEnd, 300); }, _handleFadeOutEnd: function _handleFadeOutEnd() { if (this._fadeOutEl && this._fadeOutEl.parentNode) { this._fadeOutEl.parentNode.removeChild(this._fadeOutEl); } }, componentDidMount: function componentDidMount() { if (document.querySelectorAll) { // Firefox needs delay for transition to be triggered setTimeout(this._fadeIn, 20); } }, componentWillUnmount: function componentWillUnmount() { var els = getElementsAndSelf(_react2['default'].findDOMNode(this), ['fade']), container = this.props.container && _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body; if (els.length) { this._fadeOutEl = document.createElement('div'); container.appendChild(this._fadeOutEl); this._fadeOutEl.appendChild(_react2['default'].findDOMNode(this).cloneNode(true)); // Firefox needs delay for transition to be triggered setTimeout(this._fadeOut, 20); } } }; module.exports = exports['default']; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _Static = __webpack_require__(34); var _Static2 = _interopRequireDefault(_Static); exports['default'] = { Static: _Static2['default'] }; module.exports = exports['default']; /***/ }, /* 34 */ /***/ 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; }; })(); 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _InputBase2 = __webpack_require__(19); var _InputBase3 = _interopRequireDefault(_InputBase2); var _utilsChildrenValueInputValidation = __webpack_require__(20); var _utilsChildrenValueInputValidation2 = _interopRequireDefault(_utilsChildrenValueInputValidation); var Static = (function (_InputBase) { function Static() { _classCallCheck(this, Static); if (_InputBase != null) { _InputBase.apply(this, arguments); } } _inherits(Static, _InputBase); _createClass(Static, [{ key: 'getValue', value: function getValue() { var _props = this.props; var children = _props.children; var value = _props.value; return children ? children : value; } }, { key: 'renderInput', value: function renderInput() { return _react2['default'].createElement( 'p', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'form-control-static'), ref: 'input', key: 'input' }), this.getValue() ); } }]); return Static; })(_InputBase3['default']); Static.propTypes = { value: _utilsChildrenValueInputValidation2['default'], children: _utilsChildrenValueInputValidation2['default'] }; exports['default'] = Static; module.exports = exports['default']; /***/ }, /* 35 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _styleMaps = __webpack_require__(6); var _styleMaps2 = _interopRequireDefault(_styleMaps); var Glyphicon = _react2['default'].createClass({ displayName: 'Glyphicon', mixins: [_BootstrapMixin2['default']], propTypes: { glyph: _react2['default'].PropTypes.oneOf(_styleMaps2['default'].GLYPHS).isRequired }, getDefaultProps: function getDefaultProps() { return { bsClass: 'glyphicon' }; }, render: function render() { var classes = this.getBsClassSet(); classes['glyphicon-' + this.props.glyph] = true; return _react2['default'].createElement( 'span', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = Glyphicon; module.exports = exports['default']; /***/ }, /* 36 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var Grid = _react2['default'].createClass({ displayName: 'Grid', propTypes: { fluid: _react2['default'].PropTypes.bool, componentClass: _react2['default'].PropTypes.node.isRequired }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var ComponentClass = this.props.componentClass; var className = this.props.fluid ? 'container-fluid' : 'container'; return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, className) }), this.props.children ); } }); exports['default'] = Grid; module.exports = exports['default']; /***/ }, /* 37 */ /***/ 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; desc = parent = getter = undefined; _again = false; 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; 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _InputBase2 = __webpack_require__(19); var _InputBase3 = _interopRequireDefault(_InputBase2); var _ButtonInput = __webpack_require__(17); var _ButtonInput2 = _interopRequireDefault(_ButtonInput); var _FormControls = __webpack_require__(33); var _FormControls2 = _interopRequireDefault(_FormControls); var _utilsDeprecationWarning = __webpack_require__(38); var _utilsDeprecationWarning2 = _interopRequireDefault(_utilsDeprecationWarning); var Input = (function (_InputBase) { function Input() { _classCallCheck(this, Input); if (_InputBase != null) { _InputBase.apply(this, arguments); } } _inherits(Input, _InputBase); _createClass(Input, [{ key: 'render', value: function render() { if (_ButtonInput2['default'].types.indexOf(this.props.type) > -1) { (0, _utilsDeprecationWarning2['default'])('Input type=' + this.props.type, 'ButtonInput'); return _react2['default'].createElement(_ButtonInput2['default'], this.props); } else if (this.props.type === 'static') { (0, _utilsDeprecationWarning2['default'])('Input type=static', 'StaticText'); return _react2['default'].createElement(_FormControls2['default'].Static, this.props); } return _get(Object.getPrototypeOf(Input.prototype), 'render', this).call(this); } }]); return Input; })(_InputBase3['default']); exports['default'] = Input; module.exports = exports['default']; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = deprecationWarning; function deprecationWarning(oldname, newname, link) { if (true) { if (typeof console === 'undefined' || typeof console.warn !== 'function') { return; } var message = '' + oldname + ' is deprecated. Use ' + newname + ' instead.'; console.warn(message); if (link) { console.warn('You can read more about it here ' + link); } } } module.exports = exports['default']; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { // https://www.npmjs.org/package/react-interpolate-component // TODO: Drop this in favor of es6 string interpolation '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 _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsObjectAssign = __webpack_require__(40); var _utilsObjectAssign2 = _interopRequireDefault(_utilsObjectAssign); var REGEXP = /\%\((.+?)\)s/; var Interpolate = _react2['default'].createClass({ displayName: 'Interpolate', propTypes: { format: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { component: 'span' }; }, render: function render() { var format = _utilsValidComponentChildren2['default'].hasValidComponent(this.props.children) || typeof this.props.children === 'string' ? this.props.children : this.props.format; var parent = this.props.component; var unsafe = this.props.unsafe === true; var props = (0, _utilsObjectAssign2['default'])({}, this.props); delete props.children; delete props.format; delete props.component; delete props.unsafe; if (unsafe) { var content = format.split(REGEXP).reduce(function (memo, match, index) { var html = undefined; if (index % 2 === 0) { html = match; } else { html = props[match]; delete props[match]; } if (_react2['default'].isValidElement(html)) { throw new Error('cannot interpolate a React component into unsafe text'); } memo += html; return memo; }, ''); props.dangerouslySetInnerHTML = { __html: content }; return _react2['default'].createElement(parent, props); } else { var kids = format.split(REGEXP).reduce(function (memo, match, index) { var child = undefined; if (index % 2 === 0) { if (match.length === 0) { return memo; } child = match; } else { child = props[match]; delete props[match]; } memo.push(child); return memo; }, []); return _react2['default'].createElement(parent, props, kids); } } }); exports['default'] = Interpolate; module.exports = exports['default']; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014, Facebook, Inc. * All rights reserved. * * This file contains an unmodified version of: * https://github.com/facebook/react/blob/v0.12.0/src/vendor/stubs/Object.assign.js * * This source code is licensed under the BSD-style license found here: * https://github.com/facebook/react/blob/v0.12.0/LICENSE * An additional grant of patent rights can be found here: * https://github.com/facebook/react/blob/v0.12.0/PATENTS */ // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.assign 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); 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; } exports['default'] = assign; module.exports = exports['default']; /***/ }, /* 41 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var Jumbotron = _react2['default'].createClass({ displayName: 'Jumbotron', render: function render() { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'jumbotron') }), this.props.children ); } }); exports['default'] = Jumbotron; module.exports = exports['default']; /***/ }, /* 42 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var Label = _react2['default'].createClass({ displayName: 'Label', mixins: [_BootstrapMixin2['default']], getDefaultProps: function getDefaultProps() { return { bsClass: 'label', bsStyle: 'default' }; }, render: function render() { var classes = this.getBsClassSet(); return _react2['default'].createElement( 'span', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = Label; module.exports = exports['default']; /***/ }, /* 43 */ /***/ 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; }; })(); 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var ListGroup = (function (_React$Component) { function ListGroup() { _classCallCheck(this, ListGroup); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(ListGroup, _React$Component); _createClass(ListGroup, [{ key: 'render', value: function render() { var _this = this; var items = _utilsValidComponentChildren2['default'].map(this.props.children, function (item, index) { return (0, _react.cloneElement)(item, { key: item.key ? item.key : index }); }); var childrenAnchors = false; if (!this.props.children) { return this.renderDiv(items); } else if (_react2['default'].Children.count(this.props.children) === 1 && !Array.isArray(this.props.children)) { var child = this.props.children; childrenAnchors = this.isAnchor(child.props); } else { childrenAnchors = Array.prototype.some.call(this.props.children, function (child) { return !Array.isArray(child) ? _this.isAnchor(child.props) : Array.prototype.some.call(child, function (subChild) { return _this.isAnchor(subChild.props); }); }); } if (childrenAnchors) { return this.renderDiv(items); } else { return this.renderUL(items); } } }, { key: 'isAnchor', value: function isAnchor(props) { return props.href || props.onClick; } }, { key: 'renderUL', value: function renderUL(items) { var listItems = _utilsValidComponentChildren2['default'].map(items, function (item, index) { return (0, _react.cloneElement)(item, { listItem: true }); }); return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'list-group') }), listItems ); } }, { key: 'renderDiv', value: function renderDiv(items) { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'list-group') }), items ); } }]); return ListGroup; })(_react2['default'].Component); ListGroup.propTypes = { className: _react2['default'].PropTypes.string, id: _react2['default'].PropTypes.string }; exports['default'] = ListGroup; module.exports = exports['default']; /***/ }, /* 44 */ /***/ 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 _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var ListGroupItem = _react2['default'].createClass({ displayName: 'ListGroupItem', mixins: [_BootstrapMixin2['default']], propTypes: { bsStyle: _react2['default'].PropTypes.oneOf(['danger', 'info', 'success', 'warning']), className: _react2['default'].PropTypes.string, active: _react2['default'].PropTypes.any, disabled: _react2['default'].PropTypes.any, header: _react2['default'].PropTypes.node, listItem: _react2['default'].PropTypes.bool, onClick: _react2['default'].PropTypes.func, eventKey: _react2['default'].PropTypes.any, href: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { bsClass: 'list-group-item' }; }, render: function render() { var classes = this.getBsClassSet(); classes.active = this.props.active; classes.disabled = this.props.disabled; if (this.props.href || this.props.onClick) { return this.renderAnchor(classes); } else if (this.props.listItem) { return this.renderLi(classes); } else { return this.renderSpan(classes); } }, renderLi: function renderLi(classes) { return _react2['default'].createElement( 'li', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }, renderAnchor: function renderAnchor(classes) { return _react2['default'].createElement( 'a', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }, renderSpan: function renderSpan(classes) { return _react2['default'].createElement( 'span', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.header ? this.renderStructuredContent() : this.props.children ); }, renderStructuredContent: function renderStructuredContent() { var header = undefined; if (_react2['default'].isValidElement(this.props.header)) { header = (0, _react.cloneElement)(this.props.header, { key: 'header', className: (0, _classnames2['default'])(this.props.header.props.className, 'list-group-item-heading') }); } else { header = _react2['default'].createElement( 'h4', { key: 'header', className: 'list-group-item-heading' }, this.props.header ); } var content = _react2['default'].createElement( 'p', { key: 'content', className: 'list-group-item-text' }, this.props.children ); return [header, content]; } }); exports['default'] = ListGroupItem; module.exports = exports['default']; /***/ }, /* 45 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var MenuItem = _react2['default'].createClass({ displayName: 'MenuItem', propTypes: { header: _react2['default'].PropTypes.bool, divider: _react2['default'].PropTypes.bool, href: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string, onSelect: _react2['default'].PropTypes.func, eventKey: _react2['default'].PropTypes.any, active: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { href: '#', active: false }; }, handleClick: function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } }, renderAnchor: function renderAnchor() { return _react2['default'].createElement( 'a', { onClick: this.handleClick, href: this.props.href, target: this.props.target, title: this.props.title, tabIndex: '-1' }, this.props.children ); }, render: function render() { var classes = { 'dropdown-header': this.props.header, 'divider': this.props.divider, 'active': this.props.active }; var children = null; if (this.props.header) { children = this.props.children; } else if (!this.props.divider) { children = this.renderAnchor(); } return _react2['default'].createElement( 'li', _extends({}, this.props, { role: 'presentation', title: null, href: null, className: (0, _classnames2['default'])(this.props.className, classes) }), children ); } }); exports['default'] = MenuItem; module.exports = exports['default']; /***/ }, /* 46 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _FadeMixin = __webpack_require__(32); var _FadeMixin2 = _interopRequireDefault(_FadeMixin); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsEventListener = __webpack_require__(12); var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener); // TODO: // - aria-labelledby // - Add `modal-body` div if only one child passed in that doesn't already have it // - Tests var Modal = _react2['default'].createClass({ displayName: 'Modal', mixins: [_BootstrapMixin2['default'], _FadeMixin2['default']], propTypes: { title: _react2['default'].PropTypes.node, backdrop: _react2['default'].PropTypes.oneOf(['static', true, false]), keyboard: _react2['default'].PropTypes.bool, closeButton: _react2['default'].PropTypes.bool, animation: _react2['default'].PropTypes.bool, onRequestHide: _react2['default'].PropTypes.func.isRequired, dialogClassName: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { bsClass: 'modal', backdrop: true, keyboard: true, animation: true, closeButton: true }; }, render: function render() { var modalStyle = { display: 'block' }; var dialogClasses = this.getBsClassSet(); delete dialogClasses.modal; dialogClasses['modal-dialog'] = true; var classes = { modal: true, fade: this.props.animation, 'in': !this.props.animation }; var modal = _react2['default'].createElement( 'div', _extends({}, this.props, { title: null, tabIndex: '-1', role: 'dialog', style: modalStyle, className: (0, _classnames2['default'])(this.props.className, classes), onClick: this.props.backdrop === true ? this.handleBackdropClick : null, ref: 'modal' }), _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(this.props.dialogClassName, dialogClasses) }, _react2['default'].createElement( 'div', { className: 'modal-content' }, this.props.title ? this.renderHeader() : null, this.props.children ) ) ); return this.props.backdrop ? this.renderBackdrop(modal) : modal; }, renderBackdrop: function renderBackdrop(modal) { var classes = { 'modal-backdrop': true, fade: this.props.animation, 'in': !this.props.animation }; var onClick = this.props.backdrop === true ? this.handleBackdropClick : null; return _react2['default'].createElement( 'div', null, _react2['default'].createElement('div', { className: (0, _classnames2['default'])(classes), ref: 'backdrop', onClick: onClick }), modal ); }, renderHeader: function renderHeader() { var closeButton = undefined; if (this.props.closeButton) { closeButton = _react2['default'].createElement( 'button', { type: 'button', className: 'close', 'aria-hidden': 'true', onClick: this.props.onRequestHide }, '×' ); } return _react2['default'].createElement( 'div', { className: 'modal-header' }, closeButton, this.renderTitle() ); }, renderTitle: function renderTitle() { return _react2['default'].isValidElement(this.props.title) ? this.props.title : _react2['default'].createElement( 'h4', { className: 'modal-title' }, this.props.title ); }, iosClickHack: function iosClickHack() { // IOS only allows click events to be delegated to the document on elements // it considers 'clickable' - anchors, buttons, etc. We fake a click handler on the // DOM nodes themselves. Remove if handled by React: https://github.com/facebook/react/issues/1169 _react2['default'].findDOMNode(this.refs.modal).onclick = function () {}; _react2['default'].findDOMNode(this.refs.backdrop).onclick = function () {}; }, componentDidMount: function componentDidMount() { this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(_utilsDomUtils2['default'].ownerDocument(this), 'keyup', this.handleDocumentKeyUp); var container = this.props.container && _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body; container.className += container.className.length ? ' modal-open' : 'modal-open'; this.focusModalContent(); if (this.props.backdrop) { this.iosClickHack(); } }, componentDidUpdate: function componentDidUpdate(prevProps) { if (this.props.backdrop && this.props.backdrop !== prevProps.backdrop) { this.iosClickHack(); } }, componentWillUnmount: function componentWillUnmount() { this._onDocumentKeyupListener.remove(); var container = this.props.container && _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body; container.className = container.className.replace(/ ?modal-open/, ''); this.restoreLastFocus(); }, handleBackdropClick: function handleBackdropClick(e) { if (e.target !== e.currentTarget) { return; } this.props.onRequestHide(); }, handleDocumentKeyUp: function handleDocumentKeyUp(e) { if (this.props.keyboard && e.keyCode === 27) { this.props.onRequestHide(); } }, focusModalContent: function focusModalContent() { this.lastFocus = _utilsDomUtils2['default'].ownerDocument(this).activeElement; var modalContent = _react2['default'].findDOMNode(this.refs.modal); modalContent.focus(); }, restoreLastFocus: function restoreLastFocus() { if (this.lastFocus) { this.lastFocus.focus(); this.lastFocus = null; } } }); exports['default'] = Modal; module.exports = exports['default']; /***/ }, /* 47 */ /***/ 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 _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _CollapsibleMixin = __webpack_require__(23); var _CollapsibleMixin2 = _interopRequireDefault(_CollapsibleMixin); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var Nav = _react2['default'].createClass({ displayName: 'Nav', mixins: [_BootstrapMixin2['default'], _CollapsibleMixin2['default']], propTypes: { activeHref: _react2['default'].PropTypes.string, activeKey: _react2['default'].PropTypes.any, bsStyle: _react2['default'].PropTypes.oneOf(['tabs', 'pills']), stacked: _react2['default'].PropTypes.bool, justified: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, collapsible: _react2['default'].PropTypes.bool, expanded: _react2['default'].PropTypes.bool, navbar: _react2['default'].PropTypes.bool, eventKey: _react2['default'].PropTypes.any, pullRight: _react2['default'].PropTypes.bool, right: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { bsClass: 'nav' }; }, getCollapsibleDOMNode: function getCollapsibleDOMNode() { return _react2['default'].findDOMNode(this); }, getCollapsibleDimensionValue: function getCollapsibleDimensionValue() { var node = _react2['default'].findDOMNode(this.refs.ul), height = node.offsetHeight, computedStyles = _utilsDomUtils2['default'].getComputedStyles(node); return height + parseInt(computedStyles.marginTop, 10) + parseInt(computedStyles.marginBottom, 10); }, render: function render() { var classes = this.props.collapsible ? this.getCollapsibleClassSet('navbar-collapse') : null; if (this.props.navbar && !this.props.collapsible) { return this.renderUl(); } return _react2['default'].createElement( 'nav', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.renderUl() ); }, renderUl: function renderUl() { var classes = this.getBsClassSet(); classes['nav-stacked'] = this.props.stacked; classes['nav-justified'] = this.props.justified; classes['navbar-nav'] = this.props.navbar; classes['pull-right'] = this.props.pullRight; classes['navbar-right'] = this.props.right; return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), ref: 'ul' }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderNavItem) ); }, getChildActiveProp: function getChildActiveProp(child) { if (child.props.active) { return true; } if (this.props.activeKey != null) { if (child.props.eventKey === this.props.activeKey) { return true; } } if (this.props.activeHref != null) { if (child.props.href === this.props.activeHref) { return true; } } return child.props.active; }, renderNavItem: function renderNavItem(child, index) { return (0, _react.cloneElement)(child, { active: this.getChildActiveProp(child), activeKey: this.props.activeKey, activeHref: this.props.activeHref, onSelect: (0, _utilsCreateChainedFunction2['default'])(child.props.onSelect, this.props.onSelect), key: child.key ? child.key : index, navItem: true }); } }); exports['default'] = Nav; module.exports = exports['default']; /***/ }, /* 48 */ /***/ 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 _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var Navbar = _react2['default'].createClass({ displayName: 'Navbar', mixins: [_BootstrapMixin2['default']], propTypes: { fixedTop: _react2['default'].PropTypes.bool, fixedBottom: _react2['default'].PropTypes.bool, staticTop: _react2['default'].PropTypes.bool, inverse: _react2['default'].PropTypes.bool, fluid: _react2['default'].PropTypes.bool, role: _react2['default'].PropTypes.string, componentClass: _react2['default'].PropTypes.node.isRequired, brand: _react2['default'].PropTypes.node, toggleButton: _react2['default'].PropTypes.node, toggleNavKey: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.number]), onToggle: _react2['default'].PropTypes.func, navExpanded: _react2['default'].PropTypes.bool, defaultNavExpanded: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { bsClass: 'navbar', bsStyle: 'default', role: 'navigation', componentClass: 'nav' }; }, getInitialState: function getInitialState() { return { navExpanded: this.props.defaultNavExpanded }; }, shouldComponentUpdate: function shouldComponentUpdate() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleToggle: function handleToggle() { if (this.props.onToggle) { this._isChanging = true; this.props.onToggle(); this._isChanging = false; } this.setState({ navExpanded: !this.state.navExpanded }); }, isNavExpanded: function isNavExpanded() { return this.props.navExpanded != null ? this.props.navExpanded : this.state.navExpanded; }, render: function render() { var classes = this.getBsClassSet(); var ComponentClass = this.props.componentClass; classes['navbar-fixed-top'] = this.props.fixedTop; classes['navbar-fixed-bottom'] = this.props.fixedBottom; classes['navbar-static-top'] = this.props.staticTop; classes['navbar-inverse'] = this.props.inverse; return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), _react2['default'].createElement( 'div', { className: this.props.fluid ? 'container-fluid' : 'container' }, this.props.brand || this.props.toggleButton || this.props.toggleNavKey != null ? this.renderHeader() : null, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderChild) ) ); }, renderChild: function renderChild(child, index) { return (0, _react.cloneElement)(child, { navbar: true, collapsible: this.props.toggleNavKey != null && this.props.toggleNavKey === child.props.eventKey, expanded: this.props.toggleNavKey != null && this.props.toggleNavKey === child.props.eventKey && this.isNavExpanded(), key: child.key ? child.key : index }); }, renderHeader: function renderHeader() { var brand = undefined; if (this.props.brand) { if (_react2['default'].isValidElement(this.props.brand)) { brand = (0, _react.cloneElement)(this.props.brand, { className: (0, _classnames2['default'])(this.props.brand.props.className, 'navbar-brand') }); } else { brand = _react2['default'].createElement( 'span', { className: 'navbar-brand' }, this.props.brand ); } } return _react2['default'].createElement( 'div', { className: 'navbar-header' }, brand, this.props.toggleButton || this.props.toggleNavKey != null ? this.renderToggleButton() : null ); }, renderToggleButton: function renderToggleButton() { var children = undefined; if (_react2['default'].isValidElement(this.props.toggleButton)) { return (0, _react.cloneElement)(this.props.toggleButton, { className: (0, _classnames2['default'])(this.props.toggleButton.props.className, 'navbar-toggle'), onClick: (0, _utilsCreateChainedFunction2['default'])(this.handleToggle, this.props.toggleButton.props.onClick) }); } children = this.props.toggleButton != null ? this.props.toggleButton : [_react2['default'].createElement( 'span', { className: 'sr-only', key: 0 }, 'Toggle navigation' ), _react2['default'].createElement('span', { className: 'icon-bar', key: 1 }), _react2['default'].createElement('span', { className: 'icon-bar', key: 2 }), _react2['default'].createElement('span', { className: 'icon-bar', key: 3 })]; return _react2['default'].createElement( 'button', { className: 'navbar-toggle', type: 'button', onClick: this.handleToggle }, children ); } }); exports['default'] = Navbar; module.exports = exports['default']; /***/ }, /* 49 */ /***/ 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 }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var NavItem = _react2['default'].createClass({ displayName: 'NavItem', mixins: [_BootstrapMixin2['default']], propTypes: { onSelect: _react2['default'].PropTypes.func, active: _react2['default'].PropTypes.bool, disabled: _react2['default'].PropTypes.bool, href: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.node, eventKey: _react2['default'].PropTypes.any, target: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { href: '#' }; }, render: function render() { var _props = this.props; var disabled = _props.disabled; var active = _props.active; var href = _props.href; var title = _props.title; var target = _props.target; var children = _props.children; var props = _objectWithoutProperties(_props, ['disabled', 'active', 'href', 'title', 'target', 'children']); // eslint-disable-line object-shorthand var classes = { active: active, disabled: disabled }; var linkProps = { href: href, title: title, target: target, onClick: this.handleClick, ref: 'anchor' }; if (href === '#') { linkProps.role = 'button'; } return _react2['default'].createElement( 'li', _extends({}, props, { className: (0, _classnames2['default'])(props.className, classes) }), _react2['default'].createElement( 'a', linkProps, children ) ); }, handleClick: function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); exports['default'] = NavItem; module.exports = exports['default']; /***/ }, /* 50 */ /***/ 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 _OverlayMixin = __webpack_require__(51); var _OverlayMixin2 = _interopRequireDefault(_OverlayMixin); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsCreateContextWrapper = __webpack_require__(52); var _utilsCreateContextWrapper2 = _interopRequireDefault(_utilsCreateContextWrapper); var ModalTrigger = _react2['default'].createClass({ displayName: 'ModalTrigger', mixins: [_OverlayMixin2['default']], propTypes: { modal: _react2['default'].PropTypes.node.isRequired }, getInitialState: function getInitialState() { return { isOverlayShown: false }; }, show: function show() { this.setState({ isOverlayShown: true }); }, hide: function hide() { this.setState({ isOverlayShown: false }); }, toggle: function toggle() { this.setState({ isOverlayShown: !this.state.isOverlayShown }); }, renderOverlay: function renderOverlay() { if (!this.state.isOverlayShown) { return _react2['default'].createElement('span', null); } return (0, _react.cloneElement)(this.props.modal, { onRequestHide: this.hide }); }, render: function render() { var child = _react2['default'].Children.only(this.props.children); var props = {}; props.onClick = (0, _utilsCreateChainedFunction2['default'])(child.props.onClick, this.toggle); props.onMouseOver = (0, _utilsCreateChainedFunction2['default'])(child.props.onMouseOver, this.props.onMouseOver); props.onMouseOut = (0, _utilsCreateChainedFunction2['default'])(child.props.onMouseOut, this.props.onMouseOut); props.onFocus = (0, _utilsCreateChainedFunction2['default'])(child.props.onFocus, this.props.onFocus); props.onBlur = (0, _utilsCreateChainedFunction2['default'])(child.props.onBlur, this.props.onBlur); return (0, _react.cloneElement)(child, props); } }); /** * Creates a new ModalTrigger class that forwards the relevant context * * This static method should only be called at the module level, instead of in * e.g. a render() method, because it's expensive to create new classes. * * For example, you would want to have: * * > export default ModalTrigger.withContext({ * > myContextKey: React.PropTypes.object * > }); * * and import this when needed. */ ModalTrigger.withContext = (0, _utilsCreateContextWrapper2['default'])(ModalTrigger, 'modal'); exports['default'] = ModalTrigger; module.exports = exports['default']; /***/ }, /* 51 */ /***/ 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 _utilsCustomPropTypes = __webpack_require__(7); var _utilsCustomPropTypes2 = _interopRequireDefault(_utilsCustomPropTypes); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); exports['default'] = { propTypes: { container: _utilsCustomPropTypes2['default'].mountable }, componentWillUnmount: function componentWillUnmount() { this._unrenderOverlay(); if (this._overlayTarget) { this.getContainerDOMNode().removeChild(this._overlayTarget); this._overlayTarget = null; } }, componentDidUpdate: function componentDidUpdate() { this._renderOverlay(); }, componentDidMount: function componentDidMount() { this._renderOverlay(); }, _mountOverlayTarget: function _mountOverlayTarget() { this._overlayTarget = document.createElement('div'); this.getContainerDOMNode().appendChild(this._overlayTarget); }, _renderOverlay: function _renderOverlay() { if (!this._overlayTarget) { this._mountOverlayTarget(); } var overlay = this.renderOverlay(); // Save reference to help testing if (overlay !== null) { this._overlayInstance = _react2['default'].render(overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); } }, _unrenderOverlay: function _unrenderOverlay() { _react2['default'].unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; }, getOverlayDOMNode: function getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return _react2['default'].findDOMNode(this._overlayInstance); } return null; }, getContainerDOMNode: function getContainerDOMNode() { return _react2['default'].findDOMNode(this.props.container) || _utilsDomUtils2['default'].ownerDocument(this).body; } }; module.exports = exports['default']; /***/ }, /* 52 */ /***/ 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; }; })(); exports['default'] = createContextWrapper; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); /** * Creates new trigger class that injects context into overlay. */ function createContextWrapper(Trigger, propName) { return function (contextTypes) { var ContextWrapper = (function (_React$Component) { function ContextWrapper() { _classCallCheck(this, ContextWrapper); if (_React$Component != null) { _React$Component.apply(this, arguments); } } _inherits(ContextWrapper, _React$Component); _createClass(ContextWrapper, [{ key: 'getChildContext', value: function getChildContext() { return this.props.context; } }, { key: 'render', value: function render() { // Strip injected props from below. var _props = this.props; var wrapped = _props.wrapped; var props = _objectWithoutProperties(_props, ['wrapped']); // eslint-disable-line object-shorthand delete props.context; return _react2['default'].cloneElement(wrapped, props); } }]); return ContextWrapper; })(_react2['default'].Component); ContextWrapper.childContextTypes = contextTypes; var TriggerWithContext = (function () { function TriggerWithContext() { _classCallCheck(this, TriggerWithContext); } _createClass(TriggerWithContext, [{ key: 'render', value: function render() { var props = _extends({}, this.props); props[propName] = this.getWrappedOverlay(); return _react2['default'].createElement( Trigger, props, this.props.children ); } }, { key: 'getWrappedOverlay', value: function getWrappedOverlay() { return _react2['default'].createElement(ContextWrapper, { context: this.context, wrapped: this.props[propName] }); } }]); return TriggerWithContext; })(); TriggerWithContext.contextTypes = contextTypes; return TriggerWithContext; }; } module.exports = exports['default']; /***/ }, /* 53 */ /***/ 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 _OverlayMixin = __webpack_require__(51); var _OverlayMixin2 = _interopRequireDefault(_OverlayMixin); var _RootCloseWrapper = __webpack_require__(54); var _RootCloseWrapper2 = _interopRequireDefault(_RootCloseWrapper); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _utilsCreateContextWrapper = __webpack_require__(52); var _utilsCreateContextWrapper2 = _interopRequireDefault(_utilsCreateContextWrapper); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsObjectAssign = __webpack_require__(40); var _utilsObjectAssign2 = _interopRequireDefault(_utilsObjectAssign); /** * Check if value one is inside or equal to the of value * * @param {string} one * @param {string|array} of * @returns {boolean} */ function isOneOf(one, of) { if (Array.isArray(of)) { return of.indexOf(one) >= 0; } return one === of; } var OverlayTrigger = _react2['default'].createClass({ displayName: 'OverlayTrigger', mixins: [_OverlayMixin2['default']], propTypes: { trigger: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.oneOf(['manual', 'click', 'hover', 'focus']), _react2['default'].PropTypes.arrayOf(_react2['default'].PropTypes.oneOf(['click', 'hover', 'focus']))]), placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']), delay: _react2['default'].PropTypes.number, delayShow: _react2['default'].PropTypes.number, delayHide: _react2['default'].PropTypes.number, defaultOverlayShown: _react2['default'].PropTypes.bool, overlay: _react2['default'].PropTypes.node.isRequired, containerPadding: _react2['default'].PropTypes.number, rootClose: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { placement: 'right', trigger: ['hover', 'focus'], containerPadding: 0 }; }, getInitialState: function getInitialState() { return { isOverlayShown: this.props.defaultOverlayShown == null ? false : this.props.defaultOverlayShown, overlayLeft: null, overlayTop: null, arrowOffsetLeft: null, arrowOffsetTop: null }; }, show: function show() { this.setState({ isOverlayShown: true }, function () { this.updateOverlayPosition(); }); }, hide: function hide() { this.setState({ isOverlayShown: false }); }, toggle: function toggle() { if (this.state.isOverlayShown) { this.hide(); } else { this.show(); } }, renderOverlay: function renderOverlay() { if (!this.state.isOverlayShown) { return _react2['default'].createElement('span', null); } var overlay = (0, _react.cloneElement)(this.props.overlay, { onRequestHide: this.hide, placement: this.props.placement, positionLeft: this.state.overlayLeft, positionTop: this.state.overlayTop, arrowOffsetLeft: this.state.arrowOffsetLeft, arrowOffsetTop: this.state.arrowOffsetTop }); if (this.props.rootClose) { return _react2['default'].createElement( _RootCloseWrapper2['default'], { onRootClose: this.hide }, overlay ); } else { return overlay; } }, render: function render() { var child = _react2['default'].Children.only(this.props.children); if (this.props.trigger === 'manual') { return child; } var props = {}; props.onClick = (0, _utilsCreateChainedFunction2['default'])(child.props.onClick, this.props.onClick); if (isOneOf('click', this.props.trigger)) { props.onClick = (0, _utilsCreateChainedFunction2['default'])(this.toggle, props.onClick); } if (isOneOf('hover', this.props.trigger)) { props.onMouseOver = (0, _utilsCreateChainedFunction2['default'])(this.handleDelayedShow, this.props.onMouseOver); props.onMouseOut = (0, _utilsCreateChainedFunction2['default'])(this.handleDelayedHide, this.props.onMouseOut); } if (isOneOf('focus', this.props.trigger)) { props.onFocus = (0, _utilsCreateChainedFunction2['default'])(this.handleDelayedShow, this.props.onFocus); props.onBlur = (0, _utilsCreateChainedFunction2['default'])(this.handleDelayedHide, this.props.onBlur); } return (0, _react.cloneElement)(child, props); }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this._hoverDelay); }, componentDidMount: function componentDidMount() { if (this.props.defaultOverlayShown) { this.updateOverlayPosition(); } }, handleDelayedShow: function handleDelayedShow() { if (this._hoverDelay != null) { clearTimeout(this._hoverDelay); this._hoverDelay = null; return; } var delay = this.props.delayShow != null ? this.props.delayShow : this.props.delay; if (!delay) { this.show(); return; } this._hoverDelay = setTimeout((function () { this._hoverDelay = null; this.show(); }).bind(this), delay); }, handleDelayedHide: function handleDelayedHide() { if (this._hoverDelay != null) { clearTimeout(this._hoverDelay); this._hoverDelay = null; return; } var delay = this.props.delayHide != null ? this.props.delayHide : this.props.delay; if (!delay) { this.hide(); return; } this._hoverDelay = setTimeout((function () { this._hoverDelay = null; this.hide(); }).bind(this), delay); }, updateOverlayPosition: function updateOverlayPosition() { if (!this.isMounted()) { return; } this.setState(this.calcOverlayPosition()); }, calcOverlayPosition: function calcOverlayPosition() { var childOffset = this.getPosition(); var overlayNode = this.getOverlayDOMNode(); var overlayHeight = overlayNode.offsetHeight; var overlayWidth = overlayNode.offsetWidth; var placement = this.props.placement; var overlayLeft = undefined, overlayTop = undefined, arrowOffsetLeft = undefined, arrowOffsetTop = undefined; if (placement === 'left' || placement === 'right') { overlayTop = childOffset.top + (childOffset.height - overlayHeight) / 2; if (placement === 'left') { overlayLeft = childOffset.left - overlayWidth; } else { overlayLeft = childOffset.left + childOffset.width; } var topDelta = this._getTopDelta(overlayTop, overlayHeight); overlayTop += topDelta; arrowOffsetTop = 50 * (1 - 2 * topDelta / overlayHeight) + '%'; arrowOffsetLeft = null; } else if (placement === 'top' || placement === 'bottom') { overlayLeft = childOffset.left + (childOffset.width - overlayWidth) / 2; if (placement === 'top') { overlayTop = childOffset.top - overlayHeight; } else { overlayTop = childOffset.top + childOffset.height; } var leftDelta = this._getLeftDelta(overlayLeft, overlayWidth); overlayLeft += leftDelta; arrowOffsetLeft = 50 * (1 - 2 * leftDelta / overlayWidth) + '%'; arrowOffsetTop = null; } else { throw new Error('calcOverlayPosition(): No such placement of "' + this.props.placement + '" found.'); } return { overlayLeft: overlayLeft, overlayTop: overlayTop, arrowOffsetLeft: arrowOffsetLeft, arrowOffsetTop: arrowOffsetTop }; }, _getTopDelta: function _getTopDelta(top, overlayHeight) { var containerDimensions = this._getContainerDimensions(); var containerScroll = containerDimensions.scroll; var containerHeight = containerDimensions.height; var padding = this.props.containerPadding; var topEdgeOffset = top - padding - containerScroll; var bottomEdgeOffset = top + padding - containerScroll + overlayHeight; if (topEdgeOffset < 0) { return -topEdgeOffset; } else if (bottomEdgeOffset > containerHeight) { return containerHeight - bottomEdgeOffset; } else { return 0; } }, _getLeftDelta: function _getLeftDelta(left, overlayWidth) { var containerDimensions = this._getContainerDimensions(); var containerWidth = containerDimensions.width; var padding = this.props.containerPadding; var leftEdgeOffset = left - padding; var rightEdgeOffset = left + padding + overlayWidth; if (leftEdgeOffset < 0) { return -leftEdgeOffset; } else if (rightEdgeOffset > containerWidth) { return containerWidth - rightEdgeOffset; } else { return 0; } }, _getContainerDimensions: function _getContainerDimensions() { var containerNode = this.getContainerDOMNode(); var width = undefined, height = undefined, scroll = undefined; if (containerNode.tagName === 'BODY') { width = window.innerWidth; height = window.innerHeight; scroll = _utilsDomUtils2['default'].ownerDocument(containerNode).documentElement.scrollTop || containerNode.scrollTop; } else { width = containerNode.offsetWidth; height = containerNode.offsetHeight; scroll = containerNode.scrollTop; } return { width: width, height: height, scroll: scroll }; }, getPosition: function getPosition() { var node = _react2['default'].findDOMNode(this); var container = this.getContainerDOMNode(); var offset = container.tagName === 'BODY' ? _utilsDomUtils2['default'].getOffset(node) : _utilsDomUtils2['default'].getPosition(node, container); return (0, _utilsObjectAssign2['default'])({}, offset, { height: node.offsetHeight, width: node.offsetWidth }); } }); /** * Creates a new OverlayTrigger class that forwards the relevant context * * This static method should only be called at the module level, instead of in * e.g. a render() method, because it's expensive to create new classes. * * For example, you would want to have: * * > export default OverlayTrigger.withContext({ * > myContextKey: React.PropTypes.object * > }); * * and import this when needed. */ OverlayTrigger.withContext = (0, _utilsCreateContextWrapper2['default'])(OverlayTrigger, 'overlay'); exports['default'] = OverlayTrigger; module.exports = exports['default']; /***/ }, /* 54 */ /***/ 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; desc = parent = getter = undefined; _again = false; 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; 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) subClass.__proto__ = superClass; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _utilsDomUtils = __webpack_require__(11); var _utilsDomUtils2 = _interopRequireDefault(_utilsDomUtils); var _utilsEventListener = __webpack_require__(12); var _utilsEventListener2 = _interopRequireDefault(_utilsEventListener); // TODO: Merge this logic with dropdown logic once #526 is done. /** * Checks whether a node is within * a root nodes tree * * @param {DOMElement} node * @param {DOMElement} root * @returns {boolean} */ function isNodeInRoot(node, root) { while (node) { if (node === root) { return true; } node = node.parentNode; } return false; } var RootCloseWrapper = (function (_React$Component) { function RootCloseWrapper(props) { _classCallCheck(this, RootCloseWrapper); _get(Object.getPrototypeOf(RootCloseWrapper.prototype), 'constructor', this).call(this, props); this.handleDocumentClick = this.handleDocumentClick.bind(this); this.handleDocumentKeyUp = this.handleDocumentKeyUp.bind(this); } _inherits(RootCloseWrapper, _React$Component); _createClass(RootCloseWrapper, [{ key: 'bindRootCloseHandlers', value: function bindRootCloseHandlers() { var doc = _utilsDomUtils2['default'].ownerDocument(this); this._onDocumentClickListener = _utilsEventListener2['default'].listen(doc, 'click', this.handleDocumentClick); this._onDocumentKeyupListener = _utilsEventListener2['default'].listen(doc, 'keyup', this.handleDocumentKeyUp); } }, { key: 'handleDocumentClick', value: function handleDocumentClick(e) { // If the click originated from within this component, don't do anything. if (isNodeInRoot(e.target, _react2['default'].findDOMNode(this))) { return; } this.props.onRootClose(); } }, { key: 'handleDocumentKeyUp', value: function handleDocumentKeyUp(e) { if (e.keyCode === 27) { this.props.onRootClose(); } } }, { key: 'unbindRootCloseHandlers', value: function unbindRootCloseHandlers() { if (this._onDocumentClickListener) { this._onDocumentClickListener.remove(); } if (this._onDocumentKeyupListener) { this._onDocumentKeyupListener.remove(); } } }, { key: 'componentDidMount', value: function componentDidMount() { this.bindRootCloseHandlers(); } }, { key: 'render', value: function render() { return _react2['default'].Children.only(this.props.children); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { this.unbindRootCloseHandlers(); } }]); return RootCloseWrapper; })(_react2['default'].Component); exports['default'] = RootCloseWrapper; RootCloseWrapper.propTypes = { onRootClose: _react2['default'].PropTypes.func.isRequired }; module.exports = exports['default']; /***/ }, /* 55 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var PageHeader = _react2['default'].createClass({ displayName: 'PageHeader', render: function render() { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'page-header') }), _react2['default'].createElement( 'h1', null, this.props.children ) ); } }); exports['default'] = PageHeader; module.exports = exports['default']; /***/ }, /* 56 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _CollapsibleMixin = __webpack_require__(23); var _CollapsibleMixin2 = _interopRequireDefault(_CollapsibleMixin); var Panel = _react2['default'].createClass({ displayName: 'Panel', mixins: [_BootstrapMixin2['default'], _CollapsibleMixin2['default']], propTypes: { collapsible: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, header: _react2['default'].PropTypes.node, id: _react2['default'].PropTypes.string, footer: _react2['default'].PropTypes.node, eventKey: _react2['default'].PropTypes.any }, getDefaultProps: function getDefaultProps() { return { bsClass: 'panel', bsStyle: 'default' }; }, handleSelect: function handleSelect(e) { e.selected = true; if (this.props.onSelect) { this.props.onSelect(e, this.props.eventKey); } else { e.preventDefault(); } if (e.selected) { this.handleToggle(); } }, handleToggle: function handleToggle() { this.setState({ expanded: !this.state.expanded }); }, getCollapsibleDimensionValue: function getCollapsibleDimensionValue() { return _react2['default'].findDOMNode(this.refs.panel).scrollHeight; }, getCollapsibleDOMNode: function getCollapsibleDOMNode() { if (!this.isMounted() || !this.refs || !this.refs.panel) { return null; } return _react2['default'].findDOMNode(this.refs.panel); }, render: function render() { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, this.getBsClassSet()), id: this.props.collapsible ? null : this.props.id, onSelect: null }), this.renderHeading(), this.props.collapsible ? this.renderCollapsibleBody() : this.renderBody(), this.renderFooter() ); }, renderCollapsibleBody: function renderCollapsibleBody() { var collapseClass = this.prefixClass('collapse'); return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])(this.getCollapsibleClassSet(collapseClass)), id: this.props.id, ref: 'panel', 'aria-expanded': this.isExpanded() ? 'true' : 'false' }, this.renderBody() ); }, renderBody: function renderBody() { var allChildren = this.props.children; var bodyElements = []; var panelBodyChildren = []; var bodyClass = this.prefixClass('body'); function getProps() { return { key: bodyElements.length }; } function addPanelChild(child) { bodyElements.push((0, _react.cloneElement)(child, getProps())); } function addPanelBody(children) { bodyElements.push(_react2['default'].createElement( 'div', _extends({ className: bodyClass }, getProps()), children )); } function maybeRenderPanelBody() { if (panelBodyChildren.length === 0) { return; } addPanelBody(panelBodyChildren); panelBodyChildren = []; } // Handle edge cases where we should not iterate through children. if (!Array.isArray(allChildren) || allChildren.length === 0) { if (this.shouldRenderFill(allChildren)) { addPanelChild(allChildren); } else { addPanelBody(allChildren); } } else { allChildren.forEach((function (child) { if (this.shouldRenderFill(child)) { maybeRenderPanelBody(); // Separately add the filled element. addPanelChild(child); } else { panelBodyChildren.push(child); } }).bind(this)); maybeRenderPanelBody(); } return bodyElements; }, shouldRenderFill: function shouldRenderFill(child) { return _react2['default'].isValidElement(child) && child.props.fill != null; }, renderHeading: function renderHeading() { var header = this.props.header; if (!header) { return null; } if (!_react2['default'].isValidElement(header) || Array.isArray(header)) { header = this.props.collapsible ? this.renderCollapsibleTitle(header) : header; } else { var className = (0, _classnames2['default'])(this.prefixClass('title'), header.props.className); if (this.props.collapsible) { header = (0, _react.cloneElement)(header, { className: className, children: this.renderAnchor(header.props.children) }); } else { header = (0, _react.cloneElement)(header, { className: className }); } } return _react2['default'].createElement( 'div', { className: this.prefixClass('heading') }, header ); }, renderAnchor: function renderAnchor(header) { return _react2['default'].createElement( 'a', { href: '#' + (this.props.id || ''), className: this.isExpanded() ? null : 'collapsed', 'aria-expanded': this.isExpanded() ? 'true' : 'false', onClick: this.handleSelect }, header ); }, renderCollapsibleTitle: function renderCollapsibleTitle(header) { return _react2['default'].createElement( 'h4', { className: this.prefixClass('title') }, this.renderAnchor(header) ); }, renderFooter: function renderFooter() { if (!this.props.footer) { return null; } return _react2['default'].createElement( 'div', { className: this.prefixClass('footer') }, this.props.footer ); } }); exports['default'] = Panel; module.exports = exports['default']; /***/ }, /* 57 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var PageItem = _react2['default'].createClass({ displayName: 'PageItem', propTypes: { href: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.string, disabled: _react2['default'].PropTypes.bool, previous: _react2['default'].PropTypes.bool, next: _react2['default'].PropTypes.bool, onSelect: _react2['default'].PropTypes.func, eventKey: _react2['default'].PropTypes.any }, getDefaultProps: function getDefaultProps() { return { href: '#' }; }, render: function render() { var classes = { 'disabled': this.props.disabled, 'previous': this.props.previous, 'next': this.props.next }; return _react2['default'].createElement( 'li', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), _react2['default'].createElement( 'a', { href: this.props.href, title: this.props.title, target: this.props.target, onClick: this.handleSelect, ref: 'anchor' }, this.props.children ) ); }, handleSelect: function handleSelect(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } } }); exports['default'] = PageItem; module.exports = exports['default']; /***/ }, /* 58 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var Pager = _react2['default'].createClass({ displayName: 'Pager', propTypes: { onSelect: _react2['default'].PropTypes.func }, render: function render() { return _react2['default'].createElement( 'ul', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'pager') }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderPageItem) ); }, renderPageItem: function renderPageItem(child, index) { return (0, _react.cloneElement)(child, { onSelect: (0, _utilsCreateChainedFunction2['default'])(child.props.onSelect, this.props.onSelect), key: child.key ? child.key : index }); } }); exports['default'] = Pager; module.exports = exports['default']; /***/ }, /* 59 */ /***/ 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 }; } function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _FadeMixin = __webpack_require__(32); var _FadeMixin2 = _interopRequireDefault(_FadeMixin); var Popover = _react2['default'].createClass({ displayName: 'Popover', mixins: [_BootstrapMixin2['default'], _FadeMixin2['default']], propTypes: { placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']), positionLeft: _react2['default'].PropTypes.number, positionTop: _react2['default'].PropTypes.number, arrowOffsetLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), arrowOffsetTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), title: _react2['default'].PropTypes.node, animation: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { placement: 'right', animation: true }; }, render: function render() { var _classes; var classes = (_classes = { 'popover': true }, _defineProperty(_classes, this.props.placement, true), _defineProperty(_classes, 'in', !this.props.animation && (this.props.positionLeft != null || this.props.positionTop != null)), _defineProperty(_classes, 'fade', this.props.animation), _classes); var style = { 'left': this.props.positionLeft, 'top': this.props.positionTop, 'display': 'block' }; var arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), style: style, title: null }), _react2['default'].createElement('div', { className: 'arrow', style: arrowStyle }), this.props.title ? this.renderTitle() : null, _react2['default'].createElement( 'div', { className: 'popover-content' }, this.props.children ) ); }, renderTitle: function renderTitle() { return _react2['default'].createElement( 'h3', { className: 'popover-title' }, this.props.title ); } }); exports['default'] = Popover; module.exports = exports['default']; // in class will be added by the FadeMixin when the animation property is true /***/ }, /* 60 */ /***/ 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 _Interpolate = __webpack_require__(39); var _Interpolate2 = _interopRequireDefault(_Interpolate); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var ProgressBar = _react2['default'].createClass({ displayName: 'ProgressBar', propTypes: { min: _react2['default'].PropTypes.number, now: _react2['default'].PropTypes.number, max: _react2['default'].PropTypes.number, label: _react2['default'].PropTypes.node, srOnly: _react2['default'].PropTypes.bool, striped: _react2['default'].PropTypes.bool, active: _react2['default'].PropTypes.bool }, mixins: [_BootstrapMixin2['default']], getDefaultProps: function getDefaultProps() { return { bsClass: 'progress-bar', min: 0, max: 100 }; }, getPercentage: function getPercentage(now, min, max) { var roundPrecision = 1000; return Math.round((now - min) / (max - min) * 100 * roundPrecision) / roundPrecision; }, render: function render() { var classes = { progress: true }; if (this.props.active) { classes['progress-striped'] = true; classes.active = true; } else if (this.props.striped) { classes['progress-striped'] = true; } if (!_utilsValidComponentChildren2['default'].hasValidComponent(this.props.children)) { if (!this.props.isChild) { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.renderProgressBar() ); } else { return this.renderProgressBar(); } } else { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), _utilsValidComponentChildren2['default'].map(this.props.children, this.renderChildBar) ); } }, renderChildBar: function renderChildBar(child, index) { return (0, _react.cloneElement)(child, { isChild: true, key: child.key ? child.key : index }); }, renderProgressBar: function renderProgressBar() { var percentage = this.getPercentage(this.props.now, this.props.min, this.props.max); var label = undefined; if (typeof this.props.label === 'string') { label = this.renderLabel(percentage); } else if (this.props.label) { label = this.props.label; } if (this.props.srOnly) { label = this.renderScreenReaderOnlyLabel(label); } var classes = this.getBsClassSet(); return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), role: 'progressbar', style: { width: percentage + '%' }, 'aria-valuenow': this.props.now, 'aria-valuemin': this.props.min, 'aria-valuemax': this.props.max }), label ); }, renderLabel: function renderLabel(percentage) { var InterpolateClass = this.props.interpolateClass || _Interpolate2['default']; return _react2['default'].createElement( InterpolateClass, { now: this.props.now, min: this.props.min, max: this.props.max, percent: percentage, bsStyle: this.props.bsStyle }, this.props.label ); }, renderScreenReaderOnlyLabel: function renderScreenReaderOnlyLabel(label) { return _react2['default'].createElement( 'span', { className: 'sr-only' }, label ); } }); exports['default'] = ProgressBar; module.exports = exports['default']; /***/ }, /* 61 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var Row = _react2['default'].createClass({ displayName: 'Row', propTypes: { componentClass: _react2['default'].PropTypes.node.isRequired }, getDefaultProps: function getDefaultProps() { return { componentClass: 'div' }; }, render: function render() { var ComponentClass = this.props.componentClass; return _react2['default'].createElement( ComponentClass, _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, 'row') }), this.props.children ); } }); exports['default'] = Row; module.exports = exports['default']; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* eslint react/prop-types: [1, {ignore: ["children", "className", "bsSize"]}]*/ /* BootstrapMixin contains `bsSize` type validation */ '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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _DropdownStateMixin = __webpack_require__(30); var _DropdownStateMixin2 = _interopRequireDefault(_DropdownStateMixin); var _Button = __webpack_require__(15); var _Button2 = _interopRequireDefault(_Button); var _ButtonGroup = __webpack_require__(16); var _ButtonGroup2 = _interopRequireDefault(_ButtonGroup); var _DropdownMenu = __webpack_require__(31); var _DropdownMenu2 = _interopRequireDefault(_DropdownMenu); var SplitButton = _react2['default'].createClass({ displayName: 'SplitButton', mixins: [_BootstrapMixin2['default'], _DropdownStateMixin2['default']], propTypes: { pullRight: _react2['default'].PropTypes.bool, title: _react2['default'].PropTypes.node, href: _react2['default'].PropTypes.string, id: _react2['default'].PropTypes.string, target: _react2['default'].PropTypes.string, dropdownTitle: _react2['default'].PropTypes.node, dropup: _react2['default'].PropTypes.bool, onClick: _react2['default'].PropTypes.func, onSelect: _react2['default'].PropTypes.func, disabled: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { dropdownTitle: 'Toggle dropdown' }; }, render: function render() { var groupClasses = { 'open': this.state.open, 'dropup': this.props.dropup }; var button = _react2['default'].createElement( _Button2['default'], _extends({}, this.props, { ref: 'button', onClick: this.handleButtonClick, title: null, id: null }), this.props.title ); var dropdownButton = _react2['default'].createElement( _Button2['default'], _extends({}, this.props, { ref: 'dropdownButton', className: (0, _classnames2['default'])(this.props.className, 'dropdown-toggle'), onClick: this.handleDropdownClick, title: null, href: null, target: null, id: null }), _react2['default'].createElement( 'span', { className: 'sr-only' }, this.props.dropdownTitle ), _react2['default'].createElement('span', { className: 'caret' }), _react2['default'].createElement( 'span', { style: { letterSpacing: '-.3em' } }, ' ' ) ); return _react2['default'].createElement( _ButtonGroup2['default'], { bsSize: this.props.bsSize, className: (0, _classnames2['default'])(groupClasses), id: this.props.id }, button, dropdownButton, _react2['default'].createElement( _DropdownMenu2['default'], { ref: 'menu', onSelect: this.handleOptionSelect, 'aria-labelledby': this.props.id, pullRight: this.props.pullRight }, this.props.children ) ); }, handleButtonClick: function handleButtonClick(e) { if (this.state.open) { this.setDropdownState(false); } if (this.props.onClick) { this.props.onClick(e, this.props.href, this.props.target); } }, handleDropdownClick: function handleDropdownClick(e) { e.preventDefault(); this.setDropdownState(!this.state.open); }, handleOptionSelect: function handleOptionSelect(key) { if (this.props.onSelect) { this.props.onSelect(key); } this.setDropdownState(false); } }); exports['default'] = SplitButton; module.exports = exports['default']; /***/ }, /* 63 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _utilsCreateChainedFunction = __webpack_require__(25); var _utilsCreateChainedFunction2 = _interopRequireDefault(_utilsCreateChainedFunction); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var SubNav = _react2['default'].createClass({ displayName: 'SubNav', mixins: [_BootstrapMixin2['default']], propTypes: { onSelect: _react2['default'].PropTypes.func, active: _react2['default'].PropTypes.bool, activeHref: _react2['default'].PropTypes.string, activeKey: _react2['default'].PropTypes.any, disabled: _react2['default'].PropTypes.bool, eventKey: _react2['default'].PropTypes.any, href: _react2['default'].PropTypes.string, title: _react2['default'].PropTypes.string, text: _react2['default'].PropTypes.node, target: _react2['default'].PropTypes.string }, getDefaultProps: function getDefaultProps() { return { bsClass: 'nav' }; }, handleClick: function handleClick(e) { if (this.props.onSelect) { e.preventDefault(); if (!this.props.disabled) { this.props.onSelect(this.props.eventKey, this.props.href, this.props.target); } } }, isActive: function isActive() { return this.isChildActive(this); }, isChildActive: function isChildActive(child) { var _this = this; if (child.props.active) { return true; } if (this.props.activeKey != null && this.props.activeKey === child.props.eventKey) { return true; } if (this.props.activeHref != null && this.props.activeHref === child.props.href) { return true; } if (child.props.children) { var _ret = (function () { var isActive = false; _utilsValidComponentChildren2['default'].forEach(child.props.children, function (grandchild) { if (this.isChildActive(grandchild)) { isActive = true; } }, _this); return { v: isActive }; })(); if (typeof _ret === 'object') return _ret.v; } return false; }, getChildActiveProp: function getChildActiveProp(child) { if (child.props.active) { return true; } if (this.props.activeKey != null) { if (child.props.eventKey === this.props.activeKey) { return true; } } if (this.props.activeHref != null) { if (child.props.href === this.props.activeHref) { return true; } } return child.props.active; }, render: function render() { var classes = { 'active': this.isActive(), 'disabled': this.props.disabled }; return _react2['default'].createElement( 'li', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), _react2['default'].createElement( 'a', { href: this.props.href, title: this.props.title, target: this.props.target, onClick: this.handleClick, ref: 'anchor' }, this.props.text ), _react2['default'].createElement( 'ul', { className: 'nav' }, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderNavItem) ) ); }, renderNavItem: function renderNavItem(child, index) { return (0, _react.cloneElement)(child, { active: this.getChildActiveProp(child), onSelect: (0, _utilsCreateChainedFunction2['default'])(child.props.onSelect, this.props.onSelect), key: child.key ? child.key : index }); } }); exports['default'] = SubNav; module.exports = exports['default']; /***/ }, /* 64 */ /***/ 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 _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _utilsValidComponentChildren = __webpack_require__(8); var _utilsValidComponentChildren2 = _interopRequireDefault(_utilsValidComponentChildren); var _Nav = __webpack_require__(47); var _Nav2 = _interopRequireDefault(_Nav); var _NavItem = __webpack_require__(49); var _NavItem2 = _interopRequireDefault(_NavItem); function getDefaultActiveKeyFromChildren(children) { var defaultActiveKey = undefined; _utilsValidComponentChildren2['default'].forEach(children, function (child) { if (defaultActiveKey == null) { defaultActiveKey = child.props.eventKey; } }); return defaultActiveKey; } var TabbedArea = _react2['default'].createClass({ displayName: 'TabbedArea', mixins: [_BootstrapMixin2['default']], propTypes: { activeKey: _react2['default'].PropTypes.any, defaultActiveKey: _react2['default'].PropTypes.any, bsStyle: _react2['default'].PropTypes.oneOf(['tabs', 'pills']), animation: _react2['default'].PropTypes.bool, id: _react2['default'].PropTypes.string, onSelect: _react2['default'].PropTypes.func }, getDefaultProps: function getDefaultProps() { return { bsStyle: 'tabs', animation: true }; }, getInitialState: function getInitialState() { var defaultActiveKey = this.props.defaultActiveKey != null ? this.props.defaultActiveKey : getDefaultActiveKeyFromChildren(this.props.children); return { activeKey: defaultActiveKey, previousActiveKey: null }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.activeKey != null && nextProps.activeKey !== this.props.activeKey) { this.setState({ previousActiveKey: this.props.activeKey }); } }, handlePaneAnimateOutEnd: function handlePaneAnimateOutEnd() { this.setState({ previousActiveKey: null }); }, render: function render() { var activeKey = this.props.activeKey != null ? this.props.activeKey : this.state.activeKey; function renderTabIfSet(child) { return child.props.tab != null ? this.renderTab(child) : null; } var nav = _react2['default'].createElement( _Nav2['default'], _extends({}, this.props, { activeKey: activeKey, onSelect: this.handleSelect, ref: 'tabs' }), _utilsValidComponentChildren2['default'].map(this.props.children, renderTabIfSet, this) ); return _react2['default'].createElement( 'div', null, nav, _react2['default'].createElement( 'div', { id: this.props.id, className: 'tab-content', ref: 'panes' }, _utilsValidComponentChildren2['default'].map(this.props.children, this.renderPane) ) ); }, getActiveKey: function getActiveKey() { return this.props.activeKey != null ? this.props.activeKey : this.state.activeKey; }, renderPane: function renderPane(child, index) { var activeKey = this.getActiveKey(); return (0, _react.cloneElement)(child, { active: child.props.eventKey === activeKey && (this.state.previousActiveKey == null || !this.props.animation), key: child.key ? child.key : index, animation: this.props.animation, onAnimateOutEnd: this.state.previousActiveKey != null && child.props.eventKey === this.state.previousActiveKey ? this.handlePaneAnimateOutEnd : null }); }, renderTab: function renderTab(child) { var _child$props = child.props; var eventKey = _child$props.eventKey; var className = _child$props.className; var tab = _child$props.tab; var disabled = _child$props.disabled; return _react2['default'].createElement( _NavItem2['default'], { ref: 'tab' + eventKey, eventKey: eventKey, className: className, disabled: disabled }, tab ); }, shouldComponentUpdate: function shouldComponentUpdate() { // Defer any updates to this component during the `onSelect` handler. return !this._isChanging; }, handleSelect: function handleSelect(key) { if (this.props.onSelect) { this._isChanging = true; this.props.onSelect(key); this._isChanging = false; } else if (key !== this.getActiveKey()) { this.setState({ activeKey: key, previousActiveKey: this.getActiveKey() }); } } }); exports['default'] = TabbedArea; module.exports = exports['default']; /***/ }, /* 65 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var Table = _react2['default'].createClass({ displayName: 'Table', propTypes: { striped: _react2['default'].PropTypes.bool, bordered: _react2['default'].PropTypes.bool, condensed: _react2['default'].PropTypes.bool, hover: _react2['default'].PropTypes.bool, responsive: _react2['default'].PropTypes.bool }, render: function render() { var classes = { 'table': true, 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed, 'table-hover': this.props.hover }; var table = _react2['default'].createElement( 'table', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); return this.props.responsive ? _react2['default'].createElement( 'div', { className: 'table-responsive' }, table ) : table; } }); exports['default'] = Table; module.exports = exports['default']; /***/ }, /* 66 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _utilsTransitionEvents = __webpack_require__(24); var _utilsTransitionEvents2 = _interopRequireDefault(_utilsTransitionEvents); var TabPane = _react2['default'].createClass({ displayName: 'TabPane', propTypes: { active: _react2['default'].PropTypes.bool, animation: _react2['default'].PropTypes.bool, onAnimateOutEnd: _react2['default'].PropTypes.func, disabled: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { animation: true }; }, getInitialState: function getInitialState() { return { animateIn: false, animateOut: false }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.animation) { if (!this.state.animateIn && nextProps.active && !this.props.active) { this.setState({ animateIn: true }); } else if (!this.state.animateOut && !nextProps.active && this.props.active) { this.setState({ animateOut: true }); } } }, componentDidUpdate: function componentDidUpdate() { if (this.state.animateIn) { setTimeout(this.startAnimateIn, 0); } if (this.state.animateOut) { _utilsTransitionEvents2['default'].addEndEventListener(_react2['default'].findDOMNode(this), this.stopAnimateOut); } }, startAnimateIn: function startAnimateIn() { if (this.isMounted()) { this.setState({ animateIn: false }); } }, stopAnimateOut: function stopAnimateOut() { if (this.isMounted()) { this.setState({ animateOut: false }); if (this.props.onAnimateOutEnd) { this.props.onAnimateOutEnd(); } } }, render: function render() { var classes = { 'tab-pane': true, 'fade': true, 'active': this.props.active || this.state.animateOut, 'in': this.props.active && !this.state.animateIn }; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = TabPane; module.exports = exports['default']; /***/ }, /* 67 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var Thumbnail = _react2['default'].createClass({ displayName: 'Thumbnail', mixins: [_BootstrapMixin2['default']], getDefaultProps: function getDefaultProps() { return { bsClass: 'thumbnail' }; }, render: function render() { var classes = this.getBsClassSet(); if (this.props.href) { return _react2['default'].createElement( 'a', _extends({}, this.props, { href: this.props.href, className: (0, _classnames2['default'])(this.props.className, classes) }), _react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }) ); } else { if (this.props.children) { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), _react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }), _react2['default'].createElement( 'div', { className: 'caption' }, this.props.children ) ); } else { return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), _react2['default'].createElement('img', { src: this.props.src, alt: this.props.alt }) ); } } } }); exports['default'] = Thumbnail; module.exports = exports['default']; /***/ }, /* 68 */ /***/ 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 }; } function _defineProperty(obj, key, value) { return Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var _FadeMixin = __webpack_require__(32); var _FadeMixin2 = _interopRequireDefault(_FadeMixin); var Tooltip = _react2['default'].createClass({ displayName: 'Tooltip', mixins: [_BootstrapMixin2['default'], _FadeMixin2['default']], propTypes: { placement: _react2['default'].PropTypes.oneOf(['top', 'right', 'bottom', 'left']), positionLeft: _react2['default'].PropTypes.number, positionTop: _react2['default'].PropTypes.number, arrowOffsetLeft: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), arrowOffsetTop: _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.number, _react2['default'].PropTypes.string]), animation: _react2['default'].PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { placement: 'right', animation: true }; }, render: function render() { var _classes; var classes = (_classes = { 'tooltip': true }, _defineProperty(_classes, this.props.placement, true), _defineProperty(_classes, 'in', !this.props.animation && (this.props.positionLeft != null || this.props.positionTop != null)), _defineProperty(_classes, 'fade', this.props.animation), _classes); var style = { 'left': this.props.positionLeft, 'top': this.props.positionTop }; var arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes), style: style }), _react2['default'].createElement('div', { className: 'tooltip-arrow', style: arrowStyle }), _react2['default'].createElement( 'div', { className: 'tooltip-inner' }, this.props.children ) ); } }); exports['default'] = Tooltip; module.exports = exports['default']; // in class will be added by the FadeMixin when the animation property is true /***/ }, /* 69 */ /***/ 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 _classnames = __webpack_require__(4); var _classnames2 = _interopRequireDefault(_classnames); var _BootstrapMixin = __webpack_require__(5); var _BootstrapMixin2 = _interopRequireDefault(_BootstrapMixin); var Well = _react2['default'].createClass({ displayName: 'Well', mixins: [_BootstrapMixin2['default']], getDefaultProps: function getDefaultProps() { return { bsClass: 'well' }; }, render: function render() { var classes = this.getBsClassSet(); return _react2['default'].createElement( 'div', _extends({}, this.props, { className: (0, _classnames2['default'])(this.props.className, classes) }), this.props.children ); } }); exports['default'] = Well; module.exports = exports['default']; /***/ } /******/ ]) }); ;
docs/src/examples/collections/Form/GroupVariations/FormExampleUnstackableGroup.js
Semantic-Org/Semantic-UI-React
import React from 'react' import { Button, Form } from 'semantic-ui-react' const FormExampleUnstackableGroup = () => ( <Form> <Form.Group unstackable widths={2}> <Form.Input label='First name' placeholder='First name' /> <Form.Input label='Last name' placeholder='Last name' /> </Form.Group> <Form.Group widths={2}> <Form.Input label='Address' placeholder='Address' /> <Form.Input label='Phone' placeholder='Phone' /> </Form.Group> <Form.Checkbox label='I agree to the Terms and Conditions' /> <Button type='submit'>Submit</Button> </Form> ) export default FormExampleUnstackableGroup
src/svg-icons/maps/local-grocery-store.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalGroceryStore = (props) => ( <SvgIcon {...props}> <path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/> </SvgIcon> ); MapsLocalGroceryStore = pure(MapsLocalGroceryStore); MapsLocalGroceryStore.displayName = 'MapsLocalGroceryStore'; export default MapsLocalGroceryStore;
WebRoot/res/js/jquery/jquery-1.4.4.js
sharpstill/CronHub
/*! * jQuery JavaScript Library v1.4.4 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Nov 11 19:04:53 2010 -0500 */ (function( window, undefined ) { // Use the correct document accordingly with window argument (sandbox) var document = window.document; 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 ); }, // 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 // (both of which we optimize for) quickExpr = /^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/, // Is it a simple selector isSimple = /^.[^:#\[\.,]*$/, // Check if a string has a non-whitespace character in it rnotwhite = /\S/, rwhite = /\s/, // Used for trimming whitespace trimLeft = /^\s+/, trimRight = /\s+$/, // Check for non-word characters rnonword = /\W/, // Check for digits rdigit = /\d/, // 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.]+))?/, // Keep a UserAgent string for use with jQuery.browser userAgent = navigator.userAgent, // For matching the engine and version of the browser browserMatch, // Has the ready events already been bound? readyBound = false, // The functions to execute 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 = { init: function( selector, context ) { 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 = "body"; this.length = 1; return this; } // Handle HTML strings if ( typeof selector === "string" ) { // Are we dealing with HTML string or an ID? 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] ) { 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 ? ret.fragment.cloneNode(true) : 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: $("TAG") } else if ( !context && !rnonword.test( selector ) ) { this.selector = selector; this.context = document; selector = document.getElementsByTagName( selector ); return jQuery.merge( this, selector ); // 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 jQuery( 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.4.4", // 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.slice(num)[ 0 ] : 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(); 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(); // If the DOM is already ready if ( jQuery.isReady ) { // Execute the function immediately fn.call( document, jQuery ); // Otherwise, remember the function for later } else if ( readyList ) { // Add the function to the wait list readyList.push( fn ); } return this; }, eq: function( 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 || jQuery(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 ) { window.$ = _$; if ( deep ) { 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, // Handle when the DOM is ready ready: function( wait ) { // A third-party is pushing the ready event forwards if ( wait === true ) { jQuery.readyWait--; } // Make sure that the DOM is not already loaded if ( !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 if ( readyList ) { // Execute all of them var fn, i = 0, ready = readyList; // Reset the list of functions readyList = null; while ( (fn = ready[ i++ ]) ) { fn.call( document, jQuery ); } // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger( "ready" ).unbind( "ready" ); } } } }, bindReady: function() { if ( readyBound ) { return; } readyBound = true; // 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; }, isNaN: function( obj ) { return obj == null || !rdigit.test( obj ) || isNaN( 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; } // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { 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 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 ); // 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, "")) ) { // Try to use the native JSON parser first return window.JSON && window.JSON.parse ? window.JSON.parse( data ) : (new Function("return " + data))(); } else { jQuery.error( "Invalid JSON: " + data ); } }, noop: function() {}, // Evalulates a script in a global context globalEval: function( data ) { if ( data && rnotwhite.test(data) ) { // Inspired by code by Andrea Giammarchi // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html var head = document.getElementsByTagName("head")[0] || document.documentElement, script = document.createElement("script"); script.type = "text/javascript"; if ( jQuery.support.scriptEval ) { script.appendChild( document.createTextNode( data ) ); } else { script.text = data; } // Use insertBefore instead of appendChild to circumvent an IE6 bug. // This arises when a base node is used (#2709). head.insertBefore( script, head.firstChild ); head.removeChild( script ); } }, 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 ( var value = object[0]; i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {} } } 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' // The extra typeof function check is to prevent crashes // in Safari 2 (See: #3039) // 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 ) { if ( array.indexOf ) { return array.indexOf( elem ); } for ( var i = 0, length = array.length; i < length; i++ ) { if ( 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 ret = [], value; // Go through the array, translating each of the items to their // new value (or values). for ( var i = 0, length = elems.length; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } return ret.concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, proxy: function( fn, proxy, thisObject ) { if ( arguments.length === 2 ) { if ( typeof proxy === "string" ) { thisObject = fn; fn = thisObject[ proxy ]; proxy = undefined; } else if ( proxy && !jQuery.isFunction( proxy ) ) { thisObject = proxy; proxy = undefined; } } if ( !proxy && fn ) { proxy = function() { return fn.apply( thisObject || this, arguments ); }; } // Set the guid of unique handler to the same of original handler, so it can be removed if ( fn ) { proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++; } // So proxy can be declared as an argument return proxy; }, // Mutifunctional method to get and set values to a collection // The value/s can be optionally by executed if its 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" }; }, 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; } if ( indexOf ) { jQuery.inArray = function( elem, array ) { return indexOf.call( array, elem ); }; } // Verify that \s matches non-breaking spaces // (IE fails on this test) if ( !rwhite.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(); } // Expose jQuery to the global object return (window.jQuery = window.$ = jQuery); })(); (function() { jQuery.support = {}; var root = document.documentElement, script = document.createElement("script"), div = document.createElement("div"), id = "script" + jQuery.now(); div.style.display = "none"; div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var all = div.getElementsByTagName("*"), a = div.getElementsByTagName("a")[0], select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Can't get basic test support if ( !all || !all.length || !a ) { return; } jQuery.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 insted) style: /red/.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: div.getElementsByTagName("input")[0].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, // Will be defined later deleteExpando: true, optDisabled: false, checkClone: false, scriptEval: false, noCloneEvent: true, boxModel: null, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableHiddenOffsets: true }; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as diabled) select.disabled = true; jQuery.support.optDisabled = !opt.disabled; script.type = "text/javascript"; try { script.appendChild( document.createTextNode( "window." + id + "=1;" ) ); } catch(e) {} root.insertBefore( script, root.firstChild ); // Make sure that the execution of code works by injecting a script // tag with appendChild/createTextNode // (IE doesn't support this, fails, and uses .text instead) if ( window[ id ] ) { jQuery.support.scriptEval = true; delete window[ id ]; } // Test to see if it's possible to delete an expando from an element // Fails in Internet Explorer try { delete script.test; } catch(e) { jQuery.support.deleteExpando = false; } root.removeChild( script ); if ( div.attachEvent && div.fireEvent ) { div.attachEvent("onclick", function click() { // Cloning a node shouldn't copy over any // bound event handlers (IE does this) jQuery.support.noCloneEvent = false; div.detachEvent("onclick", click); }); div.cloneNode(true).fireEvent("onclick"); } div = document.createElement("div"); div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>"; var fragment = document.createDocumentFragment(); fragment.appendChild( div.firstChild ); // WebKit doesn't clone checked state correctly in fragments jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked; // Figure out if the W3C box model works as expected // document.body must exist before we can do this jQuery(function() { var div = document.createElement("div"); div.style.width = div.style.paddingLeft = "1px"; document.body.appendChild( div ); jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2; if ( "zoom" in div.style ) { // 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; jQuery.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>"; jQuery.support.shrinkWrapBlocks = div.offsetWidth !== 2; } div.innerHTML = "<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>"; var tds = div.getElementsByTagName("td"); // 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) jQuery.support.reliableHiddenOffsets = 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) jQuery.support.reliableHiddenOffsets = jQuery.support.reliableHiddenOffsets && tds[0].offsetHeight === 0; div.innerHTML = ""; document.body.removeChild( div ).style.display = "none"; div = tds = null; }); // Technique from Juriy Zaytsev // http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/ var eventSupported = function( eventName ) { var el = document.createElement("div"); eventName = "on" + eventName; var isSupported = (eventName in el); if ( !isSupported ) { el.setAttribute(eventName, "return;"); isSupported = typeof el[eventName] === "function"; } el = null; return isSupported; }; jQuery.support.submitBubbles = eventSupported("submit"); jQuery.support.changeBubbles = eventSupported("change"); // release memory in IE root = script = div = all = a = null; })(); var windowData = {}, rbrace = /^(?:\{.*\}|\[.*\])$/; jQuery.extend({ cache: {}, // Please use with caution uuid: 0, // Unique for each copy of jQuery on the page expando: "jQuery" + jQuery.now(), // 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 }, data: function( elem, name, data ) { if ( !jQuery.acceptData( elem ) ) { return; } elem = elem == window ? windowData : elem; var isNode = elem.nodeType, id = isNode ? elem[ jQuery.expando ] : null, cache = jQuery.cache, thisCache; if ( isNode && !id && typeof name === "string" && data === undefined ) { return; } // Get the data from the object directly if ( !isNode ) { cache = elem; // Compute a unique ID for the element } else if ( !id ) { elem[ jQuery.expando ] = id = ++jQuery.uuid; } // Avoid generating a new cache unless none exists and we // want to manipulate it. if ( typeof name === "object" ) { if ( isNode ) { cache[ id ] = jQuery.extend(cache[ id ], name); } else { jQuery.extend( cache, name ); } } else if ( isNode && !cache[ id ] ) { cache[ id ] = {}; } thisCache = isNode ? cache[ id ] : cache; // Prevent overriding the named cache with undefined values if ( data !== undefined ) { thisCache[ name ] = data; } return typeof name === "string" ? thisCache[ name ] : thisCache; }, removeData: function( elem, name ) { if ( !jQuery.acceptData( elem ) ) { return; } elem = elem == window ? windowData : elem; var isNode = elem.nodeType, id = isNode ? elem[ jQuery.expando ] : elem, cache = jQuery.cache, thisCache = isNode ? cache[ id ] : id; // If we want to remove a specific section of the element's data if ( name ) { if ( thisCache ) { // Remove the section of cache data delete thisCache[ name ]; // If we've removed all the data, remove the element's cache if ( isNode && jQuery.isEmptyObject(thisCache) ) { jQuery.removeData( elem ); } } // Otherwise, we want to remove all of the element's data } else { if ( isNode && jQuery.support.deleteExpando ) { delete elem[ jQuery.expando ]; } else if ( elem.removeAttribute ) { elem.removeAttribute( jQuery.expando ); // Completely remove the data cache } else if ( isNode ) { delete cache[ id ]; // Remove all fields from the object } else { for ( var n in elem ) { delete elem[ n ]; } } } }, // 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 data = null; if ( typeof key === "undefined" ) { if ( this.length ) { var attr = this[0].attributes, name; data = jQuery.data( this[0] ); for ( var i = 0, l = attr.length; i < l; i++ ) { name = attr[i].name; if ( name.indexOf( "data-" ) === 0 ) { name = name.substr( 5 ); dataAttr( this[0], name, data[ name ] ); } } } return data; } else if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } var 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 $this = jQuery( this ), args = [ parts[0], value ]; $this.triggerHandler( "setData" + parts[1] + "!", args ); jQuery.data( this, key, value ); $this.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 ) { data = elem.getAttribute( "data-" + key ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : !jQuery.isNaN( 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; } jQuery.extend({ queue: function( elem, type, data ) { if ( !elem ) { return; } type = (type || "fx") + "queue"; var q = jQuery.data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( !data ) { return q || []; } 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(); // 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"); } fn.call(elem, function() { jQuery.dequeue(elem, type); }); } } }); 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( i ) { 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() { var elem = this; setTimeout(function() { jQuery.dequeue( elem, type ); }, time ); }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); } }); var rclass = /[\n\t]/g, rspaces = /\s+/, rreturn = /\r/g, rspecialurl = /^(?:href|src|style)$/, rtype = /^(?:button|input)$/i, rfocusable = /^(?:button|input|object|select|textarea)$/i, rclickable = /^a(?:rea)?$/i, rradiocheck = /^(?:radio|checkbox)$/i; jQuery.props = { "for": "htmlFor", "class": "className", readonly: "readOnly", maxlength: "maxLength", cellspacing: "cellSpacing", rowspan: "rowSpan", colspan: "colSpan", tabindex: "tabIndex", usemap: "useMap", frameborder: "frameBorder" }; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, name, value, true, jQuery.attr ); }, removeAttr: function( name, fn ) { return this.each(function(){ jQuery.attr( this, name, "" ); if ( this.nodeType === 1 ) { this.removeAttribute( name ); } }); }, addClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.addClass( value.call(this, i, self.attr("class")) ); }); } if ( value && typeof value === "string" ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 ) { if ( !elem.className ) { elem.className = value; } else { var className = " " + elem.className + " ", setClass = elem.className; for ( var c = 0, cl = classNames.length; c < cl; c++ ) { if ( className.indexOf( " " + classNames[c] + " " ) < 0 ) { setClass += " " + classNames[c]; } } elem.className = jQuery.trim( setClass ); } } } } return this; }, removeClass: function( value ) { if ( jQuery.isFunction(value) ) { return this.each(function(i) { var self = jQuery(this); self.removeClass( value.call(this, i, self.attr("class")) ); }); } if ( (value && typeof value === "string") || value === undefined ) { var classNames = (value || "").split( rspaces ); for ( var i = 0, l = this.length; i < l; i++ ) { var elem = this[i]; if ( elem.nodeType === 1 && elem.className ) { if ( value ) { var className = (" " + elem.className + " ").replace(rclass, " "); for ( var 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) { var self = jQuery(this); self.toggleClass( value.call(this, i, self.attr("class"), 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( rspaces ); 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 + " "; for ( var i = 0, l = this.length; i < l; i++ ) { if ( (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) { return true; } } return false; }, val: function( value ) { if ( !arguments.length ) { var elem = this[0]; if ( elem ) { if ( jQuery.nodeName( elem, "option" ) ) { // 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; } // We need to handle select boxes special if ( jQuery.nodeName( elem, "select" ) ) { var 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 for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) { var 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 ); } } return values; } // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) { return elem.getAttribute("value") === null ? "on" : elem.value; } // Everything else, we just grab the value return (elem.value || "").replace(rreturn, ""); } return undefined; } var isFunction = jQuery.isFunction(value); return this.each(function(i) { var self = jQuery(this), val = value; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call(this, i, self.val()); } // 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 + ""; }); } if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) { this.checked = jQuery.inArray( self.val(), val ) >= 0; } else if ( jQuery.nodeName( this, "select" ) ) { var values = jQuery.makeArray(val); jQuery( "option", this ).each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { this.selectedIndex = -1; } } else { this.value = val; } }); } }); jQuery.extend({ attrFn: { val: true, css: true, html: true, text: true, data: true, width: true, height: true, offset: true }, attr: function( elem, name, value, pass ) { // don't set attributes on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } if ( pass && name in jQuery.attrFn ) { return jQuery(elem)[name](value); } var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ), // Whether we are setting (or getting) set = value !== undefined; // Try to normalize/fix the name name = notxml && jQuery.props[ name ] || name; // These attributes require special treatment var special = rspecialurl.test( name ); // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( name === "selected" && !jQuery.support.optSelected ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } // If applicable, access the attribute via the DOM 0 way // 'in' checks fail in Blackberry 4.7 #6931 if ( (name in elem || elem[ name ] !== undefined) && notxml && !special ) { if ( set ) { // We can't allow the type property to be changed (since it causes problems in IE) if ( name === "type" && rtype.test( elem.nodeName ) && elem.parentNode ) { jQuery.error( "type property can't be changed" ); } if ( value === null ) { if ( elem.nodeType === 1 ) { elem.removeAttribute( name ); } } else { elem[ name ] = value; } } // browsers index elements by id/name on forms, give priority to attributes. if ( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) ) { return elem.getAttributeNode( name ).nodeValue; } // 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/ if ( name === "tabIndex" ) { var attributeNode = elem.getAttributeNode( "tabIndex" ); return attributeNode && attributeNode.specified ? attributeNode.value : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } return elem[ name ]; } if ( !jQuery.support.style && notxml && name === "style" ) { if ( set ) { elem.style.cssText = "" + value; } return elem.style.cssText; } if ( set ) { // convert the value to a string (all browsers do this but IE) see #1070 elem.setAttribute( name, "" + value ); } // Ensure that missing attributes return undefined // Blackberry 4.7 returns "" from getAttribute #6938 if ( !elem.attributes[ name ] && (elem.hasAttribute && !elem.hasAttribute( name )) ) { return undefined; } var attr = !jQuery.support.hrefNormalized && notxml && special ? // Some attributes require a special call on IE elem.getAttribute( name, 2 ) : elem.getAttribute( name ); // Non-existent attributes return null, we normalize to undefined return attr === null ? undefined : attr; } }); var rnamespaces = /\.(.*)$/, rformElems = /^(?:textarea|input|select)$/i, rperiod = /\./g, rspace = / /g, rescape = /[^\w\s.|`]/g, fcleanup = function( nm ) { return nm.replace(rescape, "\\$&"); }, focusCounts = { focusin: 0, focusout: 0 }; /* * A number of helper functions used for managing events. * Many of the ideas behind this code originated from * Dean Edwards' addEvent library. */ jQuery.event = { // Bind an event to an element // Original by Dean Edwards add: function( elem, types, handler, data ) { if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // For whatever reason, IE has trouble passing the window object // around, causing it to be cloned in the process if ( jQuery.isWindow( elem ) && ( elem !== window && !elem.frameElement ) ) { elem = window; } if ( handler === false ) { handler = returnFalse; } else if ( !handler ) { // Fixes bug #7229. Fix recommended by jdalton return; } var handleObjIn, handleObj; if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; } // Make sure that the function being executed has a unique ID if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure var elemData = jQuery.data( elem ); // If no elemData is found then we must be trying to bind to one of the // banned noData elements if ( !elemData ) { return; } // Use a key less likely to result in collisions for plain JS objects. // Fixes bug #7150. var eventKey = elem.nodeType ? "events" : "__events__", events = elemData[ eventKey ], eventHandle = elemData.handle; if ( typeof events === "function" ) { // On plain objects events is a fn that holds the the data // which prevents this data from being JSON serialized // the function does not need to be called, it just contains the data eventHandle = events.handle; events = events.events; } else if ( !events ) { if ( !elem.nodeType ) { // On plain objects, create a fn that acts as the holder // of the values to avoid JSON serialization of event data elemData[ eventKey ] = elemData = function(){}; } elemData.events = events = {}; } if ( !eventHandle ) { elemData.handle = eventHandle = function() { // Handle the second event of a trigger and when // an event is called after a page has unloaded return typeof jQuery !== "undefined" && !jQuery.event.triggered ? jQuery.event.handle.apply( eventHandle.elem, arguments ) : undefined; }; } // Add elem as a property of the handle function // This is to prevent a memory leak with non-native events in IE. eventHandle.elem = elem; // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = types.split(" "); var type, i = 0, namespaces; while ( (type = types[ i++ ]) ) { handleObj = handleObjIn ? jQuery.extend({}, handleObjIn) : { handler: handler, data: data }; // Namespaced event handlers if ( type.indexOf(".") > -1 ) { namespaces = type.split("."); type = namespaces.shift(); handleObj.namespace = namespaces.slice(0).sort().join("."); } else { namespaces = []; handleObj.namespace = ""; } handleObj.type = type; if ( !handleObj.guid ) { handleObj.guid = handler.guid; } // Get the current list of functions bound to this event var handlers = events[ type ], special = jQuery.event.special[ type ] || {}; // Init the event handler queue if ( !handlers ) { handlers = events[ type ] = []; // Check for a special event handler // 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 the function to the element's handler list handlers.push( handleObj ); // Keep track of which events have been used, for global triggering 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, pos ) { // don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } if ( handler === false ) { handler = returnFalse; } var ret, type, fn, j, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType, eventKey = elem.nodeType ? "events" : "__events__", elemData = jQuery.data( elem ), events = elemData && elemData[ eventKey ]; if ( !elemData || !events ) { return; } if ( typeof events === "function" ) { elemData = events; events = events.events; } // types is actually an event object here if ( types && types.type ) { handler = types.handler; types = types.type; } // Unbind all events for the element if ( !types || typeof types === "string" && types.charAt(0) === "." ) { types = types || ""; for ( type in events ) { jQuery.event.remove( elem, type + types ); } return; } // Handle multiple events separated by a space // jQuery(...).unbind("mouseover mouseout", fn); types = types.split(" "); while ( (type = types[ i++ ]) ) { origType = type; handleObj = null; all = type.indexOf(".") < 0; namespaces = []; if ( !all ) { // Namespaced event handlers namespaces = type.split("."); type = namespaces.shift(); namespace = new RegExp("(^|\\.)" + jQuery.map( namespaces.slice(0).sort(), fcleanup ).join("\\.(?:.*\\.)?") + "(\\.|$)"); } eventType = events[ type ]; if ( !eventType ) { continue; } if ( !handler ) { for ( j = 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( all || namespace.test( handleObj.namespace ) ) { jQuery.event.remove( elem, origType, handleObj.handler, j ); eventType.splice( j--, 1 ); } } continue; } special = jQuery.event.special[ type ] || {}; for ( j = pos || 0; j < eventType.length; j++ ) { handleObj = eventType[ j ]; if ( handler.guid === handleObj.guid ) { // remove the given handler for the given type if ( all || namespace.test( handleObj.namespace ) ) { if ( pos == null ) { eventType.splice( j--, 1 ); } if ( special.remove ) { special.remove.call( elem, handleObj ); } } if ( pos != null ) { break; } } } // remove generic event handler if no more handlers exist if ( eventType.length === 0 || pos != null && eventType.length === 1 ) { if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } ret = null; delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { var handle = elemData.handle; if ( handle ) { handle.elem = null; } delete elemData.events; delete elemData.handle; if ( typeof elemData === "function" ) { jQuery.removeData( elem, eventKey ); } else if ( jQuery.isEmptyObject( elemData ) ) { jQuery.removeData( elem ); } } }, // bubbling is internal trigger: function( event, data, elem /*, bubbling */ ) { // Event object or event type var type = event.type || event, bubbling = arguments[3]; if ( !bubbling ) { event = typeof event === "object" ? // jQuery.Event object event[ jQuery.expando ] ? event : // Object literal jQuery.extend( jQuery.Event(type), event ) : // Just the event type (string) jQuery.Event(type); if ( type.indexOf("!") >= 0 ) { event.type = type = type.slice(0, -1); event.exclusive = true; } // Handle a global trigger if ( !elem ) { // Don't bubble custom events when global (to avoid too much overhead) event.stopPropagation(); // Only trigger if we've ever bound an event for it if ( jQuery.event.global[ type ] ) { jQuery.each( jQuery.cache, function() { if ( this.events && this.events[type] ) { jQuery.event.trigger( event, data, this.handle.elem ); } }); } } // Handle triggering a single element // don't do events on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) { return undefined; } // Clean up in case it is reused event.result = undefined; event.target = elem; // Clone the incoming data, if any data = jQuery.makeArray( data ); data.unshift( event ); } event.currentTarget = elem; // Trigger the event, it is assumed that "handle" is a function var handle = elem.nodeType ? jQuery.data( elem, "handle" ) : (jQuery.data( elem, "__events__" ) || {}).handle; if ( handle ) { handle.apply( elem, data ); } var parent = elem.parentNode || elem.ownerDocument; // Trigger an inline bound script try { if ( !(elem && elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()]) ) { if ( elem[ "on" + type ] && elem[ "on" + type ].apply( elem, data ) === false ) { event.result = false; event.preventDefault(); } } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (inlineError) {} if ( !event.isPropagationStopped() && parent ) { jQuery.event.trigger( event, data, parent, true ); } else if ( !event.isDefaultPrevented() ) { var old, target = event.target, targetType = type.replace( rnamespaces, "" ), isClick = jQuery.nodeName( target, "a" ) && targetType === "click", special = jQuery.event.special[ targetType ] || {}; if ( (!special._default || special._default.call( elem, event ) === false) && !isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) { try { if ( target[ targetType ] ) { // Make sure that we don't accidentally re-trigger the onFOO events old = target[ "on" + targetType ]; if ( old ) { target[ "on" + targetType ] = null; } jQuery.event.triggered = true; target[ targetType ](); } // prevent IE from throwing an error for some elements with some event types, see #3533 } catch (triggerError) {} if ( old ) { target[ "on" + targetType ] = old; } jQuery.event.triggered = false; } } }, handle: function( event ) { var all, handlers, namespaces, namespace_re, events, namespace_sort = [], args = jQuery.makeArray( arguments ); event = args[0] = jQuery.event.fix( event || window.event ); event.currentTarget = this; // Namespaced event handlers all = event.type.indexOf(".") < 0 && !event.exclusive; if ( !all ) { namespaces = event.type.split("."); event.type = namespaces.shift(); namespace_sort = namespaces.slice(0).sort(); namespace_re = new RegExp("(^|\\.)" + namespace_sort.join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.namespace = event.namespace || namespace_sort.join("."); events = jQuery.data(this, this.nodeType ? "events" : "__events__"); if ( typeof events === "function" ) { events = events.events; } handlers = (events || {})[ event.type ]; if ( events && handlers ) { // Clone the handlers to prevent manipulation handlers = handlers.slice(0); for ( var j = 0, l = handlers.length; j < l; j++ ) { var handleObj = handlers[ j ]; // Filter the functions by class if ( all || namespace_re.test( handleObj.namespace ) ) { // Pass in a reference to the handler function itself // So that we can later remove it event.handler = handleObj.handler; event.data = handleObj.data; event.handleObj = handleObj; var ret = handleObj.handler.apply( this, args ); if ( ret !== undefined ) { event.result = ret; if ( ret === false ) { event.preventDefault(); event.stopPropagation(); } } if ( event.isImmediatePropagationStopped() ) { break; } } } } return event.result; }, props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // store a copy of the original event object // and "clone" to set read-only properties var originalEvent = event; event = jQuery.Event( originalEvent ); for ( var i = this.props.length, prop; i; ) { prop = this.props[ --i ]; event[ prop ] = originalEvent[ prop ]; } // Fix target property, if necessary if ( !event.target ) { // Fixes #1925 where srcElement might not be defined either event.target = event.srcElement || document; } // check if target is a textnode (safari) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Add relatedTarget, if necessary if ( !event.relatedTarget && event.fromElement ) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && event.clientX != null ) { var doc = document.documentElement, body = document.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); } // Add which for key events if ( event.which == null && (event.charCode != null || event.keyCode != null) ) { event.which = event.charCode != null ? event.charCode : event.keyCode; } // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs) if ( !event.metaKey && event.ctrlKey ) { event.metaKey = event.ctrlKey; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && event.button !== undefined ) { event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) )); } return event; }, // Deprecated, use jQuery.guid instead guid: 1E8, // Deprecated, use jQuery.proxy instead proxy: jQuery.proxy, special: { ready: { // Make sure the ready event is setup setup: jQuery.bindReady, teardown: jQuery.noop }, live: { add: function( handleObj ) { jQuery.event.add( this, liveConvert( handleObj.origType, handleObj.selector ), jQuery.extend({}, handleObj, {handler: liveHandler, guid: handleObj.handler.guid}) ); }, remove: function( handleObj ) { jQuery.event.remove( this, liveConvert( handleObj.origType, handleObj.selector ), handleObj ); } }, 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; } } } } }; 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 ) { // Allow instantiation without the 'new' keyword if ( !this.preventDefault ) { return new jQuery.Event( src ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Event type } else { this.type = src; } // timeStamp is buggy for some events on Firefox(#3843) // So we won't rely on the native value this.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 }; // Checks if an event happened on an element within another element // Used in jQuery.event.special.mouseenter and mouseleave handlers var withinElement = function( event ) { // Check if mouse(over|out) are still within the same parent element var parent = event.relatedTarget; // Firefox sometimes assigns relatedTarget a XUL element // which we cannot access the parentNode property of try { // Traverse up the tree while ( parent && parent !== this ) { parent = parent.parentNode; } if ( parent !== this ) { // set the correct event type event.type = event.data; // handle event if we actually just moused on to a non sub-element jQuery.event.handle.apply( this, arguments ); } // assuming we've left the element since we most likely mousedover a xul element } catch(e) { } }, // In case of event delegation, we only need to rename the event.type, // liveHandler will take care of the rest. delegate = function( event ) { event.type = event.data; jQuery.event.handle.apply( this, arguments ); }; // Create mouseenter and mouseleave events jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { setup: function( data ) { jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig ); }, teardown: function( data ) { jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement ); } }; }); // submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function( data, namespaces ) { if ( this.nodeName.toLowerCase() !== "form" ) { jQuery.event.add(this, "click.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) { e.liveFired = undefined; return trigger( "submit", this, arguments ); } }); jQuery.event.add(this, "keypress.specialSubmit", function( e ) { var elem = e.target, type = elem.type; if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) { e.liveFired = undefined; return trigger( "submit", this, arguments ); } }); } else { return false; } }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialSubmit" ); } }; } // change delegation, happens here so we have bind. if ( !jQuery.support.changeBubbles ) { var changeFilters, getVal = function( elem ) { var type = elem.type, val = elem.value; if ( type === "radio" || type === "checkbox" ) { val = elem.checked; } else if ( type === "select-multiple" ) { val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) { return elem.selected; }).join("-") : ""; } else if ( elem.nodeName.toLowerCase() === "select" ) { val = elem.selectedIndex; } return val; }, testChange = function testChange( e ) { var elem = e.target, data, val; if ( !rformElems.test( elem.nodeName ) || elem.readOnly ) { return; } data = jQuery.data( elem, "_change_data" ); val = getVal(elem); // the current data will be also retrieved by beforeactivate if ( e.type !== "focusout" || elem.type !== "radio" ) { jQuery.data( elem, "_change_data", val ); } if ( data === undefined || val === data ) { return; } if ( data != null || val ) { e.type = "change"; e.liveFired = undefined; return jQuery.event.trigger( e, arguments[1], elem ); } }; jQuery.event.special.change = { filters: { focusout: testChange, beforedeactivate: testChange, click: function( e ) { var elem = e.target, type = elem.type; if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) { return testChange.call( this, e ); } }, // Change has to be called before submit // Keydown will be called before keypress, which is used in submit-event delegation keydown: function( e ) { var elem = e.target, type = elem.type; if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") || (e.keyCode === 32 && (type === "checkbox" || type === "radio")) || type === "select-multiple" ) { return testChange.call( this, e ); } }, // Beforeactivate happens also before the previous element is blurred // with this event you can't trigger a change event, but you can store // information beforeactivate: function( e ) { var elem = e.target; jQuery.data( elem, "_change_data", getVal(elem) ); } }, setup: function( data, namespaces ) { if ( this.type === "file" ) { return false; } for ( var type in changeFilters ) { jQuery.event.add( this, type + ".specialChange", changeFilters[type] ); } return rformElems.test( this.nodeName ); }, teardown: function( namespaces ) { jQuery.event.remove( this, ".specialChange" ); return rformElems.test( this.nodeName ); } }; changeFilters = jQuery.event.special.change.filters; // Handle when the input is .focus()'d changeFilters.focus = changeFilters.beforeactivate; } function trigger( type, elem, args ) { args[0].type = type; return jQuery.event.handle.apply( elem, args ); } // Create "bubbling" focus and blur events if ( document.addEventListener ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { jQuery.event.special[ fix ] = { setup: function() { if ( focusCounts[fix]++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --focusCounts[fix] === 0 ) { document.removeEventListener( orig, handler, true ); } } }; function handler( e ) { e = jQuery.event.fix( e ); e.type = fix; return jQuery.event.trigger( e, null, e.target ); } }); } jQuery.each(["bind", "one"], function( i, name ) { jQuery.fn[ name ] = function( type, data, fn ) { // Handle object literals if ( typeof type === "object" ) { for ( var key in type ) { this[ name ](key, data, type[key], fn); } return this; } if ( jQuery.isFunction( data ) || data === false ) { fn = data; data = undefined; } var handler = name === "one" ? jQuery.proxy( fn, function( event ) { jQuery( this ).unbind( event, handler ); return fn.apply( this, arguments ); }) : fn; if ( type === "unload" && name !== "one" ) { this.one( type, data, fn ); } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.add( this[i], type, handler, data ); } } return this; }; }); jQuery.fn.extend({ unbind: function( type, fn ) { // Handle object literals if ( typeof type === "object" && !type.preventDefault ) { for ( var key in type ) { this.unbind(key, type[key]); } } else { for ( var i = 0, l = this.length; i < l; i++ ) { jQuery.event.remove( this[i], type, fn ); } } return this; }, delegate: function( selector, types, data, fn ) { return this.live( types, data, fn, selector ); }, undelegate: function( selector, types, fn ) { if ( arguments.length === 0 ) { return this.unbind( "live" ); } else { return this.die( types, null, fn, selector ); } }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { if ( this[0] ) { var event = jQuery.Event( type ); event.preventDefault(); event.stopPropagation(); jQuery.event.trigger( event, data, this[0] ); return event.result; } }, toggle: function( fn ) { // Save reference to arguments for access in closure var args = arguments, i = 1; // link all the functions, so any of them can unbind this click handler while ( i < args.length ) { jQuery.proxy( fn, args[ i++ ] ); } return this.click( jQuery.proxy( fn, 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; })); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } }); var liveMap = { focus: "focusin", blur: "focusout", mouseenter: "mouseover", mouseleave: "mouseout" }; jQuery.each(["live", "die"], function( i, name ) { jQuery.fn[ name ] = function( types, data, fn, origSelector /* Internal Use Only */ ) { var type, i = 0, match, namespaces, preType, selector = origSelector || this.selector, context = origSelector ? this : jQuery( this.context ); if ( typeof types === "object" && !types.preventDefault ) { for ( var key in types ) { context[ name ]( key, data, types[key], selector ); } return this; } if ( jQuery.isFunction( data ) ) { fn = data; data = undefined; } types = (types || "").split(" "); while ( (type = types[ i++ ]) != null ) { match = rnamespaces.exec( type ); namespaces = ""; if ( match ) { namespaces = match[0]; type = type.replace( rnamespaces, "" ); } if ( type === "hover" ) { types.push( "mouseenter" + namespaces, "mouseleave" + namespaces ); continue; } preType = type; if ( type === "focus" || type === "blur" ) { types.push( liveMap[ type ] + namespaces ); type = type + namespaces; } else { type = (liveMap[ type ] || type) + namespaces; } if ( name === "live" ) { // bind live handler for ( var j = 0, l = context.length; j < l; j++ ) { jQuery.event.add( context[j], "live." + liveConvert( type, selector ), { data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } ); } } else { // unbind live handler context.unbind( "live." + liveConvert( type, selector ), fn ); } } return this; }; }); function liveHandler( event ) { var stop, maxLevel, related, match, handleObj, elem, j, i, l, data, close, namespace, ret, elems = [], selectors = [], events = jQuery.data( this, this.nodeType ? "events" : "__events__" ); if ( typeof events === "function" ) { events = events.events; } // Make sure we avoid non-left-click bubbling in Firefox (#3861) if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) { return; } if ( event.namespace ) { namespace = new RegExp("(^|\\.)" + event.namespace.split(".").join("\\.(?:.*\\.)?") + "(\\.|$)"); } event.liveFired = this; var live = events.live.slice(0); for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( handleObj.origType.replace( rnamespaces, "" ) === event.type ) { selectors.push( handleObj.selector ); } else { live.splice( j--, 1 ); } } match = jQuery( event.target ).closest( selectors, event.currentTarget ); for ( i = 0, l = match.length; i < l; i++ ) { close = match[i]; for ( j = 0; j < live.length; j++ ) { handleObj = live[j]; if ( close.selector === handleObj.selector && (!namespace || namespace.test( handleObj.namespace )) ) { elem = close.elem; related = null; // Those two events require additional checking if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) { event.type = handleObj.preType; related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0]; } if ( !related || related !== elem ) { elems.push({ elem: elem, handleObj: handleObj, level: close.level }); } } } } for ( i = 0, l = elems.length; i < l; i++ ) { match = elems[i]; if ( maxLevel && match.level > maxLevel ) { break; } event.currentTarget = match.elem; event.data = match.handleObj.data; event.handleObj = match.handleObj; ret = match.handleObj.origHandler.apply( match.elem, arguments ); if ( ret === false || event.isPropagationStopped() ) { maxLevel = match.level; if ( ret === false ) { stop = false; } if ( event.isImmediatePropagationStopped() ) { break; } } } return stop; } function liveConvert( type, selector ) { return (type && type !== "*" ? type + "." : "") + selector.replace(rperiod, "`").replace(rspace, "&"); } 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").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.bind( name, data, fn ) : this.trigger( name ); }; if ( jQuery.attrFn ) { jQuery.attrFn[ name ] = true; } }); // Prevent memory leaks in IE // Window isn't included so as not to unbind existing unload events // More info: // - http://isaacschlueter.com/2006/10/msie-memory-leaks/ if ( window.attachEvent && !window.addEventListener ) { jQuery(window).bind("unload", function() { for ( var id in jQuery.cache ) { if ( jQuery.cache[ id ].handle ) { // Try/Catch is to handle iframes being unloaded, see #4280 try { jQuery.event.remove( jQuery.cache[ id ].handle.elem ); } catch(e) {} } } }); } /*! * Sizzle CSS Selector Engine - v1.0 * Copyright 2009, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * More information: http://sizzlejs.com/ */ (function(){ var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, done = 0, toString = Object.prototype.toString, hasDuplicate = false, baseHasDuplicate = true; // 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 ); } 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 ); } } } 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; if ( !expr ) { return []; } for ( var i = 0, l = Expr.order.length; i < l; i++ ) { var match, type = Expr.order[i]; if ( (match = Expr.leftMatch[ type ].exec( expr )) ) { var left = match[1]; match.splice( 1, 1 ); if ( left.substr( left.length - 1 ) !== "\\" ) { match[1] = (match[1] || "").replace(/\\/g, ""); set = Expr.find[ type ]( match, context, isXML ); if ( set != null ) { expr = expr.replace( Expr.match[ type ], "" ); break; } } } } if ( !set ) { set = context.getElementsByTagName( "*" ); } return { set: set, expr: expr }; }; Sizzle.filter = function( expr, set, inplace, not ) { var match, anyFound, old = expr, result = [], curLoop = set, isXMLFilter = set && set[0] && Sizzle.isXML( set[0] ); while ( expr && set.length ) { for ( var type in Expr.filter ) { if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) { var found, item, 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 ( var i = 0; (item = curLoop[i]) != null; i++ ) { if ( item ) { found = filter( item, match, i, curLoop ); var 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 "Syntax error, unrecognized expression: " + msg; }; 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|)\s*\]/, TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/, CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/, 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" ); } }, relative: { "+": function(checkSet, part){ var isPartStr = typeof part === "string", isTag = isPartStr && !/\W/.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 && !/\W/.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" && !/\W/.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" && !/\W/.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 ) { return context.getElementsByTagName( match[1] ); } }, preFilter: { CLASS: function( match, curLoop, inplace, result, not, isXML ) { match = " " + match[1].replace(/\\/g, "") + " "; 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]/g, " ").indexOf(match) >= 0) ) { if ( !inplace ) { result.push( elem ); } } else if ( inplace ) { curLoop[i] = false; } } } return false; }, ID: function( match ) { return match[1].replace(/\\/g, ""); }, TAG: function( match, curLoop ) { return match[1].toLowerCase(); }, CHILD: function( match ) { if ( match[1] === "nth" ) { // 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; } // TODO: Move to normal caching system match[0] = done++; return match; }, ATTR: function( match, curLoop, inplace, result, not, isXML ) { var name = match[1].replace(/\\/g, ""); if ( !isXML && Expr.attrMap[name] ) { match[1] = Expr.attrMap[name]; } 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 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 ) { return "text" === elem.type; }, radio: function( elem ) { return "radio" === elem.type; }, checkbox: function( elem ) { return "checkbox" === elem.type; }, file: function( elem ) { return "file" === elem.type; }, password: function( elem ) { return "password" === elem.type; }, submit: function( elem ) { return "submit" === elem.type; }, image: function( elem ) { return "image" === elem.type; }, reset: function( elem ) { return "reset" === elem.type; }, button: function( elem ) { return "button" === elem.type || elem.nodeName.toLowerCase() === "button"; }, input: function( elem ) { return (/input|select|textarea|button/i).test( elem.nodeName ); } }, 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 || Sizzle.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( "Syntax error, unrecognized expression: " + name ); } }, CHILD: function( elem, match ) { var 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": var first = match[2], last = match[3]; if ( first === 1 && last === 0 ) { return true; } var doneName = match[0], parent = elem.parentNode; if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) { var count = 0; for ( node = parent.firstChild; node; node = node.nextSibling ) { if ( node.nodeType === 1 ) { node.nodeIndex = ++count; } } parent.sizcache = doneName; } var 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.toLowerCase() === match; }, CLASS: function( elem, match ) { return (" " + (elem.className || elem.getAttribute("class")) + " ") .indexOf( match ) > -1; }, ATTR: function( elem, match ) { var name = match[1], result = 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 === "=" ? 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 ) { var al, bl, ap = [], bp = [], aup = a.parentNode, bup = b.parentNode, cur = aup; // The nodes are identical, we can exit early if ( a === b ) { hasDuplicate = true; return 0; // If the nodes are siblings (or identical) we can do a quick check } else 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; }; } // Utility function for retreiving the text value of an array of DOM nodes Sizzle.getText = function( elems ) { var ret = "", elem; for ( var i = 0; elems[i]; i++ ) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if ( elem.nodeType === 3 || elem.nodeType === 4 ) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if ( elem.nodeType !== 8 ) { ret += Sizzle.getText( elem.childNodes ); } } return ret; }; // 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; // Make sure that attribute selectors are quoted query = query.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']"); // Only use querySelectorAll on non-XML documents // (ID selectors don't work in non-HTML documents) if ( !seed && !Sizzle.isXML(context) ) { if ( context.nodeType === 9 ) { 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 old = context.getAttribute( "id" ), nid = old || id; if ( !old ) { context.setAttribute( "id", nid ); } try { return makeArray( context.querySelectorAll( "#" + nid + " " + query ), extra ); } catch(pseudoError) { } finally { if ( !old ) { context.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, 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; } if ( matches ) { 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 ) ) { return matches.call( node, expr ); } } 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.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 && !isXML ){ elem.sizcache = 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.sizcache === doneName ) { match = checkSet[elem.sizset]; break; } if ( elem.nodeType === 1 ) { if ( !isXML ) { elem.sizcache = 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 ) { 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 ); } return Sizzle.filter( later, tmpSet ); }; // EXPOSE 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; jQuery.fn.extend({ find: function( selector ) { var ret = this.pushStack( "", "find", selector ), length = 0; for ( var 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 ( var n = length; n < ret.length; n++ ) { for ( var 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 && jQuery.filter( selector, this ).length > 0; }, closest: function( selectors, context ) { var ret = [], i, l, cur = this[0]; if ( jQuery.isArray( selectors ) ) { var match, selector, matches = {}, level = 1; if ( cur && selectors.length ) { for ( i = 0, l = selectors.length; i < l; i++ ) { selector = selectors[i]; if ( !matches[selector] ) { matches[selector] = jQuery.expr.match.POS.test( selector ) ? jQuery( selector, context || this.context ) : selector; } } while ( cur && cur.ownerDocument && cur !== context ) { for ( selector in matches ) { match = matches[selector]; if ( match.jquery ? match.index(cur) > -1 : jQuery(cur).is(match) ) { ret.push({ selector: selector, elem: cur, level: level }); } } cur = cur.parentNode; level++; } } return ret; } var pos = POS.test( selectors ) ? jQuery( selectors, context || this.context ) : null; 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 ) { 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 ) { if ( !elem || typeof elem === "string" ) { return jQuery.inArray( this[0], // If it receives a string, the selector is used // If it receives nothing, the siblings are used elem ? jQuery( elem ) : this.parent().children() ); } // 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 || this.context ) : jQuery.makeArray( 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 ? 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 ) { 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; }); } var 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+;/, rnocache = /<(?:script|object|embed|option|style)/i, // checked="checked" or checked (html5) rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, raction = /\=([^="'>\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, "", "" ] }; 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 ) { return this.each(function() { jQuery( this ).wrapAll( 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(arguments[0]); 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(arguments[0]).toArray() ); 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( events ) { // Do the clone var ret = this.map(function() { if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) { // IE copies events bound via attachEvent when // using cloneNode. Calling detachEvent on the // clone will also remove the events from the orignal // In order to get around this, we use innerHTML. // Unfortunately, this means some modifications to // attributes in IE that are actually only stored // as properties will not be copied (such as the // the name attribute on an input). var html = this.outerHTML, ownerDocument = this.ownerDocument; if ( !html ) { var div = ownerDocument.createElement("div"); div.appendChild( this.cloneNode(true) ); html = div.innerHTML; } return jQuery.clean([html.replace(rinlinejQuery, "") // Handle the case in IE 8 where action=/test/> self-closes a tag .replace(raction, '="$1">') .replace(rleadingWhitespace, "")], ownerDocument)[0]; } else { return this.cloneNode(true); } }); // Copy the events from the original to the clone if ( events === true ) { cloneCopyEvent( this, ret ); cloneCopyEvent( this.find("*"), ret.find("*") ); } // Return the cloned set return ret; }, 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" && !rnocache.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.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ); } }, 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; i < l; i++ ) { callback.call( table ? root(this[i], first) : this[i], i > 0 || results.cacheable || this.length > 1 ? fragment.cloneNode(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(orig, ret) { var i = 0; ret.each(function() { if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) { return; } var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( var type in events ) { for ( var handler in events[ type ] ) { jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data ); } } } }); } jQuery.buildFragment = function( args, nodes, scripts ) { var fragment, cacheable, cacheresults, doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document); // Only cache "small" (1/2 KB) 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 if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document && !rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) { cacheable = true; cacheresults = jQuery.fragments[ args[0] ]; if ( cacheresults ) { if ( cacheresults !== 1 ) { fragment = cacheresults; } } } if ( !fragment ) { fragment = doc.createDocumentFragment(); jQuery.clean( args, doc, fragment, scripts ); } if ( cacheable ) { jQuery.fragments[ args[0] ] = 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 ); } }; }); jQuery.extend({ clean: function( elems, context, fragment, scripts ) { 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 = []; 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" && !rhtml.test( elem ) ) { elem = context.createTextNode( elem ); } else if ( typeof elem === "string" ) { // 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"); // 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 ( var 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; } if ( elem.nodeType ) { ret.push( elem ); } else { ret = jQuery.merge( ret, elem ); } } if ( fragment ) { 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 ) { ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) ); } 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 ); } else { jQuery.removeEvent( elem, type, data.handle ); } } } 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 || "" ); } if ( elem.parentNode ) { elem.parentNode.removeChild( elem ); } } var ralpha = /alpha\([^)]*\)/i, ropacity = /opacity=([^)]*)/, rdashAlpha = /-([a-z])/ig, rupper = /([A-Z])/g, rnumpx = /^-?\d+(?:px)?$/i, rnum = /^-?\d/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssWidth = [ "Left", "Right" ], cssHeight = [ "Top", "Bottom" ], curCSS, getComputedStyle, currentStyle, fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; 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: { "zIndex": true, "fontWeight": true, "opacity": true, "zoom": true, "lineHeight": 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, 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 ) { // Make sure that NaN and null values aren't set. See: #7116 if ( typeof value === "number" && isNaN( value ) || value == null ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( typeof value === "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 ) { // Make sure that we're working with the right name var ret, origName = jQuery.camelCase( name ), hooks = jQuery.cssHooks[ origName ]; name = jQuery.cssProps[ origName ] || origName; // 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, origName ); } }, // 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 ]; } }, camelCase: function( string ) { return string.replace( rdashAlpha, fcamelCase ); } }); // 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 ) { val = getWH( elem, name, extra ); } else { jQuery.swap( elem, cssShow, function() { val = getWH( elem, name, extra ); }); } if ( val <= 0 ) { val = curCSS( elem, name, name ); if ( val === "0px" && currentStyle ) { val = currentStyle( elem, name, name ); } if ( val != null ) { // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } } if ( val < 0 || val == null ) { val = elem.style[ name ]; // Should return "auto" instead of 0, use 0 for // temporary backwards-compat return val === "" || val === "auto" ? "0px" : val; } return typeof val === "string" ? val : val + "px"; } }, 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; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // Set the alpha filter to set the opacity var opacity = jQuery.isNaN(value) ? "" : "alpha(opacity=" + value * 100 + ")", filter = style.filter || ""; style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : style.filter + ' ' + opacity; } }; } if ( document.defaultView && document.defaultView.getComputedStyle ) { getComputedStyle = function( elem, newName, name ) { var ret, defaultView, computedStyle; name = name.replace( rupper, "-$1" ).toLowerCase(); if ( !(defaultView = elem.ownerDocument.defaultView) ) { return undefined; } if ( (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, ret = elem.currentStyle && elem.currentStyle[ name ], style = elem.style; // 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.left; // Put in the new values to get a computed value out elem.runtimeStyle.left = elem.currentStyle.left; style.left = name === "fontSize" ? "1em" : (ret || 0); ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; elem.runtimeStyle.left = rsLeft; } return ret === "" ? "auto" : ret; }; } curCSS = getComputedStyle || currentStyle; function getWH( elem, name, extra ) { var which = name === "width" ? cssWidth : cssHeight, val = name === "width" ? elem.offsetWidth : elem.offsetHeight; if ( extra === "border" ) { return val; } jQuery.each( which, function() { if ( !extra ) { val -= parseFloat(jQuery.css( elem, "padding" + this )) || 0; } if ( extra === "margin" ) { val += parseFloat(jQuery.css( elem, "margin" + this )) || 0; } else { val -= parseFloat(jQuery.css( elem, "border" + this + "Width" )) || 0; } }); return val; } 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.display || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } var jsc = jQuery.now(), rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, rselectTextarea = /^(?:select|textarea)/i, rinput = /^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i, rnoContent = /^(?:GET|HEAD)$/, rbracket = /\[\]$/, jsre = /\=\?(&|$)/, rquery = /\?/, rts = /([?&])_=[^&]*/, rurl = /^(\w+:)?\/\/([^\/?#]+)/, r20 = /%20/g, rhash = /#.*$/, // Keep a copy of the old load method _load = jQuery.fn.load; 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 = null; // 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: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // 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(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); 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 }; }) : { name: elem.name, value: val }; }).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.bind(o, f); }; }); jQuery.extend({ get: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = null; } return jQuery.ajax({ type: "GET", url: url, data: data, success: callback, dataType: type }); }, getScript: function( url, callback ) { return jQuery.get(url, null, callback, "script"); }, getJSON: function( url, data, callback ) { return jQuery.get(url, data, callback, "json"); }, post: function( url, data, callback, type ) { // shift arguments if data argument was omited if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = {}; } return jQuery.ajax({ type: "POST", url: url, data: data, success: callback, dataType: type }); }, ajaxSetup: function( settings ) { jQuery.extend( jQuery.ajaxSettings, settings ); }, ajaxSettings: { url: location.href, global: true, type: "GET", contentType: "application/x-www-form-urlencoded", processData: true, async: true, /* timeout: 0, data: null, username: null, password: null, traditional: false, */ // This function can be overriden by calling jQuery.ajaxSetup xhr: function() { return new window.XMLHttpRequest(); }, accepts: { xml: "application/xml, text/xml", html: "text/html", script: "text/javascript, application/javascript", json: "application/json, text/javascript", text: "text/plain", _default: "*/*" } }, ajax: function( origSettings ) { var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings), jsonp, status, data, type = s.type.toUpperCase(), noContent = rnoContent.test(type); s.url = s.url.replace( rhash, "" ); // Use original (not extended) context object if it was provided s.context = origSettings && origSettings.context != null ? origSettings.context : s; // convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Handle JSONP Parameter Callbacks if ( s.dataType === "jsonp" ) { if ( type === "GET" ) { if ( !jsre.test( s.url ) ) { s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?"; } } else if ( !s.data || !jsre.test(s.data) ) { s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?"; } s.dataType = "json"; } // Build temporary JSONP function if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) { jsonp = s.jsonpCallback || ("jsonp" + jsc++); // Replace the =? sequence both in the query string and the data if ( s.data ) { s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1"); } s.url = s.url.replace(jsre, "=" + jsonp + "$1"); // We need to make sure // that a JSONP style response is executed properly s.dataType = "script"; // Handle JSONP-style loading var customJsonp = window[ jsonp ]; window[ jsonp ] = function( tmp ) { if ( jQuery.isFunction( customJsonp ) ) { customJsonp( tmp ); } else { // Garbage collect window[ jsonp ] = undefined; try { delete window[ jsonp ]; } catch( jsonpError ) {} } data = tmp; jQuery.handleSuccess( s, xhr, status, data ); jQuery.handleComplete( s, xhr, status, data ); if ( head ) { head.removeChild( script ); } }; } if ( s.dataType === "script" && s.cache === null ) { s.cache = false; } if ( s.cache === false && noContent ) { var ts = jQuery.now(); // try replacing _= if it is there var 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 : ""); } // If data is available, append data to url for GET/HEAD requests if ( s.data && noContent ) { s.url += (rquery.test(s.url) ? "&" : "?") + s.data; } // Watch for a new set of requests if ( s.global && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Matches an absolute URL, and saves the domain var parts = rurl.exec( s.url ), remote = parts && (parts[1] && parts[1].toLowerCase() !== location.protocol || parts[2].toLowerCase() !== location.host); // If we're requesting a remote document // and trying to load JSON or Script with a GET if ( s.dataType === "script" && type === "GET" && remote ) { var head = document.getElementsByTagName("head")[0] || document.documentElement; var script = document.createElement("script"); if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Handle Script loading if ( !jsonp ) { var done = false; // Attach handlers for all browsers script.onload = script.onreadystatechange = function() { if ( !done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") ) { done = true; jQuery.handleSuccess( s, xhr, status, data ); jQuery.handleComplete( s, xhr, status, data ); // Handle memory leak in IE script.onload = script.onreadystatechange = null; if ( head && script.parentNode ) { head.removeChild( script ); } } }; } // 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 ); // We handle everything using the script element injection return undefined; } var requestDone = false; // Create the request object var xhr = s.xhr(); if ( !xhr ) { return; } // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open(type, s.url, s.async, s.username, s.password); } else { xhr.open(type, s.url, s.async); } // Need an extra try/catch for cross domain requests in Firefox 3 try { // Set content-type if data specified and content-body is valid for this type if ( (s.data != null && !noContent) || (origSettings && origSettings.contentType) ) { xhr.setRequestHeader("Content-Type", s.contentType); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[s.url] ) { xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]); } if ( jQuery.etag[s.url] ) { xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]); } } // Set header so the called script knows that it's an XMLHttpRequest // Only send the header if it's not a remote XHR if ( !remote ) { xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); } // Set the Accepts header for the server, depending on the dataType xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ? s.accepts[ s.dataType ] + ", */*; q=0.01" : s.accepts._default ); } catch( headerError ) {} // Allow custom headers/mimetypes and early abort if ( s.beforeSend && s.beforeSend.call(s.context, xhr, s) === false ) { // Handle the global AJAX counter if ( s.global && jQuery.active-- === 1 ) { jQuery.event.trigger( "ajaxStop" ); } // close opended socket xhr.abort(); return false; } if ( s.global ) { jQuery.triggerGlobal( s, "ajaxSend", [xhr, s] ); } // Wait for a response to come back var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) { // The request was aborted if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) { // Opera doesn't call onreadystatechange before this point // so we simulate the call if ( !requestDone ) { jQuery.handleComplete( s, xhr, status, data ); } requestDone = true; if ( xhr ) { xhr.onreadystatechange = jQuery.noop; } // The transfer is complete and the data is available, or the request timed out } else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) { requestDone = true; xhr.onreadystatechange = jQuery.noop; status = isTimeout === "timeout" ? "timeout" : !jQuery.httpSuccess( xhr ) ? "error" : s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" : "success"; var errMsg; if ( status === "success" ) { // Watch for, and catch, XML document parse errors try { // process the data (runs the xml through httpData regardless of callback) data = jQuery.httpData( xhr, s.dataType, s ); } catch( parserError ) { status = "parsererror"; errMsg = parserError; } } // Make sure that the request was successful or notmodified if ( status === "success" || status === "notmodified" ) { // JSONP handles its own success callback if ( !jsonp ) { jQuery.handleSuccess( s, xhr, status, data ); } } else { jQuery.handleError( s, xhr, status, errMsg ); } // Fire the complete handlers if ( !jsonp ) { jQuery.handleComplete( s, xhr, status, data ); } if ( isTimeout === "timeout" ) { xhr.abort(); } // Stop memory leaks if ( s.async ) { xhr = null; } } }; // Override the abort handler, if we can (IE 6 doesn't allow it, but that's OK) // Opera doesn't fire onreadystatechange at all on abort try { var oldAbort = xhr.abort; xhr.abort = function() { if ( xhr ) { // oldAbort has no call property in IE7 so // just do it this way, which works in all // browsers Function.prototype.call.call( oldAbort, xhr ); } onreadystatechange( "abort" ); }; } catch( abortError ) {} // Timeout checker if ( s.async && s.timeout > 0 ) { setTimeout(function() { // Check to see if the request is still happening if ( xhr && !requestDone ) { onreadystatechange( "timeout" ); } }, s.timeout); } // Send the data try { xhr.send( noContent || s.data == null ? null : s.data ); } catch( sendError ) { jQuery.handleError( s, xhr, null, sendError ); // Fire the complete handlers jQuery.handleComplete( s, xhr, status, data ); } // firefox 1.5 doesn't fire statechange for sync requests if ( !s.async ) { onreadystatechange(); } // return XMLHttpRequest to allow aborting the request etc. return xhr; }, // 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 ) { // 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) && obj.length ) { // 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" ) { if ( jQuery.isEmptyObject( obj ) ) { add( prefix, "" ); // Serialize object item. } else { jQuery.each( obj, function( k, v ) { buildParams( prefix + "[" + k + "]", v, 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: {}, handleError: function( s, xhr, status, e ) { // If a local callback was specified, fire it if ( s.error ) { s.error.call( s.context, xhr, status, e ); } // Fire the global callback if ( s.global ) { jQuery.triggerGlobal( s, "ajaxError", [xhr, s, e] ); } }, handleSuccess: function( s, xhr, status, data ) { // If a local callback was specified, fire it and pass it the data if ( s.success ) { s.success.call( s.context, data, status, xhr ); } // Fire the global callback if ( s.global ) { jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] ); } }, handleComplete: function( s, xhr, status ) { // Process result if ( s.complete ) { s.complete.call( s.context, xhr, status ); } // The request was completed if ( s.global ) { jQuery.triggerGlobal( s, "ajaxComplete", [xhr, s] ); } // Handle the global AJAX counter if ( s.global && jQuery.active-- === 1 ) { jQuery.event.trigger( "ajaxStop" ); } }, triggerGlobal: function( s, type, args ) { (s.context && s.context.url == null ? jQuery(s.context) : jQuery.event).trigger(type, args); }, // Determines if an XMLHttpRequest was successful or not httpSuccess: function( xhr ) { try { // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450 return !xhr.status && location.protocol === "file:" || xhr.status >= 200 && xhr.status < 300 || xhr.status === 304 || xhr.status === 1223; } catch(e) {} return false; }, // Determines if an XMLHttpRequest returns NotModified httpNotModified: function( xhr, url ) { var lastModified = xhr.getResponseHeader("Last-Modified"), etag = xhr.getResponseHeader("Etag"); if ( lastModified ) { jQuery.lastModified[url] = lastModified; } if ( etag ) { jQuery.etag[url] = etag; } return xhr.status === 304; }, httpData: function( xhr, type, s ) { var ct = xhr.getResponseHeader("content-type") || "", xml = type === "xml" || !type && ct.indexOf("xml") >= 0, data = xml ? xhr.responseXML : xhr.responseText; if ( xml && data.documentElement.nodeName === "parsererror" ) { jQuery.error( "parsererror" ); } // Allow a pre-filtering function to sanitize the response // s is checked to keep backwards compatibility if ( s && s.dataFilter ) { data = s.dataFilter( data, type ); } // The filter can actually parse the response if ( typeof data === "string" ) { // Get the JavaScript object, if JSON is used. if ( type === "json" || !type && ct.indexOf("json") >= 0 ) { data = jQuery.parseJSON( data ); // If the type is "script", eval it in global context } else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) { jQuery.globalEval( data ); } } return data; } }); /* * Create the request object; 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. */ if ( window.ActiveXObject ) { jQuery.ajaxSettings.xhr = function() { if ( window.location.protocol !== "file:" ) { try { return new window.XMLHttpRequest(); } catch(xhrError) {} } try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch(activeError) {} }; } // Does this browser support XHR requests? jQuery.support.ajax = !!jQuery.ajaxSettings.xhr(); var elemdisplay = {}, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = /^([+\-]=)?([\d+.\-]+)(.*)$/, timerId, fxAttrs = [ // height animations [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ], // width animations [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ], // opacity animations [ "opacity" ] ]; 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]; 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]; 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 { for ( var i = 0, j = this.length; i < j; i++ ) { var display = jQuery.css( this[i], "display" ); if ( display !== "none" ) { jQuery.data( this[i], "olddisplay", display ); } } // Set the display of the elements in a second loop // to avoid the constant reflow for ( i = 0; i < j; i++ ) { 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 ); } return this[ optall.queue === false ? "each" : "queue" ](function() { // XXX 'this' does not always have a nodeName when running the // test suite var opt = jQuery.extend({}, optall), p, isElement = this.nodeType === 1, hidden = isElement && jQuery(this).is(":hidden"), self = this; for ( p in prop ) { var name = jQuery.camelCase( p ); if ( p !== name ) { prop[ name ] = prop[ p ]; delete prop[ p ]; p = name; } if ( prop[p] === "hide" && hidden || prop[p] === "show" && !hidden ) { return opt.complete.call(this); } if ( isElement && ( p === "height" || p === "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" ) { if ( !jQuery.support.inlineBlockNeedsLayout ) { this.style.display = "inline-block"; } else { var display = defaultDisplay(this.nodeName); // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( display === "inline" ) { this.style.display = "inline-block"; } else { this.style.display = "inline"; this.style.zoom = 1; } } } } if ( jQuery.isArray( prop[p] ) ) { // Create (if needed) and add to specialEasing (opt.specialEasing = opt.specialEasing || {})[p] = prop[p][1]; prop[p] = prop[p][0]; } } if ( opt.overflow != null ) { this.style.overflow = "hidden"; } opt.curAnim = jQuery.extend({}, prop); jQuery.each( prop, function( name, val ) { var e = new jQuery.fx( self, opt, name ); if ( rfxtypes.test(val) ) { e[ val === "toggle" ? hidden ? "show" : "hide" : val ]( prop ); } else { var parts = rfxnum.exec(val), start = e.cur() || 0; if ( parts ) { var end = parseFloat( parts[2] ), unit = parts[3] || "px"; // We need to compute starting value if ( unit !== "px" ) { jQuery.style( self, name, (end || 1) + unit); start = ((end || 1) / e.cur()) * start; jQuery.style( self, name, 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; }); }, stop: function( clearQueue, gotoEnd ) { var timers = jQuery.timers; if ( clearQueue ) { this.queue([]); } this.each(function() { // go in reverse order so anything added to the queue during the loop is ignored for ( var i = timers.length - 1; i >= 0; i-- ) { if ( timers[i].elem === this ) { if (gotoEnd) { // force the next step to be the last timers[i](true); } timers.splice(i, 1); } } }); // start the next in the queue if the last step wasn't forced if ( !gotoEnd ) { this.dequeue(); } return this; } }); 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; // Queueing opt.old = opt.complete; opt.complete = function() { if ( opt.queue !== false ) { jQuery(this).dequeue(); } if ( jQuery.isFunction( opt.old ) ) { opt.old.call( 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; if ( !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 r = parseFloat( jQuery.css( this.elem, this.prop ) ); return r && r > -10000 ? r : 0; }, // Start an animation from one number to another custom: function( from, to, unit ) { var self = this, fx = jQuery.fx; this.startTime = jQuery.now(); this.start = from; this.end = to; this.unit = unit || this.unit || "px"; this.now = this.start; this.pos = this.state = 0; function t( gotoEnd ) { return self.step(gotoEnd); } t.elem = this.elem; if ( t() && jQuery.timers.push(t) && !timerId ) { timerId = setInterval(fx.tick, fx.interval); } }, // Simple 'show' function show: function() { // Remember where we started, so that we can go back to it later this.options.orig[this.prop] = 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 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.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 t = jQuery.now(), done = true; if ( gotoEnd || t >= this.options.duration + this.startTime ) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[ this.prop ] = true; for ( var i in this.options.curAnim ) { if ( this.options.curAnim[i] !== true ) { done = false; } } if ( done ) { // Reset the overflow if ( this.options.overflow != null && !jQuery.support.shrinkWrapBlocks ) { var elem = this.elem, options = this.options; jQuery.each( [ "", "X", "Y" ], function (index, value) { elem.style[ "overflow" + value ] = options.overflow[index]; } ); } // Hide the element if the "hide" operation was done if ( this.options.hide ) { jQuery(this.elem).hide(); } // Reset the properties, if the item has been hidden or shown if ( this.options.hide || this.options.show ) { for ( var p in this.options.curAnim ) { jQuery.style( this.elem, p, this.options.orig[p] ); } } // Execute the complete function this.options.complete.call( this.elem ); } return false; } else { var n = t - this.startTime; this.state = n / this.options.duration; // Perform the easing function, defaults to swing var specialEasing = this.options.specialEasing && this.options.specialEasing[this.prop]; var defaultEasing = this.options.easing || (jQuery.easing.swing ? "swing" : "linear"); this.pos = jQuery.easing[specialEasing || defaultEasing](this.state, n, 0, 1, this.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 timers = jQuery.timers; for ( var i = 0; i < timers.length; i++ ) { if ( !timers[i]() ) { 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.prop === "width" || fx.prop === "height" ? Math.max(0, fx.now) : fx.now) + fx.unit; } else { fx.elem[ fx.prop ] = fx.now; } } } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } function defaultDisplay( nodeName ) { if ( !elemdisplay[ nodeName ] ) { var elem = jQuery("<" + nodeName + ">").appendTo("body"), display = elem.css("display"); elem.remove(); if ( display === "none" || display === "" ) { display = "block"; } 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: 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 ); } jQuery.offset.initialize(); 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.offset.supportsFixedPosition && 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.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) { top += parseFloat( computedStyle.borderTopWidth ) || 0; left += parseFloat( computedStyle.borderLeftWidth ) || 0; } prevOffsetParent = offsetParent; offsetParent = elem.offsetParent; } if ( jQuery.offset.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.offset.supportsFixedPosition && prevComputedStyle.position === "fixed" ) { top += Math.max( docElem.scrollTop, body.scrollTop ); left += Math.max( docElem.scrollLeft, body.scrollLeft ); } return { top: top, left: left }; }; } jQuery.offset = { initialize: function() { var body = document.body, container = document.createElement("div"), innerDiv, checkDiv, table, td, bodyMarginTop = parseFloat( jQuery.css(body, "marginTop") ) || 0, html = "<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; jQuery.extend( container.style, { position: "absolute", top: 0, left: 0, margin: 0, border: 0, width: "1px", height: "1px", visibility: "hidden" } ); container.innerHTML = html; body.insertBefore( container, body.firstChild ); innerDiv = container.firstChild; checkDiv = innerDiv.firstChild; td = innerDiv.nextSibling.firstChild.firstChild; this.doesNotAddBorder = (checkDiv.offsetTop !== 5); this.doesAddBorderForTableAndCells = (td.offsetTop === 5); checkDiv.style.position = "fixed"; checkDiv.style.top = "20px"; // safari subtracts parent border width here which is 5px this.supportsFixedPosition = (checkDiv.offsetTop === 20 || checkDiv.offsetTop === 15); checkDiv.style.position = checkDiv.style.top = ""; innerDiv.style.overflow = "hidden"; innerDiv.style.position = "relative"; this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5); this.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== bodyMarginTop); body.removeChild( container ); body = container = innerDiv = checkDiv = table = td = null; jQuery.offset.initialize = jQuery.noop; }, bodyOffset: function( body ) { var top = body.offsetTop, left = body.offsetLeft; jQuery.offset.initialize(); if ( jQuery.offset.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" && 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 absolute if ( calculatePosition ) { curPosition = curElem.position(); } curTop = calculatePosition ? curPosition.top : parseInt( curCSSTop, 10 ) || 0; curLeft = calculatePosition ? curPosition.left : parseInt( curCSSLeft, 10 ) || 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 = this[0], win; if ( !elem ) { return null; } if ( val !== undefined ) { // 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; } }); } else { 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 ]; } }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create 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() { return this[0] ? parseFloat( jQuery.css( this[0], type, "padding" ) ) : null; }; // outerHeight and outerWidth jQuery.fn["outer" + name] = function( margin ) { return this[0] ? parseFloat( jQuery.css( this[0], type, margin ? "margin" : "border" ) ) : 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 return elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] || elem.document.body[ "client" + name ]; // 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.isNaN( ret ) ? orig : ret; // 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" ); } }; }); })(window);
packages/material-ui-icons/legacy/PersonPinCircleOutlined.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M12 1C7.59 1 4 4.59 4 9c0 5.57 6.96 13.34 7.26 13.67l.74.82.74-.82C13.04 22.34 20 14.57 20 9c0-4.41-3.59-8-8-8zm0 19.47C9.82 17.86 6 12.54 6 9c0-3.31 2.69-6 6-6s6 2.69 6 6c0 3.83-4.25 9.36-6 11.47zM12 9c.83 0 1.5-.67 1.5-1.5S12.83 6 12 6s-1.5.68-1.5 1.5c0 .83.67 1.5 1.5 1.5zm0 1c-1 0-3 .5-3 1.5v.12c.73.84 1.8 1.38 3 1.38s2.27-.54 3-1.38v-.12c0-1-2-1.5-3-1.5z" /></React.Fragment> , 'PersonPinCircleOutlined');
examples/react-es6/CheckboxWithLabel.js
bluebridgedigital/jest
import React from 'react'; class CheckboxWithLabel extends React.Component { constructor(props) { super(props); this.state = {isChecked: false}; // since auto-binding is disabled for React's class model // we can prebind methods here // http://facebook.github.io/react/blog/2015/01/27/react-v0.13.0-beta-1.html#autobinding this.onChange = this.onChange.bind(this); } onChange() { this.setState({isChecked: !this.state.isChecked}); } render() { return ( <label> <input type="checkbox" checked={this.state.isChecked} onChange={this.onChange} /> {this.state.isChecked ? this.props.labelOn : this.props.labelOff} </label> ); } } export default CheckboxWithLabel;
entry_types/scrolled/package/src/frontend/usePhonePlatform.js
codevise/pageflow
import React from 'react'; import PhonePlatformContext from './PhonePlatformContext'; export function usePhonePlatform() { return React.useContext(PhonePlatformContext); }
src/TableColumn.js
AllenFang/react-bootstrap-table
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import Const from './Const'; import Util from './util'; class TableColumn extends Component { constructor(props) { super(props); } /* eslint no-unused-vars: [0, { "args": "after-used" }] */ shouldComponentUpdate(nextProps, nextState) { const { children } = this.props; let shouldUpdated = this.props.width !== nextProps.width || this.props.className !== nextProps.className || this.props.hidden !== nextProps.hidden || this.props.dataAlign !== nextProps.dataAlign || this.props.isFocus !== nextProps.isFocus || 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 || children.props.disabled !== nextProps.children.props.disabled; } 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; } } componentDidMount() { const dom = ReactDOM.findDOMNode(this); if (this.props.isFocus) { dom.focus(); } else { dom.blur(); } } componentDidUpdate() { const dom = ReactDOM.findDOMNode(this); if (this.props.isFocus) { dom.focus(); } else { dom.blur(); } } handleCellEdit = e => { try { if (this.props.cellEdit.mode === Const.CELL_EDIT_DBCLICK) { if (document.selection && document.selection.empty) { document.selection.empty(); } else if (window.getSelection) { const sel = window.getSelection(); sel.removeAllRanges(); } } } catch (err) {} /* eslint no-empty: 0 */ this.props.onEdit( this.props.rIndex + 1, e.currentTarget.cellIndex, e); if (this.props.cellEdit.mode !== Const.CELL_EDIT_DBCLICK) { this.props.onClick(e, this.props.rIndex + 1, e.currentTarget.cellIndex); } } handleCellClick = e => { const { onClick, rIndex } = this.props; if (onClick) { onClick(e, rIndex + 1, e.currentTarget.cellIndex); } } handleKeyDown = e => { if (this.props.keyBoardNav) { this.props.onKeyDown(e); } } render() { const { children, columnTitle, dataAlign, hidden, cellEdit, attrs, style, isFocus, keyBoardNav, tabIndex, customNavStyle, withoutTabIndex, row } = this.props; let { className } = this.props; let tdStyle = { textAlign: dataAlign, display: hidden ? 'none' : null, ...style }; const opts = {}; if (cellEdit) { if (cellEdit.mode === Const.CELL_EDIT_CLICK) { opts.onClick = this.handleCellEdit; } else if (cellEdit.mode === Const.CELL_EDIT_DBCLICK) { opts.onDoubleClick = this.handleCellEdit; } else { opts.onClick = this.handleCellClick; } } if (keyBoardNav && isFocus) { opts.onKeyDown = this.handleKeyDown; } if (isFocus) { if (customNavStyle) { const cusmtStyle = Util.isFunction(customNavStyle) ? customNavStyle(children, row) : customNavStyle; tdStyle = { ...tdStyle, ...cusmtStyle }; } else { className = `${className} default-focus-cell`; } } const attr = {}; if (!withoutTabIndex) attr.tabIndex = tabIndex; return ( <td { ...attr } style={ tdStyle } title={ columnTitle } className={ className } { ...opts } { ...attrs }> { typeof children === 'boolean' ? children.toString() : children } </td> ); } } TableColumn.propTypes = { rIndex: PropTypes.number, dataAlign: PropTypes.string, hidden: PropTypes.bool, className: PropTypes.string, columnTitle: PropTypes.string, children: PropTypes.node, onClick: PropTypes.func, attrs: PropTypes.object, style: PropTypes.object, isFocus: PropTypes.bool, onKeyDown: PropTypes.func, tabIndex: PropTypes.string, withoutTabIndex: PropTypes.bool, keyBoardNav: PropTypes.oneOfType([ PropTypes.bool, PropTypes.object ]), customNavStyle: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), row: PropTypes.any /* only used on custom styling for navigation */ }; TableColumn.defaultProps = { dataAlign: 'left', withoutTabIndex: false, hidden: false, className: '', isFocus: false, keyBoardNav: false }; export default TableColumn;
source/views/building-hours/detail/badge.js
carls-app/carls
/** * @flow * * <Badge/> renders the [Open] / [Closed] / [IDK] badge on the detai view */ import * as React from 'react' import {View, Text, StyleSheet, Platform} from 'react-native' import * as c from '../../components/colors' const BGCOLORS = { Open: c.moneyGreen, Closed: c.salmon, } type Props = {status: string} export class Badge extends React.PureComponent<Props> { render() { const {status} = this.props const bgColor = BGCOLORS[status] || c.goldenrod return ( <View style={[styles.badge, {backgroundColor: bgColor}]}> <Text selectable={true} style={styles.badgeText}> {status} </Text> </View> ) } } const styles = StyleSheet.create({ badge: { marginTop: 20, paddingHorizontal: 12, paddingVertical: 4, borderRadius: 5, alignSelf: 'center', ...Platform.select({ android: { marginBottom: 14, }, }), }, badgeText: { color: c.white, fontSize: 18, }, })
src/lib/markers/implementations/CustomMarker.js
namespace-ee/react-calendar-timeline
import React from 'react' import PropTypes from 'prop-types' import { createMarkerStylesWithLeftOffset, createDefaultRenderer } from './shared' const defaultCustomMarkerRenderer = createDefaultRenderer( 'default-customer-marker-id' ) /** * CustomMarker that is placed based on passed in date prop */ class CustomMarker extends React.Component { static propTypes = { getLeftOffsetFromDate: PropTypes.func.isRequired, renderer: PropTypes.func, date: PropTypes.number.isRequired } static defaultProps = { renderer: defaultCustomMarkerRenderer } render() { const { date } = this.props const leftOffset = this.props.getLeftOffsetFromDate(date) const styles = createMarkerStylesWithLeftOffset(leftOffset) return this.props.renderer({ styles, date }) } } export default CustomMarker
client/src/containers/BulkDeleteConfirmation/tests/BulkDeleteMessage-test.js
silverstripe/silverstripe-asset-admin
/* global jest, jasmine, describe, it, expect, beforeEach, Event */ import React from 'react'; import Component from '../BulkDeleteMessage'; import ShallowRenderer from 'react-test-renderer/shallow'; const unlinkFileWarning = 'Ensure files are removed from content areas prior to deleting them, otherwise they will appear as broken links.'; const noFoldersProps = { folderCount: 0, folderDescendantFileTotals: { totalItems: 0, totalCount: 0 }, }; const oneEmptyFolder = { folderCount: 1, folderDescendantFileTotals: { totalItems: 0, totalCount: 0 }, }; const manyEmptyFolders = { folderCount: 2, folderDescendantFileTotals: { totalItems: 0, totalCount: 0 }, }; const oneFolderProps = { folderCount: 1, folderDescendantFileTotals: { totalItems: 1, totalCount: 5 }, }; const manyfolderProps = { folderCount: 2, folderDescendantFileTotals: { totalItems: 2, totalCount: 10 }, }; const noFilesProps = { fileTotalItems: 0, }; const oneFileProps = { fileTotalItems: 1, }; const manyFilesProps = { fileTotalItems: 2, }; const getMessage = (count) => [ `You're about to delete ${count} file(s) which may be used in your site's content.`, 'Carefully check the file usage on the files before deleting the folder.' ].join(' '); const emptyFolderMessage = 'Are you sure you want to delete this folder?'; const emptyFoldersMessage = 'Are you sure you want to delete these folders?'; describe('BulkDeleteMessage', () => { const renderer = new ShallowRenderer(); describe('Deleting a file and a folder', () => { const testCases = [ [ 'file in use', { ...noFoldersProps, ...oneFileProps }, getMessage('1'), ], [ 'folder in use', { ...noFilesProps, ...oneFolderProps }, getMessage('5'), ], [ 'file and folder in use', { ...oneFileProps, ...oneFolderProps }, getMessage('6'), ], ]; testCases.forEach(([desc, props, expectedMessage]) => { it(desc, () => { renderer.render(<Component {...props} />); const result = renderer.getRenderOutput(); expect(result.props.children.length).toEqual(2); expect(result.props.children[0]).toEqual( <p>{expectedMessage}</p> ); }); }); }); describe('Deleting folders', () => { const testCases = [ [ 'one folder in use', { ...noFilesProps, ...oneFolderProps }, getMessage('5'), ], [ 'multiple folders in use', { ...noFilesProps, ...manyfolderProps }, getMessage('10'), ], ]; testCases.forEach(([desc, props, expectedMessage]) => { it(desc, () => { renderer.render(<Component {...props} />); const result = renderer.getRenderOutput(); expect(result.props.children.length).toEqual(2); expect(result.props.children[0]).toEqual( <p>{expectedMessage}</p> ); }); }); }); describe('Deleting empty folders', () => { const testCases = [ [ 'one empty folder', { ...noFilesProps, ...oneEmptyFolder }, emptyFolderMessage, ], [ 'multiple empty folders', { ...noFilesProps, ...manyEmptyFolders }, emptyFoldersMessage, ], ]; testCases.forEach(([desc, props, expectedMessage]) => { it(desc, () => { renderer.render(<Component {...props} />); const result = renderer.getRenderOutput(); expect(result.props.children.length).toEqual(2); expect(result.props.children[0]).toEqual( <p>{expectedMessage}</p> ); }); }); }); describe('Deleting files', () => { const testCases = [ [ 'one file in use', { ...noFoldersProps, ...oneFileProps }, getMessage('1'), ], [ 'many files in use', { ...noFoldersProps, ...manyFilesProps }, getMessage('2'), ] ]; testCases.forEach(([desc, props, expectedMessage]) => { it(desc, () => { renderer.render(<Component {...props} />); const result = renderer.getRenderOutput(); expect(result.props.children).toEqual([ <p>{expectedMessage}</p>, <p>{unlinkFileWarning}</p> ]); }); }); }); });
client/index.js
AnatolyBelobrovik/itechartlabs
//React Stuff import React from 'react'; import { render } from 'react-dom'; import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; //Redux Stuff import { Provider } from 'react-redux'; import thunk from 'redux-thunk'; import rootReducer from './RootReducer'; import { createStore, applyMiddleware, compose } from 'redux'; //Authorization Stuff import jwtDecode from 'jwt-decode'; import { setAuthorizationToken, setCurrentUser } from './actions/signinActions'; //App routes import App from './components/App'; // User Components import SigninPage from './components/signin/SigninPage'; import SignupPage from './components/signup/SignupPage'; import ProfilePage from './components/profile/ProfilePage'; import EditProfile from './components/profile/EditProfile'; import ResetPasswordPage from './components/recovery/ResetPasswordPage'; import PasswordRecoveryPage from './components/recovery/PasswordRecoveryPage'; //Dashboard Components import AboutPage from './components/about/AboutPage'; import MySurveys from './components/dashboard/MySurveys'; import SurveyTemplates from './components/dashboard/SurveyTemplates'; import Users from './components/dashboard/Users'; //Surveys Components import SurveyLayout from './components/surveys/edit/SurveyLayout'; import Survey from './components/surveys/survey/SurveyLayout'; import ResultsLayout from './components/surveys/results/ResultsLayout'; import SurveyCompletedPage from './components/surveys/survey/SurveyCompletedPage'; //General Components import NotFound from './components//shared/NotFound'; //Higher order component to check if user is not authenticated import RequireAuth from './components/shared/RequireAuth'; import RequireAdminRights from './components/shared/RequireAdminRights'; const store = createStore(rootReducer, compose( applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f ) ); //Check if there is already a jwtToken in localStorage if (localStorage.jwtToken) { setAuthorizationToken(localStorage.jwtToken); store.dispatch(setCurrentUser(jwtDecode(localStorage.jwtToken))); } render( <Provider store={store}> <Router> <App> <Switch> <Route exact path="/" component={SigninPage} /> <Route path="/signin" component={SigninPage} /> <Route path="/signup" component={SignupPage} /> <Route path="/about" component={AboutPage} /> <Route exact path="/profile" component={RequireAuth(ProfilePage)} /> <Route path="/profile/:_id" component={RequireAdminRights(EditProfile)} /> <Route path="/recovery" component={PasswordRecoveryPage} /> <Route path="/reset/:token" component={ResetPasswordPage} /> <Route path="/users" component={RequireAdminRights(Users)} /> <Route path="/surveys/completed" component={SurveyCompletedPage} /> <Route path="/surveys" component={RequireAuth(MySurveys)} /> <Route path="/templates" component={RequireAuth(SurveyTemplates)} /> <Route path="/new" component={RequireAuth(SurveyLayout)} /> <Route path="/edit/:_id" component={RequireAuth(SurveyLayout)} /> <Route path="/survey/:_id" component={RequireAuth(Survey)} /> <Route path="/results/:_id" component={RequireAuth(ResultsLayout)} /> <Route path="*" component={NotFound} /> </Switch> </App> </Router> </Provider>, document.getElementById('app'));
app/javascript/mastodon/features/ui/components/audio_modal.js
imas/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import Audio from 'mastodon/features/audio'; import { connect } from 'react-redux'; import ImmutablePureComponent from 'react-immutable-pure-component'; import { previewState } from './video_modal'; import Footer from 'mastodon/features/picture_in_picture/components/footer'; const mapStateToProps = (state, { statusId }) => ({ accountStaticAvatar: state.getIn(['accounts', state.getIn(['statuses', statusId, 'account']), 'avatar_static']), }); export default @connect(mapStateToProps) class AudioModal extends ImmutablePureComponent { static propTypes = { media: ImmutablePropTypes.map.isRequired, statusId: PropTypes.string.isRequired, accountStaticAvatar: PropTypes.string.isRequired, options: PropTypes.shape({ autoPlay: PropTypes.bool, }), onClose: PropTypes.func.isRequired, onChangeBackgroundColor: PropTypes.func.isRequired, }; static contextTypes = { router: PropTypes.object, }; componentDidMount () { if (this.context.router) { const history = this.context.router.history; history.push(history.location.pathname, previewState); this.unlistenHistory = history.listen(() => { this.props.onClose(); }); } } componentWillUnmount () { if (this.context.router) { this.unlistenHistory(); if (this.context.router.history.location.state === previewState) { this.context.router.history.goBack(); } } } render () { const { media, accountStaticAvatar, statusId, onClose } = this.props; const options = this.props.options || {}; return ( <div className='modal-root__modal audio-modal'> <div className='audio-modal__container'> <Audio src={media.get('url')} alt={media.get('description')} duration={media.getIn(['meta', 'original', 'duration'], 0)} height={150} poster={media.get('preview_url') || accountStaticAvatar} backgroundColor={media.getIn(['meta', 'colors', 'background'])} foregroundColor={media.getIn(['meta', 'colors', 'foreground'])} accentColor={media.getIn(['meta', 'colors', 'accent'])} autoPlay={options.autoPlay} /> </div> <div className='media-modal__overlay'> {statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />} </div> </div> ); } }
packages/react/src/components/UIShell/SkipToContent.js
carbon-design-system/carbon-components
/** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import cx from 'classnames'; import React from 'react'; import PropTypes from 'prop-types'; import { usePrefix } from '../../internal/usePrefix'; const SkipToContent = ({ children, className: customClassName, href, tabIndex, ...rest }) => { const prefix = usePrefix(); const className = cx(`${prefix}--skip-to-content`, customClassName); return ( <a {...rest} className={className} href={href} tabIndex={tabIndex}> {children} </a> ); }; SkipToContent.propTypes = { /** * Provide text to display in the SkipToContent `a` tag */ children: PropTypes.string.isRequired, className: PropTypes.string, /** * Provide the `href` to the id of the element on your package that is the * main content. */ href: PropTypes.string.isRequired, /** * Optionally override the default tabindex of 0 */ tabIndex: PropTypes.string, }; SkipToContent.defaultProps = { children: 'Skip to main content', href: '#main-content', tabIndex: '0', }; export default SkipToContent;
wegas-app/src/main/node/wegas-react-form/src/Script/Views/Button.js
Heigvd/Wegas
import React from 'react'; import { css } from 'glamor'; import classNames from 'classnames'; import IconButton from '../../Components/IconButton'; const removeStatement = css({ color: '#d4d4d4', ':hover': { color: 'gray' }, }); const trashcan = css({ color: 'white', transform: "translate(0, 6px)" }); const container = css({ display: 'inline-block' }); export function RemoveStatementButton(props) { return ( <IconButton {...props} icon={[ 'fa fa-circle fa-stack-2x', `fa fa-trash ${trashcan} fa-stack-1x` ]} tooltip="Delete this item" className={classNames( removeStatement.toString(), container.toString() )} /> ); } export function AddStatementButton(props) { return ( <IconButton {...props} iconColor="#9DC06F" icon="fa fa-plus-circle" /> ); } export function AddOptionButton(props) { return ( <IconButton {...props} iconColor="#9DC06F" icon="fa fa-plus-circle" prefixedLabel /> ); }
src/common/PageNotFound.js
wanhongfu/p2p-book-library-frontend
import React from 'react'; import FineContentDiv from './FineContentDiv' import InnerToolbar from './toolbar/InnerToolbar'; export default class PageNotFound extends React.Component { render() { return ( <div> <InnerToolbar title="We are sorry!" /> <FineContentDiv> <h1>Page Not Found</h1> </FineContentDiv> </div> ); } }
ajax/libs/jquery.fancytree/2.10.2/jquery.fancytree-all.js
dmsanchez86/cdnjs
/*! * jquery.fancytree.js * Dynamic tree view control, with support for lazy loading of branches. * https://github.com/mar10/fancytree/ * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ /** Core Fancytree module. */ // Start of local namespace ;(function($, window, document, undefined) { "use strict"; // prevent duplicate loading if ( $.ui && $.ui.fancytree ) { $.ui.fancytree.warn("Fancytree: ignored duplicate include"); return; } /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; // consoleApply("assert", [!!cond, msg]); $.error("Fancytree assertion failed" + msg); } } _assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)"); function consoleApply(method, args){ var i, s, fn = window.console ? window.console[method] : null; if(fn){ try{ fn.apply(window.console, args); } catch(e) { // IE 8? s = ""; for( i=0; i<args.length; i++){ s += args[i]; } fn(s); } } } /*Return true if x is a FancytreeNode.*/ function _isNode(x){ return !!(x.tree && x.statusNodeType !== undefined); } /** Return true if dotted version string is equal or higher than requested version. * * See http://jsfiddle.net/mar10/FjSAN/ */ function isVersionAtLeast(dottedVersion, major, minor, patch){ var i, v, t, verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }), testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); }); for( i = 0; i < testParts.length; i++ ){ v = verParts[i] || 0; t = testParts[i] || 0; if( v !== t ){ return ( v > t ); } } return true; } /** Return a wrapper that calls sub.methodName() and exposes * this : tree * this._local : tree.ext.EXTNAME * this._super : base.methodName() */ function _makeVirtualFunction(methodName, tree, base, extension, extName){ // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName); // if(rexTestSuper && !rexTestSuper.test(func)){ // // extension.methodName() doesn't call _super(), so no wrapper required // return func; // } // Use an immediate function as closure var proxy = (function(){ var prevFunc = tree[methodName], // org. tree method or prev. proxy baseFunc = extension[methodName], // _local = tree.ext[extName], _super = function(){ return prevFunc.apply(tree, arguments); }, _superApply = function(args){ return prevFunc.apply(tree, args); }; // Return the wrapper function return function(){ var prevLocal = tree._local, prevSuper = tree._super, prevSuperApply = tree._superApply; try{ tree._local = _local; tree._super = _super; tree._superApply = _superApply; return baseFunc.apply(tree, arguments); }finally{ tree._local = prevLocal; tree._super = prevSuper; tree._superApply = prevSuperApply; } }; })(); // end of Immediate Function return proxy; } /** * Subclass `base` by creating proxy functions */ function _subclassObject(tree, base, extension, extName){ // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName); for(var attrName in extension){ if(typeof extension[attrName] === "function"){ if(typeof tree[attrName] === "function"){ // override existing method tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else if(attrName.charAt(0) === "_"){ // Create private methods in tree.ext.EXTENSION namespace tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName); }else{ $.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName); } }else{ // Create member variables in tree.ext.EXTENSION namespace if(attrName !== "options"){ tree.ext[extName][attrName] = extension[attrName]; } } } } function _getResolvedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.resolve();}).promise(); }else{ return $.Deferred(function(){this.resolveWith(context, argArray);}).promise(); } } function _getRejectedPromise(context, argArray){ if(context === undefined){ return $.Deferred(function(){this.reject();}).promise(); }else{ return $.Deferred(function(){this.rejectWith(context, argArray);}).promise(); } } function _makeResolveFunc(deferred, context){ return function(){ deferred.resolveWith(context); }; } function _getElementDataAsDict($el){ // Evaluate 'data-NAME' attributes with special treatment for 'data-json'. var d = $.extend({}, $el.data()), json = d.json; delete d.fancytree; // added to container by widget factory if( json ) { delete d.json; // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5) d = $.extend(d, json); } return d; } // TODO: use currying function _makeNodeTitleMatcher(s){ s = s.toLowerCase(); return function(node){ return node.title.toLowerCase().indexOf(s) >= 0; }; } function _makeNodeTitleStartMatcher(s){ var reMatch = new RegExp("^" + s, "i"); return function(node){ return reMatch.test(node.title); }; } var i, FT = null, // initialized below ENTITY_MAP = {"&": "&amp;", "<": "&lt;", ">": "&gt;", "\"": "&quot;", "'": "&#39;", "/": "&#x2F;"}, IGNORE_KEYCODES = { 16: true, 17: true, 18: true }, SPECIAL_KEYCODES = { 8: "backspace", 9: "tab", 10: "return", 13: "return", // 16: null, 17: null, 18: null, // ignore shift, ctrl, alt 19: "pause", 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home", 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del", 59: ";", 61: "=", 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7", 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111: "/", 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8", 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", 221: "]", 222: "'"}, MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" }, //boolean attributes that can be set with equivalent class names in the LI tags CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "), CLASS_ATTR_MAP = {}, // Top-level Fancytree node attributes, that can be set by dict NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy refKey selected title tooltip unselectable".split(" "), NODE_ATTR_MAP = {}, // Attribute names that should NOT be added to node.data NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true}; for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; } for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; } /* ***************************************************************************** * FancytreeNode */ /** * Creates a new FancytreeNode * * @class FancytreeNode * @classdesc A FancytreeNode represents the hierarchical data model and operations. * * @param {FancytreeNode} parent * @param {NodeData} obj * * @property {Fancytree} tree The tree instance * @property {FancytreeNode} parent The parent node * @property {string} key Node id (must be unique inside the tree) * @property {string} title Display name (may contain HTML) * @property {object} data Contains all extra data that was passed on node creation * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br> * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array * to define a node that has no children. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property. * @property {string} extraClasses Addtional CSS classes, added to the node's `&lt;span>` * @property {boolean} folder Folder nodes have different default icons and click behavior.<br> * Note: Also non-folders may have children. * @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion. * @property {boolean} selected Use isSelected(), setSelected() to access this property. * @property {string} tooltip Alternative description used as hover banner */ function FancytreeNode(parent, obj){ var i, l, name, cl; this.parent = parent; this.tree = parent.tree; this.ul = null; this.li = null; // <li id='key' ftnode=this> tag this.statusNodeType = null; // if this is a temp. node to display the status of its parent this._isLoading = false; // if this node itself is loading this._error = null; // {message: '...'} if a load error occured this.data = {}; // TODO: merge this code with node.toDict() // copy attributes from obj object for(i=0, l=NODE_ATTRS.length; i<l; i++){ name = NODE_ATTRS[i]; this[name] = obj[name]; } // node.data += obj.data if(obj.data){ $.extend(this.data, obj.data); } // copy all other attributes to this.data.NAME for(name in obj){ if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = obj.NAME this.data[name] = obj[name]; } } // Fix missing key if( this.key == null ){ // test for null OR undefined if( this.tree.options.defaultKey ) { this.key = this.tree.options.defaultKey(this); _assert(this.key, "defaultKey() must return a unique key"); } else { this.key = "_" + (FT._nextNodeKey++); } } else { this.key = "" + this.key; // Convert to string (#217) } // Fix tree.activeNode // TODO: not elegant: we use obj.active as marker to set tree.activeNode // when loading from a dictionary. if(obj.active){ _assert(this.tree.activeNode === null, "only one active node allowed"); this.tree.activeNode = this; } if( obj.selected ){ // #186 this.tree.lastSelectedNode = this; } // TODO: handle obj.focus = true // Create child nodes this.children = null; cl = obj.children; if(cl && cl.length){ this._setChildren(cl); } // Add to key/ref map (except for root node) // if( parent ) { this.tree._callHook("treeRegisterNode", this.tree, true, this); // } } FancytreeNode.prototype = /** @lends FancytreeNode# */{ /* Return the direct child FancytreeNode with a given key, index. */ _findDirectChild: function(ptr){ var i, l, cl = this.children; if(cl){ if(typeof ptr === "string"){ for(i=0, l=cl.length; i<l; i++){ if(cl[i].key === ptr){ return cl[i]; } } }else if(typeof ptr === "number"){ return this.children[ptr]; }else if(ptr.parent === this){ return ptr; } } return null; }, // TODO: activate() // TODO: activateSilently() /* Internal helper called in recursive addChildren sequence.*/ _setChildren: function(children){ _assert(children && (!this.children || this.children.length === 0), "only init supported"); this.children = []; for(var i=0, l=children.length; i<l; i++){ this.children.push(new FancytreeNode(this, children[i])); } }, /** * Append (or insert) a list of child nodes. * * @param {NodeData[]} children array of child node definitions (also single child accepted) * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such). * If omitted, the new children are appended. * @returns {FancytreeNode} first child added * * @see FancytreeNode#applyPatch */ addChildren: function(children, insertBefore){ var i, l, pos, firstNode = null, nodeList = []; if($.isPlainObject(children) ){ children = [children]; } if(!this.children){ this.children = []; } for(i=0, l=children.length; i<l; i++){ nodeList.push(new FancytreeNode(this, children[i])); } firstNode = nodeList[0]; if(insertBefore == null){ this.children = this.children.concat(nodeList); }else{ insertBefore = this._findDirectChild(insertBefore); pos = $.inArray(insertBefore, this.children); _assert(pos >= 0, "insertBefore must be an existing child"); // insert nodeList after children[pos] this.children.splice.apply(this.children, [pos, 0].concat(nodeList)); } if( !this.parent || this.parent.ul || this.tr ){ // render if the parent was rendered (or this is a root node) this.render(); } if( this.tree.options.selectMode === 3 ){ this.fixSelection3FromEndNodes(); } return firstNode; }, /** * Append or prepend a node, or append a child node. * * This a convenience function that calls addChildren() * * @param {NodeData} node node definition * @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child') * @returns {FancytreeNode} new node */ addNode: function(node, mode){ if(mode === undefined || mode === "over"){ mode = "child"; } switch(mode){ case "after": return this.getParent().addChildren(node, this.getNextSibling()); case "before": return this.getParent().addChildren(node, this); case "firstChild": // Insert before the first child if any var insertBefore = (this.children ? this.children[0] : null); return this.addChildren(node, insertBefore); case "child": case "over": return this.addChildren(node); } _assert(false, "Invalid mode: " + mode); }, /** * Append new node after this. * * This a convenience function that calls addNode(node, 'after') * * @param {NodeData} node node definition * @returns {FancytreeNode} new node */ appendSibling: function(node){ return this.addNode(node, "after"); }, /** * Modify existing child nodes. * * @param {NodePatch} patch * @returns {$.Promise} * @see FancytreeNode#addChildren */ applyPatch: function(patch) { // patch [key, null] means 'remove' if(patch === null){ this.remove(); return _getResolvedPromise(this); } // TODO: make sure that root node is not collapsed or modified // copy (most) attributes to node.ATTR or node.data.ATTR var name, promise, v, IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global for(name in patch){ v = patch[name]; if( !IGNORE_MAP[name] && !$.isFunction(v)){ if(NODE_ATTR_MAP[name]){ this[name] = v; }else{ this.data[name] = v; } } } // Remove and/or create children if(patch.hasOwnProperty("children")){ this.removeChildren(); if(patch.children){ // only if not null and not empty list // TODO: addChildren instead? this._setChildren(patch.children); } // TODO: how can we APPEND or INSERT child nodes? } if(this.isVisible()){ this.renderTitle(); this.renderStatus(); } // Expand collapse (final step, since this may be async) if(patch.hasOwnProperty("expanded")){ promise = this.setExpanded(patch.expanded); }else{ promise = _getResolvedPromise(this); } return promise; }, /** Collapse all sibling nodes. * @returns {$.Promise} */ collapseSiblings: function() { return this.tree._callHook("nodeCollapseSiblings", this); }, /** Copy this node as sibling or child of `node`. * * @param {FancytreeNode} node source node * @param {string} [mode=child] 'before' | 'after' | 'child' * @param {Function} [map] callback function(NodeData) that could modify the new node * @returns {FancytreeNode} new */ copyTo: function(node, mode, map) { return node.addNode(this.toDict(true, map), mode); }, /** Count direct and indirect children. * * @param {boolean} [deep=true] pass 'false' to only count direct children * @returns {int} number of child nodes */ countChildren: function(deep) { var cl = this.children, i, l, n; if( !cl ){ return 0; } n = cl.length; if(deep !== false){ for(i=0, l=n; i<l; i++){ n += cl[i].countChildren(); } } return n; }, // TODO: deactivate() /** Write to browser console if debugLevel >= 2 (prepending node info) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.tree.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, /** Deprecated. * @deprecated since 2014-02-16. Use resetLazy() instead. */ discard: function(){ this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."); return this.resetLazy(); }, // TODO: expand(flag) /**Find all nodes that contain `match` in the title. * * @param {string | function(node)} match string to search for, of a function that * returns `true` if a node is matched. * @returns {FancytreeNode[]} array of nodes (may be empty) * @see FancytreeNode#findAll */ findAll: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = []; this.visit(function(n){ if(match(n)){ res.push(n); } }); return res; }, /**Find first node that contains `match` in the title (not including self). * * @param {string | function(node)} match string to search for, of a function that * returns `true` if a node is matched. * @returns {FancytreeNode} matching node or null * @example * <b>fat</b> text */ findFirst: function(match) { match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match); var res = null; this.visit(function(n){ if(match(n)){ res = n; return false; } }); return res; }, /* Apply selection state (internal use only) */ _changeSelectStatusAttrs: function (state) { var changed = false; switch(state){ case false: changed = ( this.selected || this.partsel ); this.selected = false; this.partsel = false; break; case true: changed = ( !this.selected || !this.partsel ); this.selected = true; this.partsel = true; break; case undefined: changed = ( this.selected || !this.partsel ); this.selected = false; this.partsel = true; break; default: _assert(false, "invalid state: " + state); } // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed); if( changed ){ this.renderStatus(); } return changed; }, /** * Fix selection status, after this node was (de)selected in multi-hier mode. * This includes (de)selecting all children. */ fixSelection3AfterClick: function() { var flag = this.isSelected(); // this.debug("fixSelection3AfterClick()"); this.visit(function(node){ node._changeSelectStatusAttrs(flag); }); this.fixSelection3FromEndNodes(); }, /** * Fix selection status for multi-hier mode. * Only end-nodes are considered to update the descendants branch and parents. * Should be called after this node has loaded new children or after * children have been modified using the API. */ fixSelection3FromEndNodes: function() { // this.debug("fixSelection3FromEndNodes()"); _assert(this.tree.options.selectMode === 3, "expected selectMode 3"); // Visit all end nodes and adjust their parent's `selected` and `partsel` // attributes. Return selection state true, false, or undefined. function _walk(node){ var i, l, child, s, state, allSelected,someSelected, children = node.children; if( children && children.length ){ // check all children recursively allSelected = true; someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // the selection state of a node is not relevant; we need the end-nodes s = _walk(child); if( s !== false ) { someSelected = true; } if( s !== true ) { allSelected = false; } } state = allSelected ? true : (someSelected ? undefined : false); }else{ // This is an end-node: simply report the status // state = ( node.unselectable ) ? undefined : !!node.selected; state = !!node.selected; } node._changeSelectStatusAttrs(state); return state; } _walk(this); // Update parent's state this.visitParents(function(node){ var i, l, child, state, children = node.children, allSelected = true, someSelected = false; for( i=0, l=children.length; i<l; i++ ){ child = children[i]; // When fixing the parents, we trust the sibling status (i.e. // we don't recurse) if( child.selected || child.partsel ) { someSelected = true; } if( !child.unselectable && !child.selected ) { allSelected = false; } } state = allSelected ? true : (someSelected ? undefined : false); node._changeSelectStatusAttrs(state); }); }, // TODO: focus() /** * Update node data. If dict contains 'children', then also replace * the hole sub tree. * @param {NodeData} dict * * @see FancytreeNode#addChildren * @see FancytreeNode#applyPatch */ fromDict: function(dict) { // copy all other attributes to this.data.xxx for(var name in dict){ if(NODE_ATTR_MAP[name]){ // node.NAME = dict.NAME this[name] = dict[name]; }else if(name === "data"){ // node.data += dict.data $.extend(this.data, dict.data); }else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){ // node.data.NAME = dict.NAME this.data[name] = dict[name]; } } if(dict.children){ // recursively set children and render this.removeChildren(); this.addChildren(dict.children); } this.renderTitle(); /* var children = dict.children; if(children === undefined){ this.data = $.extend(this.data, dict); this.render(); return; } dict = $.extend({}, dict); dict.children = undefined; this.data = $.extend(this.data, dict); this.removeChildren(); this.addChild(children); */ }, /** Return the list of child nodes (undefined for unexpanded lazy nodes). * @returns {FancytreeNode[] | undefined} */ getChildren: function() { if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes? return undefined; // Lazy node: unloaded, currently loading, or load error } return this.children; }, /** Return the first child node or null. * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.children ? this.children[0] : null; }, /** Return the 0-based child index. * @returns {int} */ getIndex: function() { // return this.parent.children.indexOf(this); return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7 }, /** Return the hierarchical child index (1-based, e.g. '3.2.4'). * @returns {string} */ getIndexHier: function(separator) { separator = separator || "."; var res = []; $.each(this.getParentList(false, true), function(i, o){ res.push(o.getIndex() + 1); }); return res.join(separator); }, /** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32". * @param {boolean} [excludeSelf=false] * @returns {string} */ getKeyPath: function(excludeSelf) { var path = [], sep = this.tree.options.keyPathSeparator; this.visitParents(function(n){ if(n.parent){ path.unshift(n.key); } }, !excludeSelf); return sep + path.join(sep); }, /** Return the last child of this node or null. * @returns {FancytreeNode | null} */ getLastChild: function() { return this.children ? this.children[this.children.length - 1] : null; }, /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... . * @returns {int} */ getLevel: function() { var level = 0, dtn = this.parent; while( dtn ) { level++; dtn = dtn.parent; } return level; }, /** Return the successor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getNextSibling: function() { // TODO: use indexOf, if available: (not in IE6) if( this.parent ){ var i, l, ac = this.parent.children; for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null if( ac[i] === this ){ return ac[i+1]; } } } return null; }, /** Return the parent node (null for the system root node). * @returns {FancytreeNode | null} */ getParent: function() { // TODO: return null for top-level nodes? return this.parent; }, /** Return an array of all parent nodes (top-down). * @param {boolean} [includeRoot=false] Include the invisible system root node. * @param {boolean} [includeSelf=false] Include the node itself. * @returns {FancytreeNode[]} */ getParentList: function(includeRoot, includeSelf) { var l = [], dtn = includeSelf ? this : this.parent; while( dtn ) { if( includeRoot || dtn.parent ){ l.unshift(dtn); } dtn = dtn.parent; } return l; }, /** Return the predecessor node (under the same parent) or null. * @returns {FancytreeNode | null} */ getPrevSibling: function() { if( this.parent ){ var i, l, ac = this.parent.children; for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null if( ac[i] === this ){ return ac[i-1]; } } } return null; }, /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded). * @returns {boolean | undefined} */ hasChildren: function() { if(this.lazy){ if(this.children == null ){ // null or undefined: Not yet loaded return undefined; }else if(this.children.length === 0){ // Loaded, but response was empty return false; }else if(this.children.length === 1 && this.children[0].isStatusNode() ){ // Currently loading or load error return undefined; } return true; } return !!( this.children && this.children.length ); }, /** Return true if node has keyboard focus. * @returns {boolean} */ hasFocus: function() { return (this.tree.hasFocus() && this.tree.focusNode === this); }, /** Write to browser console if debugLevel >= 1 (prepending node info) * * @param {*} msg string or object or array of such */ info: function(msg){ if( this.tree.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /** Return true if node is active (see also FancytreeNode#isSelected). * @returns {boolean} */ isActive: function() { return (this.tree.activeNode === this); }, /** Return true if node is a direct child of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isChildOf: function(otherNode) { return (this.parent && this.parent === otherNode); }, /** Return true, if node is a direct or indirect sub node of otherNode. * @param {FancytreeNode} otherNode * @returns {boolean} */ isDescendantOf: function(otherNode) { if(!otherNode || otherNode.tree !== this.tree){ return false; } var p = this.parent; while( p ) { if( p === otherNode ){ return true; } p = p.parent; } return false; }, /** Return true if node is expanded. * @returns {boolean} */ isExpanded: function() { return !!this.expanded; }, /** Return true if node is the first node of its parent's children. * @returns {boolean} */ isFirstSibling: function() { var p = this.parent; return !p || p.children[0] === this; }, /** Return true if node is a folder, i.e. has the node.folder attribute set. * @returns {boolean} */ isFolder: function() { return !!this.folder; }, /** Return true if node is the last node of its parent's children. * @returns {boolean} */ isLastSibling: function() { var p = this.parent; return !p || p.children[p.children.length-1] === this; }, /** Return true if node is lazy (even if data was already loaded) * @returns {boolean} */ isLazy: function() { return !!this.lazy; }, /** Return true if node is lazy and loaded. For non-lazy nodes always return true. * @returns {boolean} */ isLoaded: function() { return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node }, /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending. * @returns {boolean} */ isLoading: function() { return !!this._isLoading; }, /* * @deprecated since v2.4.0: Use isRootNode() instead */ isRoot: function() { return this.isRootNode(); }, /** Return true if this is the (invisible) system root node. * @returns {boolean} */ isRootNode: function() { return (this.tree.rootNode === this); }, /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive). * @returns {boolean} */ isSelected: function() { return !!this.selected; }, /** Return true if this node is a temporarily generated system node like * 'loading', or 'error' (node.statusNodeType contains the type). * @returns {boolean} */ isStatusNode: function() { return !!this.statusNodeType; }, /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node. * @returns {boolean} */ isTopLevel: function() { return (this.tree.rootNode === this.parent); }, /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false. * @returns {boolean} */ isUndefined: function() { return this.hasChildren() === undefined; // also checks if the only child is a status node }, /** Return true if all parent nodes are expanded. Note: this does not check * whether the node is scrolled into the visible part of the screen. * @returns {boolean} */ isVisible: function() { var i, l, parents = this.getParentList(false, false); for(i=0, l=parents.length; i<l; i++){ if( ! parents[i].expanded ){ return false; } } return true; }, /** Deprecated. * @deprecated since 2014-02-16: use load() instead. */ lazyLoad: function(discard) { this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."); return this.load(discard); }, /** * Load all children of a lazy node if neccessary. The *expanded* state is maintained. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. * @returns {$.Promise} */ load: function(forceReload) { var res, source, that = this; _assert( this.isLazy(), "load() requires a lazy node" ); // _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" ); if( !forceReload && !this.isUndefined() ) { return _getResolvedPromise(this); } if( this.isLoaded() ){ this.resetLazy(); // also collapses } // This method is also called by setExpanded() and loadKeyPath(), so we // have to avoid recursion. source = this.tree._triggerNodeEvent("lazyLoad", this); if( source === false ) { // #69 return _getResolvedPromise(this); } _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); res = this.tree._callHook("nodeLoadChildren", this, source); if( this.expanded ) { res.always(function(){ that.render(); }); } return res; }, /** Expand all parents and optionally scroll into visible area as neccessary. * Promise is resolved, when lazy loading and animations are done. * @param {object} [opts] passed to `setExpanded()`. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true} * @returns {$.Promise} */ makeVisible: function(opts) { var i, that = this, deferreds = [], dfd = new $.Deferred(), parents = this.getParentList(false, false), len = parents.length, effects = !(opts && opts.noAnimation === true), scroll = !(opts && opts.scrollIntoView === false); // Expand bottom-up, so only the top node is animated for(i = len - 1; i >= 0; i--){ // that.debug("pushexpand" + parents[i]); deferreds.push(parents[i].setExpanded(true, opts)); } $.when.apply($, deferreds).done(function(){ // All expands have finished // that.debug("expand DONE", scroll); if( scroll ){ that.scrollIntoView(effects).done(function(){ // that.debug("scroll DONE"); dfd.resolve(); }); } else { dfd.resolve(); } }); return dfd.promise(); }, /** Move this node to targetNode. * @param {FancytreeNode} targetNode * @param {string} mode <pre> * 'child': append this node as last child of targetNode. * This is the default. To be compatble with the D'n'd * hitMode, we also accept 'over'. * 'before': add this node as sibling before targetNode. * 'after': add this node as sibling after targetNode.</pre> * @param {function} [map] optional callback(FancytreeNode) to allow modifcations */ moveTo: function(targetNode, mode, map) { if(mode === undefined || mode === "over"){ mode = "child"; } var pos, prevParent = this.parent, targetParent = (mode === "child") ? targetNode : targetNode.parent; if(this === targetNode){ return; }else if( !this.parent ){ throw "Cannot move system root"; }else if( targetParent.isDescendantOf(this) ){ throw "Cannot move a node to its own descendant"; } // Unlink this node from current parent if( this.parent.children.length === 1 ) { if( this.parent === targetParent ){ return; // #258 } this.parent.children = this.parent.lazy ? [] : null; this.parent.expanded = false; } else { pos = $.inArray(this, this.parent.children); _assert(pos >= 0, "invalid source parent"); this.parent.children.splice(pos, 1); } // Remove from source DOM parent // if(this.parent.ul){ // this.parent.ul.removeChild(this.li); // } // Insert this node to target parent's child list this.parent = targetParent; if( targetParent.hasChildren() ) { switch(mode) { case "child": // Append to existing target children targetParent.children.push(this); break; case "before": // Insert this node before target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0, "invalid target parent"); targetParent.children.splice(pos, 0, this); break; case "after": // Insert this node after target node pos = $.inArray(targetNode, targetParent.children); _assert(pos >= 0, "invalid target parent"); targetParent.children.splice(pos+1, 0, this); break; default: throw "Invalid mode " + mode; } } else { targetParent.children = [ this ]; } // Parent has no <ul> tag yet: // if( !targetParent.ul ) { // // This is the parent's first child: create UL tag // // (Hidden, because it will be // targetParent.ul = document.createElement("ul"); // targetParent.ul.style.display = "none"; // targetParent.li.appendChild(targetParent.ul); // } // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded)) // if(this.li){ // targetParent.ul.appendChild(this.li); // }^ // Let caller modify the nodes if( map ){ targetNode.visit(map, true); } // Handle cross-tree moves if( this.tree !== targetNode.tree ) { // Fix node.tree for all source nodes // _assert(false, "Cross-tree move is not yet implemented."); this.warn("Cross-tree moveTo is experimantal!"); this.visit(function(n){ // TODO: fix selection state and activation, ... n.tree = targetNode.tree; }, true); } // A collaposed node won't re-render children, so we have to remove it manually // if( !targetParent.expanded ){ // prevParent.ul.removeChild(this.li); // } // Update HTML markup if( !prevParent.isDescendantOf(targetParent)) { prevParent.render(); } if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) { targetParent.render(); } // TODO: fix selection state // TODO: fix active state /* var tree = this.tree; var opts = tree.options; var pers = tree.persistence; // Always expand, if it's below minExpandLevel // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel()); if ( opts.minExpandLevel >= ftnode.getLevel() ) { // tree.logDebug ("Force expand for %o", ftnode); this.bExpanded = true; } // In multi-hier mode, update the parents selection state // DT issue #82: only if not initializing, because the children may not exist yet // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing ) // ftnode._fixSelectionState(); // In multi-hier mode, update the parents selection state if( ftnode.bSelected && opts.selectMode==3 ) { var p = this; while( p ) { if( !p.hasSubSel ) p._setSubSel(true); p = p.parent; } } // render this node and the new child if ( tree.bEnableUpdate ) this.render(); return ftnode; */ }, /** Set focus relative to this node and optionally activate. * * @param {number} where The keyCode that would normally trigger this move, * e.g. `$.ui.keyCode.LEFT` would collapse the node if it * is expanded or move to the parent oterwise. * @param {boolean} [activate=true] * @returns {$.Promise} */ // navigate: function(where, activate) { // console.time("navigate") // this._navigate(where, activate) // console.timeEnd("navigate") // }, navigate: function(where, activate) { var i, parents, handled = true, KC = $.ui.keyCode, sib = null; // Navigate to node function _goto(n){ if( n ){ try { n.makeVisible(); } catch(e) {} // #272 // Node may still be hidden by a filter if( ! $(n.span).is(":visible") ) { n.debug("Navigate: skipping hidden node"); n.navigate(where, activate); return; } return activate === false ? n.setFocus() : n.setActive(); } } switch( where ) { case KC.BACKSPACE: if( this.parent && this.parent.parent ) { _goto(this.parent); } break; case KC.LEFT: if( this.expanded ) { this.setExpanded(false); _goto(this); } else if( this.parent && this.parent.parent ) { _goto(this.parent); } break; case KC.RIGHT: if( !this.expanded && (this.children || this.lazy) ) { this.setExpanded(); _goto(this); } else if( this.children && this.children.length ) { _goto(this.children[0]); } break; case KC.UP: sib = this.getPrevSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getPrevSibling(); } while( sib && sib.expanded && sib.children && sib.children.length ) { sib = sib.children[sib.children.length - 1]; } if( !sib && this.parent && this.parent.parent ){ sib = this.parent; } _goto(sib); break; case KC.DOWN: if( this.expanded && this.children && this.children.length ) { sib = this.children[0]; } else { parents = this.getParentList(false, true); for(i=parents.length-1; i>=0; i--) { sib = parents[i].getNextSibling(); // #359: skip hidden sibling nodes, preventing a _goto() recursion while( sib && !$(sib.span).is(":visible") ) { sib = sib.getNextSibling(); } if( sib ){ break; } } } _goto(sib); break; default: handled = false; } }, /** * Remove this node (not allowed for system root). */ remove: function() { return this.parent.removeChild(this); }, /** * Remove childNode from list of direct children. * @param {FancytreeNode} childNode */ removeChild: function(childNode) { return this.tree._callHook("nodeRemoveChild", this, childNode); }, /** * Remove all child nodes and descendents. This converts the node into a leaf.<br> * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy() * in order to trigger lazyLoad on next expand. */ removeChildren: function() { return this.tree._callHook("nodeRemoveChildren", this); }, /** * This method renders and updates all HTML markup that is required * to display this node in its current state.<br> * Note: * <ul> * <li>It should only be neccessary to call this method after the node object * was modified by direct access to its properties, because the common * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...) * already handle this. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus} * are implied. If changes are more local, calling only renderTitle() or * renderStatus() may be sufficient and faster. * <li>If a node was created/removed, node.render() must be called <i>on the parent</i>. * </ul> * * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed */ render: function(force, deep) { return this.tree._callHook("nodeRender", this, force, deep); }, /** Create HTML markup for the node's outer &lt;span> (expander, checkbox, icon, and title). * @see Fancytree_Hooks#nodeRenderTitle */ renderTitle: function() { return this.tree._callHook("nodeRenderTitle", this); }, /** Update element's CSS classes according to node state. * @see Fancytree_Hooks#nodeRenderStatus */ renderStatus: function() { return this.tree._callHook("nodeRenderStatus", this); }, /** * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad * event is triggered on next expand. */ resetLazy: function() { this.removeChildren(); this.expanded = false; this.lazy = true; this.children = undefined; this.renderStatus(); }, /** Schedule activity for delayed execution (cancel any pending request). * scheduleAction('cancel') will only cancel a pending request (if any). * @param {string} mode * @param {number} ms */ scheduleAction: function(mode, ms) { if( this.tree.timer ) { clearTimeout(this.tree.timer); // this.tree.debug("clearTimeout(%o)", this.tree.timer); } this.tree.timer = null; var self = this; // required for closures switch (mode) { case "cancel": // Simply made sure that timer was cleared break; case "expand": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger expand"); self.setExpanded(true); }, ms); break; case "activate": this.tree.timer = setTimeout(function(){ self.tree.debug("setTimeout: trigger activate"); self.setActive(true); }, ms); break; default: throw "Invalid mode " + mode; } // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer); }, /** * * @param {boolean | PlainObject} [effects=false] animation options. * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in * any case, even if `this` is outside the scroll pane. * @returns {$.Promise} */ scrollIntoView: function(effects, options) { if( options !== undefined && _isNode(options) ) { this.warn("scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."); options = {topNode: options}; } // this.$scrollParent = (this.options.scrollParent === "auto") ? $ul.scrollParent() : $(this.options.scrollParent); // this.$scrollParent = this.$scrollParent.length ? this.$scrollParent || this.$container; var topNodeY, nodeY, horzScrollbarHeight, containerOffsetTop, opts = $.extend({ effects: (effects === true) ? {duration: 200, queue: false} : effects, scrollOfs: this.tree.options.scrollOfs, scrollParent: this.tree.options.scrollParent || this.tree.$container, topNode: null }, options), dfd = new $.Deferred(), that = this, nodeHeight = $(this.span).height(), $container = $(opts.scrollParent), topOfs = opts.scrollOfs.top || 0, bottomOfs = opts.scrollOfs.bottom || 0, containerHeight = $container.height(),// - topOfs - bottomOfs, scrollTop = $container.scrollTop(), $animateTarget = $container, isParentWindow = $container[0] === window, topNode = opts.topNode || null, newScrollTop = null; // this.debug("scrollIntoView(), scrollTop=", scrollTop, opts.scrollOfs); // _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets if( !$(this.span).is(":visible") ) { // We cannot calc offsets for hidden elements this.warn("scrollIntoView(): node is invisible."); return _getResolvedPromise(); } if( isParentWindow ) { nodeY = $(this.span).offset().top; topNodeY = (topNode && topNode.span) ? $(topNode.span).offset().top : 0; $animateTarget = $("html,body"); } else { _assert($container[0] !== document && $container[0] !== document.body, "scrollParent should be an simple element or `window`, not document or body."); containerOffsetTop = $container.offset().top, nodeY = $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent topNodeY = topNode ? $(topNode.span).offset().top - containerOffsetTop + scrollTop : 0; horzScrollbarHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight)); containerHeight -= horzScrollbarHeight; } // this.debug(" scrollIntoView(), nodeY=", nodeY, "containerHeight=", containerHeight); if( nodeY < (scrollTop + topOfs) ){ // Node is above visible container area newScrollTop = nodeY - topOfs; // this.debug(" scrollIntoView(), UPPER newScrollTop=", newScrollTop); }else if((nodeY + nodeHeight) > (scrollTop + containerHeight - bottomOfs)){ newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs; // this.debug(" scrollIntoView(), LOWER newScrollTop=", newScrollTop); // If a topNode was passed, make sure that it is never scrolled // outside the upper border if(topNode){ _assert(topNode.isRootNode() || $(topNode.span).is(":visible"), "topNode must be visible"); if( topNodeY < newScrollTop ){ newScrollTop = topNodeY - topOfs; // this.debug(" scrollIntoView(), TOP newScrollTop=", newScrollTop); } } } if(newScrollTop !== null){ // this.debug(" scrollIntoView(), SET newScrollTop=", newScrollTop); if(opts.effects){ opts.effects.complete = function(){ dfd.resolveWith(that); }; $animateTarget.stop(true).animate({ scrollTop: newScrollTop }, opts.effects); }else{ $animateTarget[0].scrollTop = newScrollTop; dfd.resolveWith(this); } }else{ dfd.resolveWith(this); } return dfd.promise(); }, /**Activate this node. * @param {boolean} [flag=true] pass false to deactivate * @param {object} [opts] additional options. Defaults to {noEvents: false} * @returns {$.Promise} */ setActive: function(flag, opts){ return this.tree._callHook("nodeSetActive", this, flag, opts); }, /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done. * @param {boolean} [flag=true] pass false to collapse * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} */ setExpanded: function(flag, opts){ return this.tree._callHook("nodeSetExpanded", this, flag, opts); }, /**Set keyboard focus to this node. * @param {boolean} [flag=true] pass false to blur * @see Fancytree#setFocus */ setFocus: function(flag){ return this.tree._callHook("nodeSetFocus", this, flag); }, /**Select this node, i.e. check the checkbox. * @param {boolean} [flag=true] pass false to deselect */ setSelected: function(flag){ return this.tree._callHook("nodeSetSelected", this, flag); }, /**Mark a lazy node as 'error', 'loading', or 'ok'. * @param {string} status 'error', 'ok' * @param {string} [message] * @param {string} [details] */ setStatus: function(status, message, details){ return this.tree._callHook("nodeSetStatus", this, status, message, details); }, /**Rename this node. * @param {string} title */ setTitle: function(title){ this.title = title; this.renderTitle(); }, /**Sort child list by title. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title). * @param {boolean} [deep=false] pass true to sort all descendant nodes */ sortChildren: function(cmp, deep) { var i,l, cl = this.children; if( !cl ){ return; } cmp = cmp || function(a, b) { var x = a.title.toLowerCase(), y = b.title.toLowerCase(); return x === y ? 0 : x > y ? 1 : -1; }; cl.sort(cmp); if( deep ){ for(i=0, l=cl.length; i<l; i++){ if( cl[i].children ){ cl[i].sortChildren(cmp, "$norender$"); } } } if( deep !== "$norender$" ){ this.render(); } }, /** Convert node (or whole branch) into a plain object. * * The result is compatible with node.addChildren(). * * @param {boolean} [recursive=false] include child nodes * @param {function} [callback] callback(dict) is called for every node, in order to allow modifications * @returns {NodeData} */ toDict: function(recursive, callback) { var i, l, node, dict = {}, self = this; $.each(NODE_ATTRS, function(i, a){ if(self[a] || self[a] === false){ dict[a] = self[a]; } }); if(!$.isEmptyObject(this.data)){ dict.data = $.extend({}, this.data); if($.isEmptyObject(dict.data)){ delete dict.data; } } if( callback ){ callback(dict); } if( recursive ) { if(this.hasChildren()){ dict.children = []; for(i=0, l=this.children.length; i<l; i++ ){ node = this.children[i]; if( !node.isStatusNode() ){ dict.children.push(node.toDict(true, callback)); } } }else{ // dict.children = null; } } return dict; }, /** Flip expanded status. */ toggleExpanded: function(){ return this.tree._callHook("nodeToggleExpanded", this); }, /** Flip selection status. */ toggleSelected: function(){ return this.tree._callHook("nodeToggleSelected", this); }, toString: function() { return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>"; }, /** Call fn(node) for all child nodes.<br> * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visit: function(fn, includeSelf) { var i, l, res = true, children = this.children; if( includeSelf === true ) { res = fn(this); if( res === false || res === "skip" ){ return res; } } if(children){ for(i=0, l=children.length; i<l; i++){ res = children[i].visit(fn, true); if( res === false ){ break; } } } return res; }, /** Call fn(node) for all child nodes and recursively load lazy children.<br> * <b>Note:</b> If you need this method, you probably should consider to review * your architecture! Recursivley loading nodes is a perfect way for lazy * programmers to flood the server with requests ;-) * * @param {function} [fn] optional callback function. * Return false to stop iteration, return "skip" to skip this node and * its children only. * @param {boolean} [includeSelf=false] * @returns {$.Promise} */ visitAndLoad: function(fn, includeSelf, _recursion) { var dfd, res, loaders, node = this; // node.debug("visitAndLoad"); if( fn && includeSelf === true ) { res = fn(node); if( res === false || res === "skip" ) { return _recursion ? res : _getResolvedPromise(); } } if( !node.children && !node.lazy ) { return _getResolvedPromise(); } dfd = new $.Deferred(); loaders = []; // node.debug("load()..."); node.load().done(function(){ // node.debug("load()... done."); for(var i=0, l=node.children.length; i<l; i++){ res = node.children[i].visitAndLoad(fn, true, true); if( res === false ) { dfd.reject(); break; } else if ( res !== "skip" ) { loaders.push(res); // Add promise to the list } } $.when.apply(this, loaders).then(function(){ dfd.resolve(); }); }); return dfd.promise(); }, /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br> * Stop iteration, if fn() returns false.<br> * Return false if iteration was stopped. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @param {boolean} [includeSelf=false] * @returns {boolean} */ visitParents: function(fn, includeSelf) { // Visit parent nodes (bottom up) if(includeSelf && fn(this) === false){ return false; } var p = this.parent; while( p ) { if(fn(p) === false){ return false; } p = p.parent; } return true; }, /** Write warning to browser console (prepending node info) * * @param {*} msg string or object or array of such */ warn: function(msg){ Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }; /* ***************************************************************************** * Fancytree */ /** * Construct a new tree object. * * @class Fancytree * @classdesc The controller behind a fancytree. * This class also contains 'hook methods': see {@link Fancytree_Hooks}. * * @param {Widget} widget * * @property {FancytreeOptions} options * @property {FancytreeNode} rootNode * @property {FancytreeNode} activeNode * @property {FancytreeNode} focusNode * @property {jQueryObject} $div * @property {object} widget * @property {object} ext * @property {object} data * @property {object} options * @property {string} _id * @property {string} statusClassPropName * @property {string} ariaPropName * @property {string} nodeContainerAttrName * @property {string} $container * @property {FancytreeNode} lastSelectedNode */ function Fancytree(widget) { this.widget = widget; this.$div = widget.element; this.options = widget.options; if( this.options ) { if( $.isFunction(this.options.lazyload ) && !$.isFunction(this.options.lazyLoad) ) { this.options.lazyLoad = function() { FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."); return widget.options.lazyload.apply(this, arguments); }; } if( $.isFunction(this.options.loaderror) ) { $.error("The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."); } if( this.options.fx !== undefined ) { FT.warn("The 'fx' options was replaced by 'toggleEffect' since 2014-11-30."); } } this.ext = {}; // Active extension instances // allow to init tree.data.foo from <div data-foo=''> this.data = _getElementDataAsDict(this.$div); this._id = $.ui.fancytree._nextId++; this._ns = ".fancytree-" + this._id; // append for namespaced events this.activeNode = null; this.focusNode = null; this._hasFocus = null; this.lastSelectedNode = null; this.systemFocusElement = null; this.lastQuicksearchTerm = ""; this.lastQuicksearchTime = 0; this.statusClassPropName = "span"; this.ariaPropName = "li"; this.nodeContainerAttrName = "li"; // Remove previous markup if any this.$div.find(">ul.fancytree-container").remove(); // Create a node without parent. var fakeParent = { tree: this }, $ul; this.rootNode = new FancytreeNode(fakeParent, { title: "root", key: "root_" + this._id, children: null, expanded: true }); this.rootNode.parent = null; // Create root markup $ul = $("<ul>", { "class": "ui-fancytree fancytree-container" }).appendTo(this.$div); this.$container = $ul; this.rootNode.ul = $ul[0]; if(this.options.debugLevel == null){ this.options.debugLevel = FT.debugLevel; } // Add container to the TAB chain // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1"); if(this.options.aria){ this.$container .attr("role", "tree") .attr("aria-multiselectable", true); } } Fancytree.prototype = /** @lends Fancytree# */{ /* Return a context object that can be re-used for _callHook(). * @param {Fancytree | FancytreeNode | EventData} obj * @param {Event} originalEvent * @param {Object} extra * @returns {EventData} */ _makeHookContext: function(obj, originalEvent, extra) { var ctx, tree; if(obj.node !== undefined){ // obj is already a context object if(originalEvent && obj.originalEvent !== originalEvent){ $.error("invalid args"); } ctx = obj; }else if(obj.tree){ // obj is a FancytreeNode tree = obj.tree; ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent }; }else if(obj.widget){ // obj is a Fancytree ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent }; }else{ $.error("invalid args"); } if(extra){ $.extend(ctx, extra); } return ctx; }, /* Trigger a hook function: funcName(ctx, [...]). * * @param {string} funcName * @param {Fancytree|FancytreeNode|EventData} contextObject * @param {any} [_extraArgs] optional additional arguments * @returns {any} */ _callHook: function(funcName, contextObject, _extraArgs) { var ctx = this._makeHookContext(contextObject), fn = this[funcName], args = Array.prototype.slice.call(arguments, 2); if(!$.isFunction(fn)){ $.error("_callHook('" + funcName + "') is not a function"); } args.unshift(ctx); // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args); return fn.apply(this, args); }, /* Check if current extensions dependencies are met and throw an error if not. * * This method may be called inside the `treeInit` hook for custom extensions. * * @param {string} extension name of the required extension * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter) * @param {string} [message] optional error message (defaults to a descriptve error message) */ _requireExtension: function(name, required, before, message) { before = !!before; var thisName = this._local.name, extList = this.options.extensions, isBefore = $.inArray(name, extList) < $.inArray(thisName, extList), isMissing = required && this.ext[name] == null, badOrder = !isMissing && before != null && (before !== isBefore); _assert(thisName && thisName !== name, "invalid or same name"); if( isMissing || badOrder ){ if( !message ){ if( isMissing || required ){ message = "'" + thisName + "' extension requires '" + name + "'"; if( badOrder ){ message += " to be registered " + (before ? "before" : "after") + " itself"; } }else{ message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`"; } } $.error(message); return false; } return true; }, /** Activate node with a given key and fire focus and activate events. * * A prevously activated node will be deactivated. * If activeVisible option is set, all parents will be expanded as necessary. * Pass key = false, to deactivate the current node only. * @param {string} key * @returns {FancytreeNode} activated node (null, if not found) */ activateKey: function(key) { var node = this.getNodeByKey(key); if(node){ node.setActive(); }else if(this.activeNode){ this.activeNode.setActive(false); } return node; }, /** (experimental) * * @param {Array} patchList array of [key, NodePatch] arrays * @returns {$.Promise} resolved, when all patches have been applied * @see TreePatch */ applyPatch: function(patchList) { var dfd, i, p2, key, patch, node, patchCount = patchList.length, deferredList = []; for(i=0; i<patchCount; i++){ p2 = patchList[i]; _assert(p2.length === 2, "patchList must be an array of length-2-arrays"); key = p2[0]; patch = p2[1]; node = (key === null) ? this.rootNode : this.getNodeByKey(key); if(node){ dfd = new $.Deferred(); deferredList.push(dfd); node.applyPatch(patch).always(_makeResolveFunc(dfd, node)); }else{ this.warn("could not find node with key '" + key + "'"); } } // Return a promise that is resolved, when ALL patches were applied return $.when.apply($, deferredList).promise(); }, /* TODO: implement in dnd extension cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } }, */ /** Return the number of nodes. * @returns {integer} */ count: function() { return this.rootNode.countChildren(); }, /** Write to browser console if debugLevel >= 2 (prepending tree name) * * @param {*} msg string or object or array of such */ debug: function(msg){ if( this.options.debugLevel >= 2 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("log", arguments); } }, // TODO: disable() // TODO: enable() // TODO: enableUpdate() /** Find the next visible node that starts with `match`, starting at `startNode` * and wrap-around at the end. * * @param {string|function} match * @param {FancytreeNode} [startNode] defaults to first node * @returns {FancytreeNode} matching node or null */ findNextNode: function(match, startNode, visibleOnly) { var stopNode = null, parentChildren = startNode.parent.children, matchingNode = null, walkVisible = function(parent, idx, fn) { var i, grandParent, parentChildren = parent.children, siblingCount = parentChildren.length, node = parentChildren[idx]; // visit node itself if( node && fn(node) === false ) { return false; } // visit descendants if( node && node.children && node.expanded ) { if( walkVisible(node, 0, fn) === false ) { return false; } } // visit subsequent siblings for( i = idx + 1; i < siblingCount; i++ ) { if( walkVisible(parent, i, fn) === false ) { return false; } } // visit parent's subsequent siblings grandParent = parent.parent; if( grandParent ) { return walkVisible(grandParent, grandParent.children.indexOf(parent) + 1, fn); } else { // wrap-around: restart with first node return walkVisible(parent, 0, fn); } }; match = (typeof match === "string") ? _makeNodeTitleStartMatcher(match) : match; startNode = startNode || this.getFirstChild(); walkVisible(startNode.parent, parentChildren.indexOf(startNode), function(node){ // Stop iteration if we see the start node a second time if( node === stopNode ) { return false; } stopNode = stopNode || node; // Ignore nodes hidden by a filter if( ! $(node.span).is(":visible") ) { node.debug("quicksearch: skipping hidden node"); return; } // Test if we found a match, but search for a second match if this // was the currently active node if( match(node) ) { // node.debug("quicksearch match " + node.title, startNode); matchingNode = node; if( matchingNode !== startNode ) { return false; } } }); return matchingNode; }, // TODO: fromDict /** * Generate INPUT elements that can be submitted with html forms. * * In selectMode 3 only the topmost selected nodes are considered, unless * `opts.stopOnParents: false` is passed. * * @param {boolean | string} [selected=true] Pass false to disable, pass a string to overide the field name (default: 'ft_ID[]') * @param {boolean | string} [active=true] Pass false to disable, pass a string to overide the field name (default: 'ft_ID_active') * @param {object} [opts] default { stopOnParents: true } */ generateFormElements: function(selected, active, opts) { // TODO: test case opts = opts || {}; var nodeList, selectedName = (typeof selected === "string") ? selected : "ft_" + this._id + "[]", activeName = (typeof active === "string") ? active : "ft_" + this._id + "_active", id = "fancytree_result_" + this._id, $result = $("#" + id), stopOnParents = this.options.selectMode === 3 && opts.stopOnParents !== false; if($result.length){ $result.empty(); }else{ $result = $("<div>", { id: id }).hide().insertAfter(this.$container); } if(selected !== false){ nodeList = this.getSelectedNodes(stopOnParents); $.each(nodeList, function(idx, node){ $result.append($("<input>", { type: "checkbox", name: selectedName, value: node.key, checked: true })); }); } if(active !== false && this.activeNode){ $result.append($("<input>", { type: "radio", name: activeName, value: this.activeNode.key, checked: true })); } }, /** * Return the currently active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.activeNode; }, /** Return the first top level node if any (not the invisible root node). * @returns {FancytreeNode | null} */ getFirstChild: function() { return this.rootNode.getFirstChild(); }, /** * Return node that has keyboard focus or null. * @returns {FancytreeNode} */ getFocusNode: function() { return this.focusNode; }, /** * Return node with a given key or null if not found. * @param {string} key * @param {FancytreeNode} [searchRoot] only search below this node * @returns {FancytreeNode | null} */ getNodeByKey: function(key, searchRoot) { // Search the DOM by element ID (assuming this is faster than traversing all nodes). // $("#...") has problems, if the key contains '.', so we use getElementById() var el, match; if(!searchRoot){ el = document.getElementById(this.options.idPrefix + key); if( el ){ return el.ftnode ? el.ftnode : null; } } // Not found in the DOM, but still may be in an unrendered part of tree // TODO: optimize with specialized loop // TODO: consider keyMap? searchRoot = searchRoot || this.rootNode; match = null; searchRoot.visit(function(node){ // window.console.log("getNodeByKey(" + key + "): ", node.key); if(node.key === key) { match = node; return false; } }, true); return match; }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.rootNode; }, /** * Return an array of selected nodes. * @param {boolean} [stopOnParents=false] only return the topmost selected * node (useful with selectMode 3) * @returns {FancytreeNode[]} */ getSelectedNodes: function(stopOnParents) { var nodeList = []; this.rootNode.visit(function(node){ if( node.selected ) { nodeList.push(node); if( stopOnParents === true ){ return "skip"; // stop processing this branch } } }); return nodeList; }, /** Return true if the tree control has keyboard focus * @returns {boolean} */ hasFocus: function(){ return !!this._hasFocus; }, /** Write to browser console if debugLevel >= 1 (prepending tree name) * @param {*} msg string or object or array of such */ info: function(msg){ if( this.options.debugLevel >= 1 ) { Array.prototype.unshift.call(arguments, this.toString()); consoleApply("info", arguments); } }, /* TODO: isInitializing: function() { return ( this.phase=="init" || this.phase=="postInit" ); }, TODO: isReloading: function() { return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound; }, TODO: isUserEvent: function() { return ( this.phase=="userEvent" ); }, */ /** * Make sure that a node with a given ID is loaded, by traversing - and * loading - its parents. This method is ment for lazy hierarchies. * A callback is executed for every node as we go. * @example * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){ * if(status === "loaded") { * console.log("loaded intermiediate node " + node); * }else if(status === "ok") { * node.activate(); * } * }); * * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7') * @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error') * @returns {$.Promise} */ loadKeyPath: function(keyPathList, callback, _rootNode) { var deferredList, dfd, i, path, key, loadMap, node, root, segList, sep = this.options.keyPathSeparator, self = this; if(!$.isArray(keyPathList)){ keyPathList = [keyPathList]; } // Pass 1: handle all path segments for nodes that are already loaded // Collect distinct top-most lazy nodes in a map loadMap = {}; for(i=0; i<keyPathList.length; i++){ root = _rootNode || this.rootNode; path = keyPathList[i]; // strip leading slash if(path.charAt(0) === sep){ path = path.substr(1); } // traverse and strip keys, until we hit a lazy, unloaded node segList = path.split(sep); while(segList.length){ key = segList.shift(); // node = _findDirectChild(root, key); node = root._findDirectChild(key); if(!node){ this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")"); callback.call(this, key, "error"); break; }else if(segList.length === 0){ callback.call(this, node, "ok"); break; }else if(!node.lazy || (node.hasChildren() !== undefined )){ callback.call(this, node, "loaded"); root = node; }else{ callback.call(this, node, "loaded"); // segList.unshift(key); if(loadMap[key]){ loadMap[key].push(segList.join(sep)); }else{ loadMap[key] = [segList.join(sep)]; } break; } } } // alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap)); // Now load all lazy nodes and continue itearation for remaining paths deferredList = []; // Avoid jshint warning 'Don't make functions within a loop.': function __lazyload(key, node, dfd){ callback.call(self, node, "loading"); node.load().done(function(){ self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self)); }).fail(function(errMsg){ self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")"); callback.call(self, node, "error"); dfd.reject(); }); } for(key in loadMap){ node = root._findDirectChild(key); // alert("loadKeyPath: lazy node(" + key + ") = " + node); dfd = new $.Deferred(); deferredList.push(dfd); __lazyload(key, node, dfd); } // Return a promise that is resolved, when ALL paths were loaded return $.when.apply($, deferredList).promise(); }, /** Re-fire beforeActivate and activate events. */ reactivate: function(setFocus) { var res, node = this.activeNode; if( !node ) { return _getResolvedPromise(); } this.activeNode = null; // Force re-activating res = node.setActive(); if( setFocus ){ node.setFocus(); } return res; }, /** Reload tree from source and return a promise. * @param [source] optional new source (defaults to initial source data) * @returns {$.Promise} */ reload: function(source) { this._callHook("treeClear", this); return this._callHook("treeLoad", this, source); }, /**Render tree (i.e. create DOM elements for all top-level nodes). * @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed * @param {boolean} [deep=false] */ render: function(force, deep) { return this.rootNode.render(force, deep); }, // TODO: selectKey: function(key, select) // TODO: serializeArray: function(stopOnParents) /** * @param {boolean} [flag=true] */ setFocus: function(flag) { return this._callHook("treeSetFocus", this, flag); }, /** * Return all nodes as nested list of {@link NodeData}. * * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children) * @param {function} [callback(node)] Called for every node * @returns {Array | object} * @see FancytreeNode#toDict */ toDict: function(includeRoot, callback){ var res = this.rootNode.toDict(true, callback); return includeRoot ? res : res.children; }, /* Implicitly called for string conversions. * @returns {string} */ toString: function(){ return "<Fancytree(#" + this._id + ")>"; }, /* _trigger a widget event with additional node ctx. * @see EventData */ _triggerNodeEvent: function(type, node, originalEvent, extra) { // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx); var ctx = this._makeHookContext(node, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /* _trigger a widget event with additional tree data. */ _triggerTreeEvent: function(type, originalEvent, extra) { // this.debug("_trigger(" + type + ")", ctx); var ctx = this._makeHookContext(this, originalEvent, extra), res = this.widget._trigger(type, originalEvent, ctx); if(res !== false && ctx.result !== undefined){ return ctx.result; } return res; }, /** Call fn(node) for all nodes. * * @param {function} fn the callback function. * Return false to stop iteration, return "skip" to skip this node and children only. * @returns {boolean} false, if the iterator was stopped. */ visit: function(fn) { return this.rootNode.visit(fn, false); }, /** Write warning to browser console (prepending tree info) * * @param {*} msg string or object or array of such */ warn: function(msg){ Array.prototype.unshift.call(arguments, this.toString()); consoleApply("warn", arguments); } }; /** * These additional methods of the {@link Fancytree} class are 'hook functions' * that can be used and overloaded by extensions. * (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.) * @mixin Fancytree_Hooks */ $.extend(Fancytree.prototype, /** @lends Fancytree_Hooks# */ { /** Default handling for mouse click events. * * @param {EventData} ctx */ nodeClick: function(ctx) { // this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which); var activate, expand, // event = ctx.originalEvent, targetType = ctx.targetType, node = ctx.node; // TODO: use switch // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample) if( targetType === "expander" ) { // Clicking the expander icon always expands/collapses this._callHook("nodeToggleExpanded", ctx); } else if( targetType === "checkbox" ) { // Clicking the checkbox always (de)selects this._callHook("nodeToggleSelected", ctx); if( ctx.options.focusOnSelect ) { // #358 this._callHook("nodeSetFocus", ctx, true); } } else { // Honor `clickFolderMode` for expand = false; activate = true; if( node.folder ) { switch( ctx.options.clickFolderMode ) { case 2: // expand only expand = true; activate = false; break; case 3: // expand and activate activate = true; expand = true; //!node.isExpanded(); break; // else 1 or 4: just activate } } if( activate ) { this.nodeSetFocus(ctx); this._callHook("nodeSetActive", ctx, true); } if( expand ) { if(!activate){ // this._callHook("nodeSetFocus", ctx); } // this._callHook("nodeSetExpanded", ctx, true); this._callHook("nodeToggleExpanded", ctx); } } // Make sure that clicks stop, otherwise <a href='#'> jumps to the top // if(event.target.localName === "a" && event.target.className === "fancytree-title"){ // event.preventDefault(); // } // TODO: return promise? }, /** Collapse all other children of same parent. * * @param {EventData} ctx * @param {object} callOpts */ nodeCollapseSiblings: function(ctx, callOpts) { // TODO: return promise? var ac, i, l, node = ctx.node; if( node.parent ){ ac = node.parent.children; for (i=0, l=ac.length; i<l; i++) { if ( ac[i] !== node && ac[i].expanded ){ this._callHook("nodeSetExpanded", ac[i], false, callOpts); } } } }, /** Default handling for mouse douleclick events. * @param {EventData} ctx */ nodeDblclick: function(ctx) { // TODO: return promise? if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) { // this.nodeSetFocus(ctx); // this._callHook("nodeSetActive", ctx, true); this._callHook("nodeToggleExpanded", ctx); } // TODO: prevent text selection on dblclicks if( ctx.targetType === "title" ) { ctx.originalEvent.preventDefault(); } }, /** Default handling for mouse keydown events. * * NOTE: this may be called with node == null if tree (but no node) has focus. * @param {EventData} ctx */ nodeKeydown: function(ctx) { // TODO: return promise? var matchNode, stamp, res, focusNode, event = ctx.originalEvent, node = ctx.node, tree = ctx.tree, opts = ctx.options, which = event.which, whichChar = String.fromCharCode(which), clean = !(event.altKey || event.ctrlKey || event.metaKey || event.shiftKey), $target = $(event.target), handled = true, activate = !(event.ctrlKey || !opts.autoActivate ); // (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); // FT.debug("eventToString", which, '"' + String.fromCharCode(which) + '"', '"' + FT.eventToString(event) + '"'); // Set focus to active (or first node) if no other node has the focus yet if( !node ){ focusNode = (this.getActiveNode() || this.getFirstChild()); if (focusNode){ focusNode.setFocus(); node = ctx.node = this.focusNode; node.debug("Keydown force focus on active node"); } } if( opts.quicksearch && clean && /\w/.test(whichChar) && !$target.is(":input:enabled") ) { // Allow to search for longer streaks if typed in quickly stamp = new Date().getTime(); if( stamp - tree.lastQuicksearchTime > 500 ) { tree.lastQuicksearchTerm = ""; } tree.lastQuicksearchTime = stamp; tree.lastQuicksearchTerm += whichChar; // tree.debug("quicksearch find", tree.lastQuicksearchTerm); matchNode = tree.findNextNode(tree.lastQuicksearchTerm, tree.getActiveNode()); if( matchNode ) { matchNode.setActive(); } event.preventDefault(); return; } switch( FT.eventToString(event) ) { case "+": case "=": // 187: '+' @ Chrome, Safari tree.nodeSetExpanded(ctx, true); break; case "-": tree.nodeSetExpanded(ctx, false); break; case "space": if(opts.checkbox){ tree.nodeToggleSelected(ctx); }else{ tree.nodeSetActive(ctx, true); } break; case "return": tree.nodeSetActive(ctx, true); break; case "backspace": case "left": case "right": case "up": case "down": res = node.navigate(event.which, activate); break; default: handled = false; } if(handled){ event.preventDefault(); } }, // /** Default handling for mouse keypress events. */ // nodeKeypress: function(ctx) { // var event = ctx.originalEvent; // }, // /** Trigger lazyLoad event (async). */ // nodeLazyLoad: function(ctx) { // var node = ctx.node; // if(this._triggerNodeEvent()) // }, /** Load child nodes (async). * * @param {EventData} ctx * @param {object[]|object|string|$.Promise|function} source * @returns {$.Promise} The deferred will be resolved as soon as the (ajax) * data was rendered. */ nodeLoadChildren: function(ctx, source) { var ajax, delay, dfd, tree = ctx.tree, node = ctx.node; if($.isFunction(source)){ source = source(); } // TOTHINK: move to 'ajax' extension? if(source.url){ // `source` is an Ajax options object ajax = $.extend({}, ctx.options.ajax, source); if(ajax.debugDelay){ // simulate a slow server delay = ajax.debugDelay; if($.isArray(delay)){ // random delay range [min..max] delay = delay[0] + Math.random() * (delay[1] - delay[0]); } node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms"); ajax.debugDelay = false; dfd = $.Deferred(function (dfd) { setTimeout(function () { $.ajax(ajax) .done(function () { dfd.resolveWith(this, arguments); }) .fail(function () { dfd.rejectWith(this, arguments); }); }, delay); }); }else{ dfd = $.ajax(ajax); } // Defer the deferred: we want to be able to reject, even if ajax // resolved ok. source = new $.Deferred(); dfd.done(function (data, textStatus, jqXHR) { var errorObj, res; if(this.dataType === "json" && typeof data === "string"){ $.error("Ajax request returned a string (did you get the JSON dataType wrong?)."); } // postProcess is similar to the standard ajax dataFilter hook, // but it is also called for JSONP if( ctx.options.postProcess ){ res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, error: null, dataType: this.dataType}); if( res.error ) { errorObj = $.isPlainObject(res.error) ? res.error : {message: res.error}; errorObj = tree._makeHookContext(node, null, errorObj); source.rejectWith(this, [errorObj]); return; } data = $.isArray(res) ? res : data; } else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) { // Process ASPX WebMethod JSON object inside "d" property data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d; } source.resolveWith(this, [data]); }).fail(function (jqXHR, textStatus, errorThrown) { var errorObj = tree._makeHookContext(node, null, { error: jqXHR, args: Array.prototype.slice.call(arguments), message: errorThrown, details: jqXHR.status + ": " + errorThrown }); source.rejectWith(this, [errorObj]); }); } // #383: accept and convert ECMAScript 6 Promise if( $.isFunction(source.then) && $.isFunction(source["catch"]) ) { dfd = source; source = new $.Deferred(); dfd.then(function(value){ source.resolve(value); }, function(reason){ source.reject(reason); }); } if($.isFunction(source.promise)){ // `source` is a deferred, i.e. ajax request _assert(!node.isLoading(), "recursive load"); // node._isLoading = true; tree.nodeSetStatus(ctx, "loading"); source.done(function (children) { tree.nodeSetStatus(ctx, "ok"); }).fail(function(error){ var ctxErr; if (error.node && error.error && error.message) { // error is already a context object ctxErr = error; } else { ctxErr = tree._makeHookContext(node, null, { error: error, // it can be jqXHR or any custom error args: Array.prototype.slice.call(arguments), message: error ? (error.message || error.toString()) : "" }); } if( tree._triggerNodeEvent("loadError", ctxErr, null) !== false ) { tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details); } }); } // $.when(source) resolves also for non-deferreds return $.when(source).done(function(children){ var metaData; if( $.isPlainObject(children) ){ // We got {foo: 'abc', children: [...]} // Copy extra properties to tree.data.foo _assert($.isArray(children.children), "source must contain (or be) an array of children"); _assert(node.isRootNode(), "source may only be an object for root nodes"); metaData = children; children = children.children; delete metaData.children; $.extend(tree.data, metaData); } _assert($.isArray(children), "expected array of children"); node._setChildren(children); // trigger fancytreeloadchildren tree._triggerNodeEvent("loadChildren", node); // }).always(function(){ // node._isLoading = false; }); }, /** [Not Implemented] */ nodeLoadKeyPath: function(ctx, keyPathList) { // TODO: implement and improve // http://code.google.com/p/dynatree/issues/detail?id=222 }, /** * Remove a single direct child of ctx.node. * @param {EventData} ctx * @param {FancytreeNode} childNode dircect child of ctx.node */ nodeRemoveChild: function(ctx, childNode) { var idx, node = ctx.node, opts = ctx.options, subCtx = $.extend({}, ctx, {node: childNode}), children = node.children; // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString()); if( children.length === 1 ) { _assert(childNode === children[0], "invalid single child"); return this.nodeRemoveChildren(ctx); } if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveMarkup(subCtx); this.nodeRemoveChildren(subCtx); idx = $.inArray(childNode, children); _assert(idx >= 0, "invalid child"); // Unlink to support GC childNode.visit(function(n){ n.parent = null; }, true); this._callHook("treeRegisterNode", this, false, childNode); if ( opts.removeNode ){ opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx); } // remove from child list children.splice(idx, 1); }, /**Remove HTML markup for all descendents of ctx.node. * @param {EventData} ctx */ nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveChildMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.ul){ if( node.isRootNode() ) { $(node.ul).empty(); } else { $(node.ul).remove(); node.ul = null; } node.visit(function(n){ n.li = n.ul = null; }); } }, /**Remove all descendants of ctx.node. * @param {EventData} ctx */ nodeRemoveChildren: function(ctx) { var subCtx, tree = ctx.tree, node = ctx.node, children = node.children, opts = ctx.options; // FT.debug("nodeRemoveChildren()", node.toString()); if(!children){ return; } if( this.activeNode && this.activeNode.isDescendantOf(node)){ this.activeNode.setActive(false); // TODO: don't fire events } if( this.focusNode && this.focusNode.isDescendantOf(node)){ this.focusNode = null; } // TODO: persist must take care to clear select and expand cookies this.nodeRemoveChildMarkup(ctx); // Unlink children to support GC // TODO: also delete this.children (not possible using visit()) subCtx = $.extend({}, ctx); node.visit(function(n){ n.parent = null; tree._callHook("treeRegisterNode", tree, false, n); if ( opts.removeNode ){ subCtx.node = n; opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx); } }); if( node.lazy ){ // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes node.children = []; } else{ node.children = null; } if( !node.isRootNode() ) { node.expanded = false; // #449, #459 } this.nodeRenderStatus(ctx); }, /**Remove HTML markup for ctx.node and all its descendents. * @param {EventData} ctx */ nodeRemoveMarkup: function(ctx) { var node = ctx.node; // FT.debug("nodeRemoveMarkup()", node.toString()); // TODO: Unlink attr.ftnode to support GC if(node.li){ $(node.li).remove(); node.li = null; } this.nodeRemoveChildMarkup(ctx); }, /** * Create `&lt;li>&lt;span>..&lt;/span> .. &lt;/li>` tags for this node. * * This method takes care that all HTML markup is created that is required * to display this node in it's current state. * * Call this method to create new nodes, or after the strucuture * was changed (e.g. after moving this node or adding/removing children) * nodeRenderTitle() and nodeRenderStatus() are implied. * * Note: if a node was created/removed, nodeRender() must be called for the * parent. * &lt;code> * &lt;li id='KEY' ftnode=NODE> * &lt;span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'> * &lt;span class="fancytree-expander">&lt;/span> * &lt;span class="fancytree-checkbox">&lt;/span> // only present in checkbox mode * &lt;span class="fancytree-icon">&lt;/span> * &lt;a href="#" class="fancytree-title"> Node 1 &lt;/a> * &lt;/span> * &lt;ul> // only present if node has children * &lt;li id='KEY' ftnode=NODE> child1 ... &lt;/li> * &lt;li id='KEY' ftnode=NODE> child2 ... &lt;/li> * &lt;/ul> * &lt;/li> * &lt;/code> * * @param {EventData} ctx * @param {boolean} [force=false] re-render, even if html markup was already created * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { /* This method must take care of all cases where the current data mode * (i.e. node hierarchy) does not match the current markup. * * - node was not yet rendered: * create markup * - node was rendered: exit fast * - children have been added * - childern have been removed */ var childLI, childNode1, childNode2, i, l, next, subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, firstTime = false, parent = node.parent, isRootNode = !parent, children = node.children; // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString()); if( ! isRootNode && ! parent.ul ) { // Calling node.collapse on a deep, unrendered node return; } _assert(isRootNode || parent.ul, "parent UL must exist"); // Render the node if( !isRootNode ){ // Discard markup on force-mode, or if it is not linked to parent <ul> if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){ if(node.li.parentNode !== node.parent.ul){ // May happen, when a top-level node was dropped over another this.debug("Unlinking " + node + " (must be child of " + node.parent + ")"); } // this.debug("nodeRemoveMarkup..."); this.nodeRemoveMarkup(ctx); } // Create <li><span /> </li> // node.debug("render..."); if( !node.li ) { // node.debug("render... really"); firstTime = true; node.li = document.createElement("li"); node.li.ftnode = node; if(aria){ // TODO: why doesn't this work: // node.li.role = "treeitem"; // $(node.li).attr("role", "treeitem") // .attr("aria-labelledby", "ftal_" + node.key); } if( node.key && opts.generateIds ){ node.li.id = opts.idPrefix + node.key; } node.span = document.createElement("span"); node.span.className = "fancytree-node"; if(aria){ $(node.span).attr("aria-labelledby", "ftal_" + node.key); } node.li.appendChild(node.span); // Create inner HTML for the <span> (expander, checkbox, icon, and title) this.nodeRenderTitle(ctx); // Allow tweaking and binding, after node was created for the first time if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } }else{ // this.nodeRenderTitle(ctx); this.nodeRenderStatus(ctx); } // Allow tweaking after node state was rendered if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } } // Visit child nodes if( children ){ if( isRootNode || node.expanded || deep === true ) { // Create a UL to hold the children if( !node.ul ){ node.ul = document.createElement("ul"); if((collapsed === true && !_recursive) || !node.expanded){ // hide top UL, so we can use an animation to show it later node.ul.style.display = "none"; } if(aria){ $(node.ul).attr("role", "group"); } if ( node.li ) { // issue #67 node.li.appendChild(node.ul); } else { node.tree.$div.append(node.ul); } } // Add child markup for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); this.nodeRender(subCtx, force, deep, false, true); } // Remove <li> if nodes have moved to another parent childLI = node.ul.firstChild; while( childLI ){ childNode2 = childLI.ftnode; if( childNode2 && childNode2.parent !== node ) { node.debug("_fixParent: remove missing " + childNode2, childLI); next = childLI.nextSibling; childLI.parentNode.removeChild(childLI); childLI = next; }else{ childLI = childLI.nextSibling; } } // Make sure, that <li> order matches node.children order. childLI = node.ul.firstChild; for(i=0, l=children.length-1; i<l; i++) { childNode1 = children[i]; childNode2 = childLI.ftnode; if( childNode1 !== childNode2 ) { // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2); node.ul.insertBefore(childNode1.li, childNode2.li); } else { childLI = childLI.nextSibling; } } } }else{ // No children: remove markup if any if( node.ul ){ // alert("remove child markup for " + node); this.warn("remove child markup for " + node); this.nodeRemoveChildMarkup(ctx); } } if( !isRootNode ){ // Update element classes according to node state // this.nodeRenderStatus(ctx); // Finally add the whole structure to the DOM, so the browser can render if(firstTime){ parent.ul.appendChild(node.li); } } }, /** Create HTML inside the node's outer &lt;span> (i.e. expander, checkbox, * icon, and title). * * nodeRenderStatus() is implied. * @param {EventData} ctx * @param {string} [title] optinal new title */ nodeRenderTitle: function(ctx, title) { // set node connector images, links and text var id, iconSpanClass, nodeTitle, role, tabindex, tooltip, node = ctx.node, tree = ctx.tree, opts = ctx.options, aria = opts.aria, level = node.getLevel(), ares = [], iconSrc = node.data.icon; if(title !== undefined){ node.title = title; } if(!node.span){ // Silently bail out if node was not rendered yet, assuming // node.render() will be called as the node becomes visible return; } // connector (expanded, expandable or simple) // TODO: optimize this if clause if( level < opts.minExpandLevel ) { if( !node.lazy ) { node.expanded = true; } if(level > 1){ if(aria){ ares.push("<span role='button' class='fancytree-expander fancytree-expander-fixed'></span>"); }else{ ares.push("<span class='fancytree-expander fancytree-expander-fixed''></span>"); } } // .. else (i.e. for root level) skip expander/connector alltogether } else { if(aria){ ares.push("<span role='button' class='fancytree-expander'></span>"); }else{ ares.push("<span class='fancytree-expander'></span>"); } } // Checkbox mode if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) { if(aria){ ares.push("<span role='checkbox' class='fancytree-checkbox'></span>"); }else{ ares.push("<span class='fancytree-checkbox'></span>"); } } // folder or doctype icon role = aria ? " role='img'" : ""; if( iconSrc === true || (iconSrc !== false && opts.icons !== false) ) { // opts.icons defines the default behavior, node.icon == true/false can override this if ( iconSrc && typeof iconSrc === "string" ) { // node.icon is an image url iconSrc = (iconSrc.charAt(0) === "/") ? iconSrc : ((opts.imagePath || "") + iconSrc); ares.push("<img src='" + iconSrc + "' class='fancytree-icon' alt='' />"); } else { // See if node.iconClass or opts.iconClass() define a class name iconSpanClass = (opts.iconClass && opts.iconClass.call(tree, node, ctx)) || node.data.iconclass || null; if( iconSpanClass ) { ares.push("<span " + role + " class='fancytree-custom-icon " + iconSpanClass + "'></span>"); } else { ares.push("<span " + role + " class='fancytree-icon'></span>"); } } } // node title nodeTitle = ""; if ( opts.renderTitle ){ nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || ""; } if(!nodeTitle){ tooltip = node.tooltip ? " title='" + FT.escapeHtml(node.tooltip) + "'" : ""; id = aria ? " id='ftal_" + node.key + "'" : ""; role = aria ? " role='treeitem'" : ""; tabindex = opts.titlesTabbable ? " tabindex='0'" : ""; nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>"; } ares.push(nodeTitle); // Note: this will trigger focusout, if node had the focus //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly node.span.innerHTML = ares.join(""); // Update CSS classes this.nodeRenderStatus(ctx); }, /** Update element classes according to node state. * @param {EventData} ctx */ nodeRenderStatus: function(ctx) { // Set classes for current status var node = ctx.node, tree = ctx.tree, opts = ctx.options, // nodeContainer = node[tree.nodeContainerAttrName], hasChildren = node.hasChildren(), isLastSib = node.isLastSibling(), aria = opts.aria, // $ariaElem = aria ? $(node[tree.ariaPropName]) : null, $ariaElem = $(node.span).find(".fancytree-title"), cn = opts._classNames, cnList = [], statusElem = node[tree.statusClassPropName]; if( !statusElem ){ // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway) return; } // Build a list of class names that we will add to the node <span> cnList.push(cn.node); if( tree.activeNode === node ){ cnList.push(cn.active); // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // tree.$container.removeAttr("tabindex"); // }else{ // $(">span.fancytree-title", statusElem).removeAttr("tabindex"); // tree.$container.attr("tabindex", "0"); } if( tree.focusNode === node ){ cnList.push(cn.focused); if(aria){ // $(">span.fancytree-title", statusElem).attr("tabindex", "0"); // $(">span.fancytree-title", statusElem).attr("tabindex", "-1"); // TODO: is this the right element for this attribute? $ariaElem .attr("aria-activedescendant", true); // .attr("tabindex", "-1"); } }else if(aria){ // $(">span.fancytree-title", statusElem).attr("tabindex", "-1"); $ariaElem .removeAttr("aria-activedescendant"); // .removeAttr("tabindex"); } if( node.expanded ){ cnList.push(cn.expanded); if(aria){ $ariaElem.attr("aria-expanded", true); } }else if(aria){ $ariaElem.removeAttr("aria-expanded"); } if( node.folder ){ cnList.push(cn.folder); } if( hasChildren !== false ){ cnList.push(cn.hasChildren); } // TODO: required? if( isLastSib ){ cnList.push(cn.lastsib); } if( node.lazy && node.children == null ){ cnList.push(cn.lazy); } if( node.partsel ){ cnList.push(cn.partsel); } if( node.unselectable ){ cnList.push(cn.unselectable); } if( node._isLoading ){ cnList.push(cn.loading); } if( node._error ){ cnList.push(cn.error); } if( node.selected ){ cnList.push(cn.selected); if(aria){ $ariaElem.attr("aria-selected", true); } }else if(aria){ $ariaElem.attr("aria-selected", false); } if( node.extraClasses ){ cnList.push(node.extraClasses); } // IE6 doesn't correctly evaluate multiple class names, // so we create combined class names that can be used in the CSS if( hasChildren === false ){ cnList.push(cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "") ); }else{ cnList.push(cn.combinedExpanderPrefix + (node.expanded ? "e" : "c") + (node.lazy && node.children == null ? "d" : "") + (isLastSib ? "l" : "") ); } cnList.push(cn.combinedIconPrefix + (node.expanded ? "e" : "c") + (node.folder ? "f" : "") ); // node.span.className = cnList.join(" "); statusElem.className = cnList.join(" "); // TODO: we should not set this in the <span> tag also, if we set it here: // Maybe most (all) of the classes should be set in LI instead of SPAN? if(node.li){ node.li.className = isLastSib ? cn.lastsib : ""; } }, /** Activate node. * flag defaults to true. * If flag is true, the node is activated (must be a synchronous operation) * If flag is false, the node is deactivated (must be a synchronous operation) * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false} * @returns {$.Promise} */ nodeSetActive: function(ctx, flag, callOpts) { // Handle user click / [space] / [enter], according to clickFolderMode. callOpts = callOpts || {}; var subCtx, node = ctx.node, tree = ctx.tree, opts = ctx.options, noEvents = (callOpts.noEvents === true), noFocus = (callOpts.noFocus === true), isActive = (node === tree.activeNode); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetActive", flag); if(isActive === flag){ // Nothing to do return _getResolvedPromise(node); }else if(flag && !noEvents && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } if(flag){ if(tree.activeNode){ _assert(tree.activeNode !== node, "node was active (inconsistency)"); subCtx = $.extend({}, ctx, {node: tree.activeNode}); tree.nodeSetActive(subCtx, false); _assert(tree.activeNode === null, "deactivate was out of sync?"); } if(opts.activeVisible){ // tree.nodeMakeVisible(ctx); node.makeVisible({scrollIntoView: false}); // nodeSetFocus will scroll } tree.activeNode = node; tree.nodeRenderStatus(ctx); if( !noFocus ) { tree.nodeSetFocus(ctx); } if( !noEvents ) { tree._triggerNodeEvent("activate", node, ctx.originalEvent); } }else{ _assert(tree.activeNode === node, "node was not active (inconsistency)"); tree.activeNode = null; this.nodeRenderStatus(ctx); if( !noEvents ) { ctx.tree._triggerNodeEvent("deactivate", node, ctx.originalEvent); } } return _getResolvedPromise(node); }, /** Expand or collapse node, return Deferred.promise. * * @param {EventData} ctx * @param {boolean} [flag=true] * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false} * @returns {$.Promise} The deferred will be resolved as soon as the (lazy) * data was retrieved, rendered, and the expand animation finshed. */ nodeSetExpanded: function(ctx, flag, callOpts) { callOpts = callOpts || {}; var _afterLoad, dfd, i, l, parents, prevAC, node = ctx.node, tree = ctx.tree, opts = ctx.options, noAnimation = (callOpts.noAnimation === true), noEvents = (callOpts.noEvents === true); // flag defaults to true flag = (flag !== false); // node.debug("nodeSetExpanded(" + flag + ")"); if((node.expanded && flag) || (!node.expanded && !flag)){ // Nothing to do // node.debug("nodeSetExpanded(" + flag + "): nothing to do"); return _getResolvedPromise(node); }else if(flag && !node.lazy && !node.hasChildren() ){ // Prevent expanding of empty nodes // return _getRejectedPromise(node, ["empty"]); return _getResolvedPromise(node); }else if( !flag && node.getLevel() < opts.minExpandLevel ) { // Prevent collapsing locked levels return _getRejectedPromise(node, ["locked"]); }else if ( !noEvents && this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){ // Callback returned false return _getRejectedPromise(node, ["rejected"]); } // If this node inside a collpased node, no animation and scrolling is needed if( !noAnimation && !node.isVisible() ) { noAnimation = callOpts.noAnimation = true; } dfd = new $.Deferred(); // Auto-collapse mode: collapse all siblings if( flag && !node.expanded && opts.autoCollapse ) { parents = node.getParentList(false, true); prevAC = opts.autoCollapse; try{ opts.autoCollapse = false; for(i=0, l=parents.length; i<l; i++){ // TODO: should return promise? this._callHook("nodeCollapseSiblings", parents[i], callOpts); } }finally{ opts.autoCollapse = prevAC; } } // Trigger expand/collapse after expanding dfd.done(function(){ var lastChild = node.getLastChild(); if( flag && opts.autoScroll && !noAnimation && lastChild ) { // Scroll down to last child, but keep current node visible lastChild.scrollIntoView(true, {topNode: node}).always(function(){ if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } }); } else { if( !noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } } }); // vvv Code below is executed after loading finished: _afterLoad = function(callback){ var isVisible, isExpanded, effect = opts.toggleEffect; node.expanded = flag; // Create required markup, but make sure the top UL is hidden, so we // can animate later tree._callHook("nodeRender", ctx, false, false, true); // If the currently active node is now hidden, deactivate it // if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) { // this.activeNode.deactivate(); // } // Expanding a lazy node: set 'loading...' and call callback // if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) { // this._loadContent(); // return; // } // Hide children, if node is collapsed if( node.ul ) { isVisible = (node.ul.style.display !== "none"); isExpanded = !!node.expanded; if ( isVisible === isExpanded ) { node.warn("nodeSetExpanded: UL.style.display already set"); } else if ( !effect || noAnimation ) { node.ul.style.display = ( node.expanded || !parent ) ? "" : "none"; } else { // The UI toggle() effect works with the ext-wide extension, // while jQuery.animate() has problems when the title span // has positon: absolute // duration = opts.fx.duration || 200; // easing = opts.fx.easing; // $(node.ul).animate(opts.fx, duration, easing, function(){ // node.debug("nodeSetExpanded: animate start..."); $(node.ul).toggle(effect.effect, effect.options, effect.duration, function(){ // node.debug("nodeSetExpanded: animate done"); callback(); }); return; } } callback(); }; // ^^^ Code above is executed after loading finshed. // Load lazy nodes, if any. Then continue with _afterLoad() if(flag && node.lazy && node.hasChildren() === undefined){ // node.debug("nodeSetExpanded: load start..."); node.load().done(function(){ // node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad(function () { dfd.resolveWith(node); }); }).fail(function(errMsg){ _afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); }); /* var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent); _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result"); node.debug("nodeSetExpanded: load start..."); this._callHook("nodeLoadChildren", ctx, source).done(function(){ node.debug("nodeSetExpanded: load done"); if(dfd.notifyWith){ // requires jQuery 1.6+ dfd.notifyWith(node, ["loaded"]); } _afterLoad.call(tree); }).fail(function(errMsg){ dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); }); */ }else{ _afterLoad(function () { dfd.resolveWith(node); }); } // node.debug("nodeSetExpanded: returns"); return dfd.promise(); }, /** Focus or blur this node. * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetFocus: function(ctx, flag) { // ctx.node.debug("nodeSetFocus(" + flag + ")"); var ctx2, tree = ctx.tree, node = ctx.node; flag = (flag !== false); // Blur previous node if any if(tree.focusNode){ if(tree.focusNode === node && flag){ // node.debug("nodeSetFocus(" + flag + "): nothing to do"); return; } ctx2 = $.extend({}, ctx, {node: tree.focusNode}); tree.focusNode = null; this._triggerNodeEvent("blur", ctx2); this._callHook("nodeRenderStatus", ctx2); } // Set focus to container and node if(flag){ if( !this.hasFocus() ){ node.debug("nodeSetFocus: forcing container focus"); this._callHook("treeSetFocus", ctx, true, {calledByNode: true}); } node.makeVisible({scrollIntoView: false}); tree.focusNode = node; // node.debug("FOCUS..."); // $(node.span).find(".fancytree-title").focus(); this._triggerNodeEvent("focus", ctx); // if(ctx.options.autoActivate){ // tree.nodeSetActive(ctx, true); // } if(ctx.options.autoScroll){ node.scrollIntoView(); } this._callHook("nodeRenderStatus", ctx); } }, /** (De)Select node, return new status (sync). * * @param {EventData} ctx * @param {boolean} [flag=true] */ nodeSetSelected: function(ctx, flag) { var node = ctx.node, tree = ctx.tree, opts = ctx.options; // flag defaults to true flag = (flag !== false); node.debug("nodeSetSelected(" + flag + ")", ctx); if( node.unselectable){ return; } // TODO: !!node.expanded is nicer, but doesn't pass jshint // https://github.com/jshint/jshint/issues/455 // if( !!node.expanded === !!flag){ if((node.selected && flag) || (!node.selected && !flag)){ return !!node.selected; }else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){ return !!node.selected; } if(flag && opts.selectMode === 1){ // single selection mode if(tree.lastSelectedNode){ tree.lastSelectedNode.setSelected(false); } }else if(opts.selectMode === 3){ // multi.hier selection mode node.selected = flag; // this._fixSelectionState(node); node.fixSelection3AfterClick(); } node.selected = flag; this.nodeRenderStatus(ctx); tree.lastSelectedNode = flag ? node : null; tree._triggerNodeEvent("select", ctx); }, /** Show node status (ok, loading, error) using styles and a dummy child node. * * @param {EventData} ctx * @param status * @param message * @param details */ nodeSetStatus: function(ctx, status, message, details) { var node = ctx.node, tree = ctx.tree; // cn = ctx.options._classNames; function _clearStatusNode() { // Remove dedicated dummy node, if any var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { try{ // I've seen exceptions here with loadKeyPath... if(node.ul){ node.ul.removeChild(firstChild.li); firstChild.li = null; // avoid leaks (DT issue 215) } }catch(e){} if( node.children.length === 1 ){ node.children = []; }else{ node.children.shift(); } } } function _setStatusNode(data, type) { // Create/modify the dedicated dummy node for 'loading...' or // 'error!' status. (only called for direct child of the invisible // system root) var firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $.extend(firstChild, data); // tree._callHook("nodeRender", firstChild); tree._callHook("nodeRenderTitle", firstChild); } else { data.key = "_statusNode"; node._setChildren([data]); node.children[0].statusNodeType = type; tree.render(); } return node.children[0]; } switch( status ){ case "ok": _clearStatusNode(); // $(node.span).removeClass(cn.loading).removeClass(cn.error); node._isLoading = false; node._error = null; node.renderStatus(); break; case "loading": // $(node.span).removeClass(cn.error).addClass(cn.loading); if( !node.parent ) { _setStatusNode({ title: tree.options.strings.loading + (message ? " (" + message + ") " : ""), tooltip: details, extraClasses: "fancytree-statusnode-wait" }, status); } node._isLoading = true; node._error = null; node.renderStatus(); break; case "error": // $(node.span).removeClass(cn.loading).addClass(cn.error); _setStatusNode({ title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""), tooltip: details, extraClasses: "fancytree-statusnode-error" }, status); node._isLoading = false; node._error = { message: message, details: details }; node.renderStatus(); break; default: $.error("invalid node status " + status); } }, /** * * @param {EventData} ctx */ nodeToggleExpanded: function(ctx) { return this.nodeSetExpanded(ctx, !ctx.node.expanded); }, /** * @param {EventData} ctx */ nodeToggleSelected: function(ctx) { return this.nodeSetSelected(ctx, !ctx.node.selected); }, /** Remove all nodes. * @param {EventData} ctx */ treeClear: function(ctx) { var tree = ctx.tree; tree.activeNode = null; tree.focusNode = null; tree.$div.find(">ul.fancytree-container").empty(); // TODO: call destructors and remove reference loops tree.rootNode.children = null; }, /** Widget was created (called only once, even it re-initialized). * @param {EventData} ctx */ treeCreate: function(ctx) { }, /** Widget was destroyed. * @param {EventData} ctx */ treeDestroy: function(ctx) { this.$div.find(">ul.fancytree-container").remove(); this.$source && this.$source.removeClass("ui-helper-hidden"); }, /** Widget was (re-)initialized. * @param {EventData} ctx */ treeInit: function(ctx) { //this.debug("Fancytree.treeInit()"); this.treeLoad(ctx); }, /** Parse Fancytree from source, as configured in the options. * @param {EventData} ctx * @param {object} [source] optional new source (use last data otherwise) */ treeLoad: function(ctx, source) { var type, $ul, tree = ctx.tree, $container = ctx.widget.element, dfd, // calling context for root node rootCtx = $.extend({}, ctx, {node: this.rootNode}); if(tree.rootNode.children){ this.treeClear(ctx); } source = source || this.options.source; if(!source){ type = $container.data("type") || "html"; switch(type){ case "html": $ul = $container.find(">ul:first"); $ul.addClass("ui-fancytree-source ui-helper-hidden"); source = $.ui.fancytree.parseHtml($ul); // allow to init tree.data.foo from <ul data-foo=''> this.data = $.extend(this.data, _getElementDataAsDict($ul)); break; case "json": // $().addClass("ui-helper-hidden"); source = $.parseJSON($container.text()); if(source.children){ if(source.title){tree.title = source.title;} source = source.children; } break; default: $.error("Invalid data-type: " + type); } }else if(typeof source === "string"){ // TODO: source is an element ID $.error("Not implemented"); } // $container.addClass("ui-widget ui-widget-content ui-corner-all"); // Trigger fancytreeinit after nodes have been loaded dfd = this.nodeLoadChildren(rootCtx, source).done(function(){ tree.render(); if( ctx.options.selectMode === 3 ){ tree.rootNode.fixSelection3FromEndNodes(); } tree._triggerTreeEvent("init", null, { status: true }); }).fail(function(){ tree.render(); tree._triggerTreeEvent("init", null, { status: false }); }); return dfd; }, /** Node was inserted into or removed from the tree. * @param {EventData} ctx * @param {boolean} add * @param {FancytreeNode} node */ treeRegisterNode: function(ctx, add, node) { }, /** Widget got focus. * @param {EventData} ctx * @param {boolean} [flag=true] */ treeSetFocus: function(ctx, flag, callOpts) { flag = (flag !== false); // this.debug("treeSetFocus(" + flag + "), callOpts: " + callOpts); // this.debug(" focusNode: " + this.focusNode); // this.debug(" activeNode: " + this.activeNode); if( flag !== this.hasFocus() ){ this._hasFocus = flag; if( !flag && this.focusNode ) { // Node also looses focus if widget blurs this.focusNode.setFocus(false); } this.$container.toggleClass("fancytree-treefocus", flag); this._triggerTreeEvent(flag ? "focusTree" : "blurTree"); } } }); /* ****************************************************************************** * jQuery UI widget boilerplate */ /** * The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br> * This constructor is not called directly. Use `$(selector).fancytree({})` * to initialize the plugin instead.<br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access widget methods and members: * var tree = $("#tree").fancytree("getTree"); * var node = $("#tree").fancytree("getActiveNode", "1234"); * </pre> * * @mixin Fancytree_Widget */ $.widget("ui.fancytree", /** @lends Fancytree_Widget# */ { /**These options will be used as defaults * @type {FancytreeOptions} */ options: { activeVisible: true, ajax: { type: "GET", cache: false, // false: Append random '_' argument to the request url to prevent caching. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable dataType: "json" // Expect json format and pass json object to callbacks. }, // aria: false, // TODO: default to true autoActivate: true, autoCollapse: false, // autoFocus: false, autoScroll: false, checkbox: false, /**defines click behavior*/ clickFolderMode: 4, debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo) disabled: false, // TODO: required anymore? enableAspx: true, // TODO: document extensions: [], // fx: { height: "toggle", duration: 200 }, // toggleEffect: { effect: "drop", options: {direction: "left"}, duration: 200 }, // toggleEffect: { effect: "slide", options: {direction: "up"}, duration: 200 }, toggleEffect: { effect: "blind", options: {direction: "vertical", scale: "box"}, duration: 200 }, generateIds: false, icons: true, idPrefix: "ft_", focusOnSelect: false, keyboard: true, keyPathSeparator: "/", minExpandLevel: 1, quicksearch: false, scrollOfs: {top: 0, bottom: 0}, scrollParent: null, selectMode: 2, strings: { loading: "Loading&#8230;", loadError: "Load error!" }, tabbable: true, titlesTabbable: false, _classNames: { node: "fancytree-node", folder: "fancytree-folder", combinedExpanderPrefix: "fancytree-exp-", combinedIconPrefix: "fancytree-ico-", hasChildren: "fancytree-has-children", active: "fancytree-active", selected: "fancytree-selected", expanded: "fancytree-expanded", lazy: "fancytree-lazy", focused: "fancytree-focused", partsel: "fancytree-partsel", unselectable: "fancytree-unselectable", lastsib: "fancytree-lastsib", loading: "fancytree-loading", error: "fancytree-error" }, // events lazyLoad: null, postProcess: null }, /* Set up the widget, Called on first $().fancytree() */ _create: function() { this.tree = new Fancytree(this); this.$source = this.source || this.element.data("type") === "json" ? this.element : this.element.find(">ul:first"); // Subclass Fancytree instance with all enabled extensions var extension, extName, i, extensions = this.options.extensions, base = this.tree; for(i=0; i<extensions.length; i++){ extName = extensions[i]; extension = $.ui.fancytree._extensions[extName]; if(!extension){ $.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)"); } // Add extension options as tree.options.EXTENSION // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName); this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]); // Add a namespace tree.ext.EXTENSION, to hold instance data _assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'"); // this.tree[extName] = extension; this.tree.ext[extName] = {}; // Subclass Fancytree methods using proxies. _subclassObject(this.tree, base, extension, extName); // current extension becomes base for the next extension base = extension; } // this.tree._callHook("treeCreate", this.tree); // Note: 'fancytreecreate' event is fired by widget base class // this.tree._triggerTreeEvent("create"); }, /* Called on every $().fancytree() */ _init: function() { this.tree._callHook("treeInit", this.tree); // TODO: currently we call bind after treeInit, because treeInit // might change tree.$container. // It would be better, to move ebent binding into hooks altogether this._bind(); }, /* Use the _setOption method to respond to changes to options */ _setOption: function(key, value) { var callDefault = true, rerender = false; switch( key ) { case "aria": case "checkbox": case "icons": case "minExpandLevel": case "tabbable": // case "nolink": this.tree._callHook("treeCreate", this.tree); rerender = true; break; case "source": callDefault = false; this.tree._callHook("treeLoad", this.tree, value); break; } this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">"); if(callDefault){ // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget $.Widget.prototype._setOption.apply(this, arguments); // TODO: In jQuery UI 1.9 and above, you use the _super method instead // this._super( "_setOption", key, value ); } if(rerender){ this.tree.render(true, false); // force, not-deep } }, /** Use the destroy method to clean up any modifications your widget has made to the DOM */ destroy: function() { this._unbind(); this.tree._callHook("treeDestroy", this.tree); // In jQuery UI 1.8, you must invoke the destroy method from the base widget $.Widget.prototype.destroy.call(this); // TODO: delete tree and nodes to make garbage collect easier? // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method }, // ------------------------------------------------------------------------- /* Remove all event handlers for our namespace */ _unbind: function() { var ns = this.tree._ns; this.element.unbind(ns); this.tree.$container.unbind(ns); $(document).unbind(ns); }, /* Add mouse and kyboard handlers to the container */ _bind: function() { var that = this, opts = this.options, tree = this.tree, ns = tree._ns // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" ) ; // Remove all previuous handlers for this tree this._unbind(); //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container); // tree.debug("bind events; container: ", tree.$container); tree.$container.on("focusin" + ns + " focusout" + ns, function(event){ var node = FT.getNode(event), flag = (event.type === "focusin"); // tree.debug("Tree container got event " + event.type, node, event); // tree.treeOnFocusInOut.call(tree, event); if(node){ // For example clicking into an <input> that is part of a node tree._callHook("nodeSetFocus", node, flag); }else{ tree._callHook("treeSetFocus", tree, flag); } }).on("selectstart" + ns, "span.fancytree-title", function(event){ // prevent mouse-drags to select text ranges // tree.debug("<span title> got event " + event.type); event.preventDefault(); }).on("keydown" + ns, function(event){ // TODO: also bind keyup and keypress // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus()); // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){ if(opts.disabled || opts.keyboard === false ){ return true; } var res, node = tree.focusNode, // node may be null ctx = tree._makeHookContext(node || tree, event), prevPhase = tree.phase; try { tree.phase = "userEvent"; // If a 'fancytreekeydown' handler returns false, skip the default // handling (implemented by tree.nodeKeydown()). if(node){ res = tree._triggerNodeEvent("keydown", node, event); }else{ res = tree._triggerTreeEvent("keydown", event); } if ( res === "preventNav" ){ res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls } else if ( res !== false ){ res = tree._callHook("nodeKeydown", ctx); } return res; } finally { tree.phase = prevPhase; } }).on("click" + ns + " dblclick" + ns, function(event){ if(opts.disabled){ return true; } var ctx, et = FT.getEventTarget(event), node = et.node, tree = that.tree, prevPhase = tree.phase; if( !node ){ return true; // Allow bubbling of other events } ctx = tree._makeHookContext(node, event); // that.tree.debug("event(" + event.type + "): node: ", node); try { tree.phase = "userEvent"; switch(event.type) { case "click": ctx.targetType = et.type; return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx); case "dblclick": ctx.targetType = et.type; return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx); } // } catch(e) { // // var _ = null; // DT issue 117 // TODO // $.error(e); } finally { tree.phase = prevPhase; } }); }, /** Return the active node or null. * @returns {FancytreeNode} */ getActiveNode: function() { return this.tree.activeNode; }, /** Return the matching node or null. * @param {string} key * @returns {FancytreeNode} */ getNodeByKey: function(key) { return this.tree.getNodeByKey(key); }, /** Return the invisible system root node. * @returns {FancytreeNode} */ getRootNode: function() { return this.tree.rootNode; }, /** Return the current tree instance. * @returns {Fancytree} */ getTree: function() { return this.tree; } }); // $.ui.fancytree was created by the widget factory. Create a local shortcut: FT = $.ui.fancytree; /** * Static members in the `$.ui.fancytree` namespace.<br> * <br> * <pre class="sh_javascript sunlight-highlight-javascript">// Access static members: * var node = $.ui.fancytree.getNode(element); * alert($.ui.fancytree.version); * </pre> * * @mixin Fancytree_Static */ $.extend($.ui.fancytree, /** @lends Fancytree_Static# */ { /** @type {string} */ version: "2.10.2", // Set to semver by 'grunt release' /** @type {string} */ buildType: "production", // Set to 'production' by 'grunt build' /** @type {int} */ debugLevel: 1, // Set to 1 by 'grunt build' // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel _nextId: 1, _nextNodeKey: 1, _extensions: {}, // focusTree: null, /** Expose class object as $.ui.fancytree._FancytreeClass */ _FancytreeClass: Fancytree, /** Expose class object as $.ui.fancytree._FancytreeNodeClass */ _FancytreeNodeClass: FancytreeNode, /* Feature checks to provide backwards compatibility */ jquerySupports: { // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at positionMyOfs: isVersionAtLeast($.ui.version, 1, 9) }, /** Throw an error if condition fails (debug method). * @param {boolean} cond * @param {string} msg */ assert: function(cond, msg){ return _assert(cond, msg); }, /** Return a function that executes *fn* at most every *timeout* ms. * @param {integer} timeout * @param {function} fn * @param {boolean} [invokeAsap=false] * @param {any} [ctx] */ debounce: function(timeout, fn, invokeAsap, ctx) { var timer; if(arguments.length === 3 && typeof invokeAsap !== "boolean") { ctx = invokeAsap; invokeAsap = false; } return function() { var args = arguments; ctx = ctx || this; invokeAsap && !timer && fn.apply(ctx, args); clearTimeout(timer); timer = setTimeout(function() { invokeAsap || fn.apply(ctx, args); timer = null; }, timeout); }; }, /** Write message to console if debugLevel >= 2 * @param {string} msg */ debug: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments); }, /** Write error message to console. * @param {string} msg */ error: function(msg){ consoleApply("error", arguments); }, /** Convert &lt;, &gt;, &amp;, &quot;, &#39;, &#x2F; to the equivalent entities. * * @param {string} s * @returns {string} */ escapeHtml: function(s){ return ("" + s).replace(/[&<>"'\/]/g, function (s) { return ENTITY_MAP[s]; }); }, /** Make jQuery.position() arguments backwards compatible, i.e. if * jQuery UI version <= 1.8, convert * { my: "left+3 center", at: "left bottom", of: $target } * to * { my: "left center", at: "left bottom", of: $target, offset: "3 0" } * * See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at * and http://jsfiddle.net/mar10/6xtu9a4e/ */ fixPositionOptions: function(opts) { if( opts.offset || ("" + opts.my + opts.at ).indexOf("%") >= 0 ) { $.error("expected new position syntax (but '%' is not supported)"); } if( ! $.ui.fancytree.jquerySupports.positionMyOfs ) { var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined] myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.my), atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(opts.at), // convert to numbers dx = (myParts[2] ? (+myParts[2]) : 0) + (atParts[2] ? (+atParts[2]) : 0), dy = (myParts[4] ? (+myParts[4]) : 0) + (atParts[4] ? (+atParts[4]) : 0); opts = $.extend({}, opts, { // make a copy and overwrite my: myParts[1] + " " + myParts[3], at: atParts[1] + " " + atParts[3] }); if( dx || dy ) { opts.offset = "" + dx + " " + dy; } } return opts; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTargetType: function(event){ return this.getEventTarget(event).type; }, /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event. * * @param {Event} event Mouse event, e.g. click, ... * @returns {object} Return a {node: FancytreeNode, type: TYPE} object * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined */ getEventTarget: function(event){ var tcn = event && event.target ? event.target.className : "", res = {node: this.getNode(event.target), type: undefined}; // We use a fast version of $(res.node).hasClass() // See http://jsperf.com/test-for-classname/2 if( /\bfancytree-title\b/.test(tcn) ){ res.type = "title"; }else if( /\bfancytree-expander\b/.test(tcn) ){ res.type = (res.node.hasChildren() === false ? "prefix" : "expander"); }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){ res.type = "checkbox"; }else if( /\bfancytree-icon\b/.test(tcn) ){ res.type = "icon"; }else if( /\bfancytree-node\b/.test(tcn) ){ // Somewhere near the title res.type = "title"; }else if( event && event.target && $(event.target).closest(".fancytree-title").length ) { // #228: clicking an embedded element inside a title res.type = "title"; } return res; }, /** Return a FancytreeNode instance from element. * * @param {Element | jQueryObject | Event} el * @returns {FancytreeNode} matching node or null */ getNode: function(el){ if(el instanceof FancytreeNode){ return el; // el already was a FancytreeNode }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } while( el ) { if(el.ftnode) { return el.ftnode; } el = el.parentNode; } return null; }, /* Return a Fancytree instance from element. * TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem * @param {Element | jQueryObject | Event} el * @returns {Fancytree} matching tree or null * / getTree: function(el){ if(el instanceof Fancytree){ return el; // el already was a Fancytree }else if(el.selector !== undefined){ el = el[0]; // el was a jQuery object: use the DOM element }else if(el.originalEvent !== undefined){ el = el.target; // el was an Event } ... return null; }, */ /** Write message to console if debugLevel >= 1 * @param {string} msg */ info: function(msg){ /*jshint expr:true */ ($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments); }, /** Convert a keydown or mouse event to a canonical string like 'ctrl+a', 'ctrl+shift+f2', 'shift+leftdblclick'. * This is especially handy for switch-statements in event handlers. * @param {event} * @returns {string} */ eventToString: function(event) { // Poor-man's hotkeys. See here for a complete implementation: // https://github.com/jeresig/jquery.hotkeys var which = event.which, et = event.type, s = []; if( event.altKey ) { s.push("alt"); } if( event.ctrlKey ) { s.push("ctrl"); } if( event.metaKey ) { s.push("meta"); } if( event.shiftKey ) { s.push("shift"); } if( et === "click" || et === "dblclick" ) { s.push(MOUSE_BUTTONS[event.button] + et); } else { if( !IGNORE_KEYCODES[which] ) { s.push( SPECIAL_KEYCODES[which] || String.fromCharCode(which).toLowerCase() ); } } return s.join("+"); }, /* @deprecated: use eventToString(event) instead. */ keyEventToString: function(event) { this.warn("keyEventToString() is deprecated: use eventToString()"); return this.eventToString(event); }, /** * Parse tree data from HTML <ul> markup * * @param {jQueryObject} $ul * @returns {NodeData[]} */ parseHtml: function($ul) { // TODO: understand this: /*jshint validthis:true */ var extraClasses, i, l, iPos, tmp, tmp2, classes, className, $children = $ul.find(">li"), children = []; $children.each(function() { var allData, $li = $(this), $liSpan = $li.find(">span:first", this), $liA = $liSpan.length ? null : $li.find(">a:first"), d = { tooltip: null, data: {} }; if( $liSpan.length ) { d.title = $liSpan.html(); } else if( $liA && $liA.length ) { // If a <li><a> tag is specified, use it literally and extract href/target. d.title = $liA.html(); d.data.href = $liA.attr("href"); d.data.target = $liA.attr("target"); d.tooltip = $liA.attr("title"); } else { // If only a <li> tag is specified, use the trimmed string up to // the next child <ul> tag. d.title = $li.html(); iPos = d.title.search(/<ul/i); if( iPos >= 0 ){ d.title = d.title.substring(0, iPos); } } d.title = $.trim(d.title); // Make sure all fields exist for(i=0, l=CLASS_ATTRS.length; i<l; i++){ d[CLASS_ATTRS[i]] = undefined; } // Initialize to `true`, if class is set and collect extraClasses classes = this.className.split(" "); extraClasses = []; for(i=0, l=classes.length; i<l; i++){ className = classes[i]; if(CLASS_ATTR_MAP[className]){ d[className] = true; }else{ extraClasses.push(className); } } d.extraClasses = extraClasses.join(" "); // Parse node options from ID, title and class attributes tmp = $li.attr("title"); if( tmp ){ d.tooltip = tmp; // overrides <a title='...'> } tmp = $li.attr("id"); if( tmp ){ d.key = tmp; } // Add <li data-NAME='...'> as node.data.NAME allData = _getElementDataAsDict($li); if(allData && !$.isEmptyObject(allData)) { // #56: Allow to set special node.attributes from data-... for(i=0, l=NODE_ATTRS.length; i<l; i++){ tmp = NODE_ATTRS[i]; tmp2 = allData[tmp]; if( tmp2 != null ) { delete allData[tmp]; d[tmp] = tmp2; } } // All other data-... goes to node.data... $.extend(d.data, allData); } // Recursive reading of child nodes, if LI tag contains an UL tag $ul = $li.find(">ul:first"); if( $ul.length ) { d.children = $.ui.fancytree.parseHtml($ul); }else{ d.children = d.lazy ? undefined : null; } children.push(d); // FT.debug("parse ", d, children); }); return children; }, /** Add Fancytree extension definition to the list of globally available extensions. * * @param {object} definition */ registerExtension: function(definition){ _assert(definition.name != null, "extensions must have a `name` property."); _assert(definition.version != null, "extensions must have a `version` property."); $.ui.fancytree._extensions[definition.name] = definition; }, /** Inverse of escapeHtml(). * * @param {string} s * @returns {string} */ unescapeHtml: function(s){ var e = document.createElement("div"); e.innerHTML = s; return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue; }, /** Write warning message to console. * @param {string} msg */ warn: function(msg){ consoleApply("warn", arguments); } }); }(jQuery, window, document)); // Extending Fancytree // =================== // // See also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code. // // Every extension should have a comment header containing some information // about the author, copyright and licensing. Also a pointer to the latest // source code. // Prefix with `/*!` so the comment is not removed by the minifier. /*! * jquery.fancytree.childcounter.js * * Add a child counter bubble to tree nodes. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ // To keep the global namespace clean, we wrap everything in a closure ;(function($, undefined) { // Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/) "use strict"; // The [coding guidelines](http://contribute.jquery.org/style-guide/js/) // require jshint compliance. // But for this sample, we want to allow unused variables for demonstration purpose. /*jshint unused:false */ // Adding methods // -------------- // New member functions can be added to the `Fancytree` class. // This function will be available for every tree instance. // // var tree = $("#tree").fancytree("getTree"); // tree.countSelected(false); $.ui.fancytree._FancytreeClass.prototype.countSelected = function(topOnly){ var tree = this, treeOptions = tree.options; return tree.getSelectedNodes(topOnly).length; }; // The `FancytreeNode` class can also be easily extended. This would be called // like // // node.toUpper(); $.ui.fancytree._FancytreeNodeClass.prototype.toUpper = function(){ var node = this; return node.setTitle(node.title.toUpperCase()); }; // Finally, we can extend the widget API and create functions that are called // like so: // // $("#tree").fancytree("widgetMethod1", "abc"); $.ui.fancytree.prototype.widgetMethod1 = function(arg1){ var tree = this.tree; return arg1; }; // Register a Fancytree extension // ------------------------------ // A full blown extension, extension is available for all trees and can be // enabled like so (see also the [live demo](http://wwwendt.de/tech/fancytree/demo/sample-ext-childcounter.html)): // // <script src="../src/jquery.fancytree.js" type="text/javascript"></script> // <script src="../src/jquery.fancytree.childcounter.js" type="text/javascript"></script> // ... // // $("#tree").fancytree({ // extensions: ["childcounter"], // childcounter: { // hideExpanded: true // }, // ... // }); // /* 'childcounter' extension */ $.ui.fancytree.registerExtension({ // Every extension must be registered by a unique name. name: "childcounter", // Version information should be compliant with [semver](http://semver.org) version: "1.0.0", // Extension specific options and their defaults. // This options will be available as `tree.options.childcounter.hideExpanded` options: { deep: true, hideZeros: true, hideExpanded: false }, // Attributes other than `options` (or functions) can be defined here, and // will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`. // They can also be accessed as `this._local.foo` from within the extension // methods. foo: 42, // Local functions are prefixed with an underscore '_'. // Callable as `this._local._appendCounter()`. _appendCounter: function(bar){ var tree = this; }, // **Override virtual methods for this extension.** // // Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'. // with a `ctx` argument (see [EventData](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/global.html#EventData) // for details) and an extended calling context:<br> // `this` : the Fancytree instance<br> // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br> // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree) // // See also the [complete list of available hook functions](http://www.wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html). /* Init */ // `treeInit` is triggered when a tree is initalized. We can set up classes or // bind event handlers here... treeInit: function(ctx){ var tree = this, // same as ctx.tree, opts = ctx.options, extOpts = ctx.options.childcounter; // Optionally check for dependencies with other extensions /* this._requireExtension("glyph", false, false); */ // Call the base implementation this._superApply(arguments); // Add a class to the tree container this.$container.addClass("fancytree-ext-childcounter"); }, // Destroy this tree instance (we only call the default implementation, so // this method could as well be omitted). treeDestroy: function(ctx){ this._superApply(arguments); }, // Overload the `renderTitle` hook, to append a counter badge nodeRenderTitle: function(ctx, title) { var node = ctx.node, extOpts = ctx.options.childcounter, count = (node.data.childCounter == null) ? node.countChildren(extOpts.deep) : +node.data.childCounter; // Let the base implementation render the title this._superApply(arguments); // Append a counter badge if( (count || ! extOpts.hideZeros) && (!node.isExpanded() || !extOpts.hideExpanded) ){ $("span.fancytree-icon", node.span).append($("<span class='fancytree-childcounter'/>").text(count)); } }, // Overload the `setExpanded` hook, so the counters are updated nodeSetExpanded: function(ctx, flag, opts) { var tree = ctx.tree, node = ctx.node; // Let the base implementation expand/collapse the node, then redraw the title // after the animation has finished return this._superApply(arguments).always(function(){ tree.nodeRenderTitle(ctx); }); } // End of extension definition }); // End of namespace closure }(jQuery)); /*! * * jquery.fancytree.clones.js * Support faster lookup of nodes by key and shared ref-ids. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ function _assert(cond, msg){ // TODO: see qunit.js extractStacktrace() if(!cond){ msg = msg ? ": " + msg : ""; $.error("Assertion failed" + msg); } } /* Return first occurrence of member from array. */ function _removeArrayMember(arr, elem) { // TODO: use Array.indexOf for IE >= 9 var i; for (i = arr.length - 1; i >= 0; i--) { if (arr[i] === elem) { arr.splice(i, 1); return true; } } return false; } // /** // * Calculate a 32 bit FNV-1a hash // * Found here: https://gist.github.com/vaiorabbit/5657561 // * Ref.: http://isthe.com/chongo/tech/comp/fnv/ // * // * @param {string} str the input value // * @param {boolean} [asString=false] set to true to return the hash value as // * 8-digit hex string instead of an integer // * @param {integer} [seed] optionally pass the hash of the previous chunk // * @returns {integer | string} // */ // function hashFnv32a(str, asString, seed) { // /*jshint bitwise:false */ // var i, l, // hval = (seed === undefined) ? 0x811c9dc5 : seed; // for (i = 0, l = str.length; i < l; i++) { // hval ^= str.charCodeAt(i); // hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24); // } // if( asString ){ // // Convert to 8 digit hex string // return ("0000000" + (hval >>> 0).toString(16)).substr(-8); // } // return hval >>> 0; // } /** * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @author <a href="mailto:[email protected]">Gary Court</a> * @see http://github.com/garycourt/murmurhash-js * @author <a href="mailto:[email protected]">Austin Appleby</a> * @see http://sites.google.com/site/murmurhash/ * * @param {string} key ASCII only * @param {boolean} [asString=false] * @param {number} seed Positive integer only * @return {number} 32-bit positive integer hash */ function hashMurmur3(key, asString, seed) { /*jshint bitwise:false */ var h1b, k1, remainder = key.length & 3, bytes = key.length - remainder, h1 = seed, c1 = 0xcc9e2d51, c2 = 0x1b873593, i = 0; while (i < bytes) { k1 = ((key.charCodeAt(i) & 0xff)) | ((key.charCodeAt(++i) & 0xff) << 8) | ((key.charCodeAt(++i) & 0xff) << 16) | ((key.charCodeAt(++i) & 0xff) << 24); ++i; k1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff; h1 ^= k1; h1 = (h1 << 13) | (h1 >>> 19); h1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff; h1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16)); } k1 = 0; switch (remainder) { /*jshint -W086:true */ case 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16; case 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8; case 1: k1 ^= (key.charCodeAt(i) & 0xff); k1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff; k1 = (k1 << 15) | (k1 >>> 17); k1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff; h1 ^= k1; } h1 ^= key.length; h1 ^= h1 >>> 16; h1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff; h1 ^= h1 >>> 13; h1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff; h1 ^= h1 >>> 16; if( asString ){ // Convert to 8 digit hex string return ("0000000" + (h1 >>> 0).toString(16)).substr(-8); } return h1 >>> 0; } // console.info(hashMurmur3("costarring")); // console.info(hashMurmur3("costarring", true)); // console.info(hashMurmur3("liquid")); // console.info(hashMurmur3("liquid", true)); /* * Return a unique key for node by calculationg the hash of the parents refKey-list */ function calcUniqueKey(node) { var key, path = $.map(node.getParentList(false, true), function(e){ return e.refKey || e.key; }); path = path.join("/"); key = "id_" + hashMurmur3(path, true); // node.debug(path + " -> " + key); return key; } /** * [ext-clones] Return a list of clone-nodes or null. * @param {boolean} [includeSelf=false] * @returns {FancytreeNode[] | null} * * @alias FancytreeNode#getCloneList * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function(includeSelf){ var key, tree = this.tree, refList = tree.refMap[this.refKey] || null, keyMap = tree.keyMap; if( refList ) { key = this.key; // Convert key list to node list if( includeSelf ) { refList = $.map(refList, function(val){ return keyMap[val]; }); } else { refList = $.map(refList, function(val){ return val === key ? null : keyMap[val]; }); if( refList.length < 1 ) { refList = null; } } } return refList; }; /** * [ext-clones] Return true if this node has at least another clone with same refKey. * @returns {boolean} * * @alias FancytreeNode#isClone * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isClone = function(){ var refKey = this.refKey || null, refList = refKey && this.tree.refMap[refKey] || null; return !!(refList && refList.length > 1); }; /** * [ext-clones] Update key and/or refKey for an existing node. * @param {string} key * @param {string} refKey * @returns {boolean} * * @alias FancytreeNode#reRegister * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function(key, refKey){ key = (key == null) ? null : "" + key; refKey = (refKey == null) ? null : "" + refKey; // this.debug("reRegister", key, refKey); var tree = this.tree, prevKey = this.key, prevRefKey = this.refKey, keyMap = tree.keyMap, refMap = tree.refMap, refList = refMap[prevRefKey] || null, // curCloneKeys = refList ? node.getCloneList(true), modified = false; // Key has changed: update all references if( key != null && key !== this.key ) { if( keyMap[key] ) { $.error("[ext-clones] reRegister(" + key + "): already exists: " + this); } // Update keyMap delete keyMap[prevKey]; keyMap[key] = this; // Update refMap if( refList ) { refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? key : e; }); } this.key = key; modified = true; } // refKey has changed if( refKey != null && refKey !== this.refKey ) { // Remove previous refKeys if( refList ){ if( refList.length === 1 ){ delete refMap[prevRefKey]; }else{ refMap[prevRefKey] = $.map(refList, function(e){ return e === prevKey ? null : e; }); } } // Add refKey if( refMap[refKey] ) { refMap[refKey].append(key); }else{ refMap[refKey] = [ this.key ]; } this.refKey = refKey; modified = true; } return modified; }; /** * [ext-clones] Return all nodes with a given refKey (null if not found). * @param {string} refKey * @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node * @returns {FancytreeNode[] | null} * @alias Fancytree#getNodesByRef * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function(refKey, rootNode){ var keyMap = this.keyMap, refList = this.refMap[refKey] || null; if( refList ) { // Convert key list to node list if( rootNode ) { refList = $.map(refList, function(val){ var node = keyMap[val]; return node.isDescendantOf(rootNode) ? node : null; }); }else{ refList = $.map(refList, function(val){ return keyMap[val]; }); } if( refList.length < 1 ) { refList = null; } } return refList; }; /** * [ext-clones] Replace a refKey with a new one. * @param {string} oldRefKey * @param {string} newRefKey * @alias Fancytree#changeRefKey * @requires jquery.fancytree.clones.js */ $.ui.fancytree._FancytreeClass.prototype.changeRefKey = function(oldRefKey, newRefKey) { var i, node, keyMap = this.keyMap, refList = this.refMap[oldRefKey] || null; if (refList) { for (i = 0; i < refList.length; i++) { node = keyMap[refList[i]]; node.refKey = newRefKey; } delete this.refMap[oldRefKey]; this.refMap[newRefKey] = refList; } }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "clones", version: "0.0.3", // Default options for this extension. options: { highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers highlightClones: false // set 'fancytree-clone' class on any node that has at least one clone }, treeCreate: function(ctx){ this._superApply(arguments); ctx.tree.refMap = {}; ctx.tree.keyMap = {}; }, treeInit: function(ctx){ this.$container.addClass("fancytree-ext-clones"); _assert(ctx.options.defaultKey == null); // Generate unique / reproducible default keys ctx.options.defaultKey = function(node){ return calcUniqueKey(node); }; // The default implementation loads initial data this._superApply(arguments); }, treeClear: function(ctx){ ctx.tree.refMap = {}; ctx.tree.keyMap = {}; return this._superApply(arguments); }, treeRegisterNode: function(ctx, add, node) { var refList, len, tree = ctx.tree, keyMap = tree.keyMap, refMap = tree.refMap, key = node.key, refKey = (node && node.refKey != null) ? "" + node.refKey : null; // ctx.tree.debug("clones.treeRegisterNode", add, node); if( key === "_statusNode" ){ return this._superApply(arguments); } if( add ) { if( keyMap[node.key] != null ) { $.error("clones.treeRegisterNode: node.key already exists: " + node); } keyMap[key] = node; if( refKey ) { refList = refMap[refKey]; if( refList ) { refList.push(key); if( refList.length === 2 && ctx.options.clones.highlightClones ) { // Mark peer node, if it just became a clone (no need to // mark current node, since it will be rendered later anyway) keyMap[refList[0]].renderStatus(); } } else { refMap[refKey] = [key]; } // node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]); } }else { if( keyMap[key] == null ) { $.error("clones.treeRegisterNode: node.key not registered: " + node.key); } delete keyMap[key]; if( refKey ) { refList = refMap[refKey]; // node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]); if( refList ) { len = refList.length; if( len <= 1 ){ _assert(len === 1); _assert(refList[0] === key); delete refMap[refKey]; }else{ _removeArrayMember(refList, key); // Unmark peer node, if this was the only clone if( len === 2 && ctx.options.clones.highlightClones ) { // node.debug("clones.treeRegisterNode: last =>", node.getCloneList()); keyMap[refList[0]].renderStatus(); } } // node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]); } } } return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { var $span, res, node = ctx.node; res = this._superApply(arguments); if( ctx.options.clones.highlightClones ) { $span = $(node[ctx.tree.statusClassPropName]); // Only if span already exists if( $span.length && node.isClone() ){ // node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones); $span.addClass("fancytree-clone"); } } return res; }, nodeSetActive: function(ctx, flag) { var res, scpn = ctx.tree.statusClassPropName, node = ctx.node; res = this._superApply(arguments); if( ctx.options.clones.highlightActiveClones && node.isClone() ) { $.each(node.getCloneList(true), function(idx, n){ // n.debug("clones.nodeSetActive: ", flag !== false); $(n[scpn]).toggleClass("fancytree-active-clone", flag !== false); }); } return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.dnd.js * * Drag-and-drop support. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ var didRegisterDnd = false; /* Convert number to string and prepend +/-; return empty string for 0.*/ function offsetString(n){ return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n)); } /* ***************************************************************************** * Drag and drop support */ function _initDragAndDrop(tree) { var dnd = tree.options.dnd || null; // Register 'connectToFancytree' option with ui.draggable if( dnd ) { _registerDnd(); } // Attach ui.draggable to this Fancytree instance if(dnd && dnd.dragStart ) { tree.widget.element.draggable($.extend({ addClasses: false, // DT issue 244: helper should be child of scrollParent: appendTo: tree.$container, // appendTo: "body", containment: false, delay: 0, distance: 4, revert: false, scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container scrollSpeed: 7, scrollSensitivity: 10, // Delegate draggable.start, drag, and stop events to our handler connectToFancytree: true, // Let source tree create the helper element helper: function(event) { var $helper, $nodeTag, sourceNode = $.ui.fancytree.getNode(event.target); if(!sourceNode){ // #405, DT issue 211: might happen, if dragging a table *header* return "<div>ERROR?: helper requested but sourceNode not found</div>"; } $nodeTag = $(sourceNode.span); // Only event and node argument is available $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>") .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar .append($nodeTag.find("span.fancytree-title").clone()); // Attach node reference to helper object $helper.data("ftSourceNode", sourceNode); // we return an unconnected element, so `draggable` will add this // to the parent specified as `appendTo` option return $helper; }, start: function(event, ui) { var sourceNode = ui.helper.data("ftSourceNode"); return !!sourceNode; // Abort dragging if no node could be found } }, tree.options.dnd.draggable)); } // Attach ui.droppable to this Fancytree instance if(dnd && dnd.dragDrop) { tree.widget.element.droppable($.extend({ addClasses: false, tolerance: "intersect", greedy: false /* activate: function(event, ui) { tree.debug("droppable - activate", event, ui, this); }, create: function(event, ui) { tree.debug("droppable - create", event, ui); }, deactivate: function(event, ui) { tree.debug("droppable - deactivate", event, ui); }, drop: function(event, ui) { tree.debug("droppable - drop", event, ui); }, out: function(event, ui) { tree.debug("droppable - out", event, ui); }, over: function(event, ui) { tree.debug("droppable - over", event, ui); } */ }, tree.options.dnd.droppable)); } } //--- Extend ui.draggable event handling -------------------------------------- function _registerDnd() { if(didRegisterDnd){ return; } // Register proxy-functions for draggable.start/drag/stop $.ui.plugin.add("draggable", "connectToFancytree", { start: function(event, ui) { // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 var draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null; if(sourceNode) { // Adjust helper offset, so cursor is slightly outside top/left corner draggable.offset.click.top = -2; draggable.offset.click.left = + 16; // Trigger dragStart event // TODO: when called as connectTo..., the return value is ignored(?) return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable); } }, drag: function(event, ui) { var isHelper, logObject, // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null, prevTargetNode = ui.helper.data("ftTargetNode") || null, targetNode = $.ui.fancytree.getNode(event.target); if(event.target && !targetNode){ // We got a drag event, but the targetNode could not be found // at the event location. This may happen, // 1. if the mouse jumped over the drag helper, // 2. or if a non-fancytree element is dragged // We ignore it: isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0; if(isHelper){ logObject = sourceNode || prevTargetNode || $.ui.fancytree; logObject.debug("Drag event over helper: ignored."); return; } } ui.helper.data("ftTargetNode", targetNode); // Leaving a tree node if(prevTargetNode && prevTargetNode !== targetNode ) { prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); } if(targetNode){ if(!targetNode.tree.options.dnd.dragDrop) { // not enabled as drop target } else if(targetNode === prevTargetNode) { // Moving over same node targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable); }else{ // Entering this node first time targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); } } // else go ahead with standard event handling }, stop: function(event, ui) { // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10 var logObject, draggable = $(this).data("ui-draggable") || $(this).data("draggable"), sourceNode = ui.helper.data("ftSourceNode") || null, targetNode = ui.helper.data("ftTargetNode") || null, // mouseDownEvent = draggable._mouseDownEvent, eventType = event.type, dropped = (eventType === "mouseup" && event.which === 1); if(!dropped){ logObject = sourceNode || targetNode || $.ui.fancytree; logObject.debug("Drag was cancelled"); } if(targetNode) { if(dropped){ targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); } targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); } if(sourceNode){ sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable); } } }); didRegisterDnd = true; } /* ***************************************************************************** * */ $.ui.fancytree.registerExtension({ name: "dnd", version: "0.1.0", // Default options for this extension. options: { // Make tree nodes accept draggables autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering. draggable: null, // Additional options passed to jQuery draggable droppable: null, // Additional options passed to jQuery droppable focusOnClick: false, // Focus, although draggable cancels mousedown event (#270) // helper: null, // Callback // helperParent: null, // jQuery object (defaults to Fancytree container) preventVoidMoves: true, // Prevent dropping nodes 'before self', etc. preventRecursiveMoves: true, // Prevent dropping nodes on own descendants // Events (drag support) dragStart: null, // Callback(sourceNode, data), return true, to enable dnd dragStop: null, // Callback(sourceNode, data) // Events (drop support) dragEnter: null, // Callback(targetNode, data) dragOver: null, // Callback(targetNode, data) dragDrop: null, // Callback(targetNode, data) dragLeave: null // Callback(targetNode, data) }, treeInit: function(ctx){ var tree = ctx.tree; this._superApply(arguments); // issue #270: draggable eats mousedown events if( tree.options.dnd.dragStart ){ tree.$container.on("mousedown", function(event){ // if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) { if( ctx.options.dnd.focusOnClick ) { // #270 var node = $.ui.fancytree.getNode(event); if (node){ node.debug("Re-enable focus that was prevented by jQuery UI draggable."); // node.setFocus(); // $(node.span).closest(":tabbable").focus(); // $(event.target).trigger("focus"); // $(event.target).closest(":tabbable").trigger("focus"); } setTimeout(function() { // #300 $(event.target).closest(":tabbable").focus(); }, 10); } }); } _initDragAndDrop(tree); }, /* Override key handler in order to cancel dnd on escape.*/ nodeKeydown: function(ctx) { var event = ctx.originalEvent; if( event.which === $.ui.keyCode.ESCAPE) { this._local._cancelDrag(); } return this._superApply(arguments); }, nodeClick: function(ctx) { // if( ctx.options.dnd.dragStart ){ // ctx.tree.$container.focus(); // } return this._superApply(arguments); }, /* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */ _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) { var markerOffsetX = 0, markerAt = "center", instData = this._local, $source = sourceNode ? $(sourceNode.span) : null, $target = $(targetNode.span); if( !instData.$dropMarker ) { instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>") .hide() .css({"z-index": 1000}) .prependTo($(this.$div).parent()); // .prependTo("body"); } // this.$dropMarker.attr("class", hitMode); if(hitMode === "after" || hitMode === "before" || hitMode === "over"){ // $source && $source.addClass("fancytree-drag-source"); // $target.addClass("fancytree-drop-target"); switch(hitMode){ case "before": instData .$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over") .addClass("fancytree-drop-before"); markerAt = "top"; break; case "after": instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over") .addClass("fancytree-drop-after"); markerAt = "bottom"; break; default: instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before") .addClass("fancytree-drop-over"); $target.addClass("fancytree-drop-target"); markerOffsetX = 8; } instData.$dropMarker .show() .position($.ui.fancytree.fixPositionOptions({ my: "left" + offsetString(markerOffsetX) + " center", at: "left " + markerAt, of: $target })); // helper.addClass("fancytree-drop-hover"); } else { // $source && $source.removeClass("fancytree-drag-source"); $target.removeClass("fancytree-drop-target"); instData.$dropMarker.hide(); // helper.removeClass("fancytree-drop-hover"); } if(hitMode === "after"){ $target.addClass("fancytree-drop-after"); } else { $target.removeClass("fancytree-drop-after"); } if(hitMode === "before"){ $target.addClass("fancytree-drop-before"); } else { $target.removeClass("fancytree-drop-before"); } if(accept === true){ if($source){ $source.addClass("fancytree-drop-accept"); } $target.addClass("fancytree-drop-accept"); helper.addClass("fancytree-drop-accept"); }else{ if($source){ $source.removeClass("fancytree-drop-accept"); } $target.removeClass("fancytree-drop-accept"); helper.removeClass("fancytree-drop-accept"); } if(accept === false){ if($source){ $source.addClass("fancytree-drop-reject"); } $target.addClass("fancytree-drop-reject"); helper.addClass("fancytree-drop-reject"); }else{ if($source){ $source.removeClass("fancytree-drop-reject"); } $target.removeClass("fancytree-drop-reject"); helper.removeClass("fancytree-drop-reject"); } }, /* * Handles drag'n'drop functionality. * * A standard jQuery drag-and-drop process may generate these calls: * * draggable helper(): * _onDragEvent("helper", sourceNode, null, event, null, null); * start: * _onDragEvent("start", sourceNode, null, event, ui, draggable); * drag: * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable); * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable); * stop: * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable); * _onDragEvent("stop", sourceNode, null, event, ui, draggable); */ _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) { if(eventName !== "over"){ this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this); } var /*$helper, $helperParent,*/ nodeOfs, relPos, relPos2, enterResponse, hitMode, r, opts = this.options, dnd = opts.dnd, ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}), res = null, $nodeTag = $(node.span); switch (eventName) { // case "helper": // // Only event and node argument is available // $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>") // .css({zIndex: 3, position: "relative"}) // so it appears above ext-wide selection bar // .append($nodeTag.find("span.fancytree-title").clone()); // // #345: helper parent is now set using draggable.appendTo // // $helperParent = dnd.helperParent || $("ul.fancytree-container", node.tree.$div); // // DT issue 244: helper should be child of scrollParent // // $helperParent.append($helper); // // Attach node reference to helper object // $helper.data("ftSourceNode", node); // // this.debug("helper=%o", $helper); // // this.debug("helper.sourceNode=%o", $helper.data("ftSourceNode")); // res = $helper; // break; case "start": if( node.isStatusNode() ) { res = false; } else if(dnd.dragStart) { res = dnd.dragStart(node, ctx); } if(res === false) { this.debug("tree.dragStart() cancelled"); //draggable._clear(); // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned) // TODO: call this._cancelDrag()? ui.helper.trigger("mouseup") .hide(); } else { $nodeTag.addClass("fancytree-drag-source"); } break; case "enter": if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){ r = false; }else{ r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null; } if(!r){ // convert null, undefined, false to false res = false; }else if ( $.isArray(r) ) { // TODO: also accept passing an object of this format directly res = { over: ($.inArray("over", r) >= 0), before: ($.inArray("before", r) >= 0), after: ($.inArray("after", r) >= 0) }; }else{ res = { over: ((r === true) || (r === "over")), before: ((r === true) || (r === "before")), after: ((r === true) || (r === "after")) }; } ui.helper.data("enterResponse", res); this.debug("helper.enterResponse: %o", res); break; case "over": enterResponse = ui.helper.data("enterResponse"); hitMode = null; if(enterResponse === false){ // Don't call dragOver if onEnter returned false. // break; } else if(typeof enterResponse === "string") { // Use hitMode from onEnter if provided. hitMode = enterResponse; } else { // Calculate hitMode from relative cursor position. nodeOfs = $nodeTag.offset(); relPos = { x: event.pageX - nodeOfs.left, y: event.pageY - nodeOfs.top }; relPos2 = { x: relPos.x / $nodeTag.width(), y: relPos.y / $nodeTag.height() }; if( enterResponse.after && relPos2.y > 0.75 ){ hitMode = "after"; } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){ hitMode = "after"; } else if(enterResponse.before && relPos2.y <= 0.25) { hitMode = "before"; } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) { hitMode = "before"; } else if(enterResponse.over) { hitMode = "over"; } // Prevent no-ops like 'before source node' // TODO: these are no-ops when moving nodes, but not in copy mode if( dnd.preventVoidMoves ){ if(node === otherNode){ this.debug(" drop over source node prevented"); hitMode = null; }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){ this.debug(" drop after source node prevented"); hitMode = null; }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){ this.debug(" drop before source node prevented"); hitMode = null; }else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){ this.debug(" drop last child over own parent prevented"); hitMode = null; } } // this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling()); ui.helper.data("hitMode", hitMode); } // Auto-expand node (only when 'over' the node, not 'before', or 'after') if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) { node.scheduleAction("expand", dnd.autoExpandMS); } if(hitMode && dnd.dragOver){ // TODO: http://code.google.com/p/dynatree/source/detail?r=625 ctx.hitMode = hitMode; res = dnd.dragOver(node, ctx); } // DT issue 332 // this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false); this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null); break; case "drop": hitMode = ui.helper.data("hitMode"); if(hitMode && dnd.dragDrop){ ctx.hitMode = hitMode; dnd.dragDrop(node, ctx); } break; case "leave": // Cancel pending expand request node.scheduleAction("cancel"); ui.helper.data("enterResponse", null); ui.helper.data("hitMode", null); this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined); if(dnd.dragLeave){ dnd.dragLeave(node, ctx); } break; case "stop": $nodeTag.removeClass("fancytree-drag-source"); if(dnd.dragStop){ dnd.dragStop(node, ctx); } break; default: $.error("Unsupported drag event: " + eventName); } return res; }, _cancelDrag: function() { var dd = $.ui.ddmanager.current; if(dd){ dd.cancel(); } } }); }(jQuery, window, document)); /*! * jquery.fancytree.edit.js * * Make node titles editable. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ var isMac = /Mac/.test(navigator.platform), escapeHtml = $.ui.fancytree.escapeHtml, unescapeHtml = $.ui.fancytree.unescapeHtml; /** * [ext-edit] Start inline editing of current node title. * * @alias FancytreeNode#editStart * @requires Fancytree */ $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){ var $input, node = this, tree = this.tree, local = tree.ext.edit, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), eventData = { node: node, tree: tree, options: tree.options, isNew: $(node.span).hasClass("fancytree-edit-new"), orgTitle: node.title, input: null, dirty: false }; // beforeEdit may want to modify the title before editing if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false ) { return false; } $.ui.fancytree.assert(!local.currentNode, "recursive edit"); local.currentNode = this; local.eventData = eventData; // Disable standard Fancytree mouse- and key handling tree.widget._unbind(); // #116: ext-dnd prevents the blur event, so we have to catch outer clicks $(document).on("mousedown.fancytree-edit", function(event){ if( ! $(event.target).hasClass("fancytree-edit-input") ){ node.editEnd(true, event); } }); // Replace node with <input> $input = $("<input />", { "class": "fancytree-edit-input", type: "text", value: unescapeHtml(eventData.orgTitle) }); local.eventData.input = $input; if ( instOpts.adjustWidthOfs != null ) { $input.width($title.width() + instOpts.adjustWidthOfs); } if ( instOpts.inputCss != null ) { $input.css(instOpts.inputCss); } $title.html($input); // Focus <input> and bind keyboard handler $input .focus() .change(function(event){ $input.addClass("fancytree-edit-dirty"); }).keydown(function(event){ switch( event.which ) { case $.ui.keyCode.ESCAPE: node.editEnd(false, event); break; case $.ui.keyCode.ENTER: node.editEnd(true, event); return false; // so we don't start editmode on Mac } event.stopPropagation(); }).blur(function(event){ return node.editEnd(true, event); }); instOpts.edit.call(node, {type: "edit"}, eventData); }; /** * [ext-edit] Stop inline editing. * @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified) * @alias FancytreeNode#editEnd * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){ var newVal, node = this, tree = this.tree, local = tree.ext.edit, eventData = local.eventData, instOpts = tree.options.edit, $title = $(".fancytree-title", node.span), $input = $title.find("input.fancytree-edit-input"); // eventData.isNew = $(node.span).hasClass("fancytree-edit-new"); if( instOpts.trim ) { $input.val($.trim($input.val())); } newVal = $input.val(); // eventData.dirty = $input.hasClass("fancytree-edit-dirty") || ; eventData.dirty = ( newVal !== node.title ); // Find out, if saving is required if( applyChanges === false ) { // If true/false was passed, honor this (except in rename mode, if unchanged) eventData.save = false; } else if( eventData.isNew ) { // In create mode, we save everyting, except for empty text eventData.save = (newVal !== ""); } else { // In rename mode, we save everyting, except for empty or unchanged text eventData.save = eventData.dirty && (newVal !== ""); } // Allow to break (keep editor open), modify input, or re-define data.save if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){ return false; } if( eventData.save && instOpts.save.call(node, {type: "save"}, eventData) === false){ return false; } $input .removeClass("fancytree-edit-dirty") .unbind(); // Unbind outer-click handler $(document).off(".fancytree-edit"); if( eventData.save ) { node.setTitle( escapeHtml(newVal) ); // $(node.span).removeClass("fancytree-edit-new"); node.setFocus(); }else{ if( eventData.isNew ) { node.remove(); node = eventData.node = null; local.relatedNode.setFocus(); } else { node.renderTitle(); node.setFocus(); } } local.eventData = null; local.currentNode = null; local.relatedNode = null; // Re-enable mouse and keyboard handling tree.widget._bind(); // Set keyboard focus, even if setFocus() claims 'nothing to do' $(tree.$container).focus(); eventData.input = null; instOpts.close.call(node, {type: "close"}, eventData); return true; }; /** * [ext-edit] Create a new child or sibling node and start edit mode. * * @param {String} [mode='child'] 'before', 'after', or 'child' * @param {Object} [init] NodeData (or simple title string) * @alias FancytreeNode#editCreateNode * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode, init){ var newNode, self = this; mode = mode || "child"; if( init == null ) { init = { title: "" }; } else if( typeof init === "string" ) { init = { title: init }; } else { $.ui.fancytree.assert($.isPlainObject(init)); } // Make sure node is expanded (and loaded) in 'child' mode if( mode === "child" && !this.isExpanded() && this.hasChildren() !== false ) { this.setExpanded().done(function(){ self.editCreateNode(mode, init); }); return; } newNode = this.addNode(init, mode); newNode.makeVisible(/*{noAnimation: true}*/).done(function(){ $(newNode.span).addClass("fancytree-edit-new"); self.tree.ext.edit.relatedNode = self; newNode.editStart(); }); }; /** * [ext-edit] Check if any node in this tree in edit mode. * * @returns {FancytreeNode | null} * @alias Fancytree#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeClass.prototype.isEditing = function(){ return this.ext.edit.currentNode; }; /** * [ext-edit] Check if this node is in edit mode. * @returns {Boolean} true if node is currently beeing edited * @alias FancytreeNode#isEditing * @requires jquery.fancytree.edit.js */ $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){ return this.tree.ext.edit.currentNode === this; }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "edit", version: "0.2.0", // Default options for this extension. options: { adjustWidthOfs: 4, // null: don't adjust input size to content allowEmpty: false, // Prevent empty input inputCss: {minWidth: "3em"}, triggerCancel: ["esc", "tab", "click"], // triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"], triggerStart: ["f2", "shift+click", "mac+enter"], trim: true, // Trim whitespace before save // Events: beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available) beforeEdit: $.noop, // Return false to prevent edit mode close: $.noop, // Editor was removed edit: $.noop, // Editor was opened (available as data.input) // keypress: $.noop, // Not yet implemented save: $.noop // Save data.input.val() or return false to keep editor open }, // Local attributes currentNode: null, treeInit: function(ctx){ this._superApply(arguments); this.$container.addClass("fancytree-ext-edit"); }, nodeClick: function(ctx) { if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){ if( ctx.originalEvent.shiftKey ){ ctx.node.editStart(); return false; } } return this._superApply(arguments); }, nodeDblclick: function(ctx) { if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } return this._superApply(arguments); }, nodeKeydown: function(ctx) { switch( ctx.originalEvent.which ) { case 113: // [F2] if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){ ctx.node.editStart(); return false; } break; case $.ui.keyCode.ENTER: if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){ ctx.node.editStart(); return false; } break; } return this._superApply(arguments); } }); }(jQuery, window, document)); /*! * jquery.fancytree.filter.js * * Remove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ function _escapeRegex(str){ /*jshint regexdash:true */ return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1"); } $.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function(filter, branchMode, opts){ var leavesOnly, match, re, count = 0, hideMode = this.options.filter.mode === "hide"; opts = opts || {}; leavesOnly = !!opts.leavesOnly && !branchMode; // Default to 'match title substring (not case sensitive)' if(typeof filter === "string"){ match = _escapeRegex(filter); // make sure a '.' is treated literally re = new RegExp(".*" + match + ".*", "i"); filter = function(node){ return !!re.exec(node.title); }; } this.enableFilter = true; this.lastFilterArgs = arguments; this.$div.addClass("fancytree-ext-filter"); if( hideMode ){ this.$div.addClass("fancytree-ext-filter-hide"); } else { this.$div.addClass("fancytree-ext-filter-dimm"); } // Reset current filter this.visit(function(node){ delete node.match; delete node.subMatch; }); // Adjust node.hide, .match, .subMatch flags this.visit(function(node){ if ((!leavesOnly || node.children == null) && filter(node)) { count++; node.match = true; node.visitParents(function(p){ p.subMatch = true; if( opts.autoExpand && !p.expanded ) { p.setExpanded(true, {noAnimation: true, noEvents: true, scrollIntoView: false}); p._filterAutoExpanded = true; } }); if( branchMode ) { node.visit(function(p){ p.match = true; }); return "skip"; } } }); // Redraw this.render(); return count; }; /** * [ext-filter] Dimm or hide nodes. * * @param {function | string} filter * @param {boolean} [opts={autoExpand: false, leavesOnly: false}] * @returns {integer} count * @alias Fancytree#filterNodes * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterNodes = function(filter, opts) { if( typeof opts === "boolean" ) { opts = { leavesOnly: opts }; this.warn("Fancytree.filterNodes() leavesOnly option is deprecated since 2015-04-20."); } return this._applyFilterImpl(filter, false, opts); }; /** * @deprecated */ $.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){ this.warn("Fancytree.applyFilter() is deprecated since 2014-05-10. Use .filterNodes() instead."); return this.filterNodes.apply(this, arguments); }; /** * [ext-filter] Dimm or hide whole branches. * * @param {function | string} filter * @param {boolean} [opts={autoExpand: false}] * @returns {integer} count * @alias Fancytree#filterBranches * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.filterBranches = function(filter, opts){ return this._applyFilterImpl(filter, true, opts); }; /** * [ext-filter] Reset the filter. * * @alias Fancytree#clearFilter * @requires jquery.fancytree.filter.js */ $.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){ this.visit(function(node){ delete node.match; delete node.subMatch; if( node._filterAutoExpanded && node.expanded ) { node.setExpanded(false, {noAnimation: true, noEvents: true, scrollIntoView: false}); } delete node._filterAutoExpanded; }); this.enableFilter = false; this.lastFilterArgs = null; this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide"); this.render(); }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "filter", version: "0.4.0", // Default options for this extension. options: { autoApply: true, // re-apply last filter if lazy data is loaded mode: "dimm" }, // treeInit: function(ctx){ // this._superApply(arguments); // }, nodeLoadChildren: function(ctx, source) { return this._superApply(arguments).done(function() { if( ctx.tree.enableFilter && ctx.tree.lastFilterArgs && ctx.options.filter.autoApply ) { ctx.tree._applyFilterImpl.apply(ctx.tree, ctx.tree.lastFilterArgs); } }); }, nodeSetExpanded: function(ctx, flag, callOpts) { delete ctx.node._filterAutoExpanded; return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { // Set classes for current status var res, node = ctx.node, tree = ctx.tree, $span = $(node[tree.statusClassPropName]); res = this._superApply(arguments); // nothing to do, if node was not yet rendered if( !$span.length || !tree.enableFilter ) { return res; } $span .toggleClass("fancytree-match", !!node.match) .toggleClass("fancytree-submatch", !!node.subMatch) .toggleClass("fancytree-hide", !(node.match || node.subMatch)); return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.glyph.js * * Use glyph fonts as instead of icon sprites. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _getIcon(opts, type){ return opts.map[type]; } $.ui.fancytree.registerExtension({ name: "glyph", version: "0.2.0", // Default options for this extension. options: { map: { checkbox: "icon-check-empty", checkboxSelected: "icon-check", checkboxUnknown: "icon-check icon-muted", error: "icon-exclamation-sign", expanderClosed: "icon-caret-right", expanderLazy: "icon-angle-right", expanderOpen: "icon-caret-down", doc: "icon-file-alt", noExpander: "", // Default node icons. // (Use tree.options.iconClass(node) callback to define custom icons // based on node data) docOpen: "icon-file-alt", loading: "icon-refresh icon-spin", folder: "icon-folder-close-alt", folderOpen: "icon-folder-open-alt" } }, treeInit: function(ctx){ var tree = ctx.tree; this._superApply(arguments); tree.$container.addClass("fancytree-ext-glyph"); }, nodeRenderStatus: function(ctx) { var icon, span, node = ctx.node, $span = $(node.span), opts = ctx.options.glyph, // callback = opts.icon, map = opts.map // $span = $(node.span) ; this._superApply(arguments); if( node.isRoot() ){ return; } span = $span.children("span.fancytree-expander").get(0); if( span ){ if( node.isLoading() ){ icon = "loading"; }else if( node.expanded ){ icon = "expanderOpen"; }else if( node.isUndefined() ){ icon = "expanderLazy"; }else if( node.hasChildren() ){ icon = "expanderClosed"; }else{ icon = "noExpander"; } span.className = "fancytree-expander " + map[icon]; } if( node.tr ){ span = $("td", node.tr).children("span.fancytree-checkbox").get(0); }else{ span = $span.children("span.fancytree-checkbox").get(0); } if( span ){ icon = node.selected ? "checkboxSelected" : (node.partsel ? "checkboxUnknown" : "checkbox"); span.className = "fancytree-checkbox " + map[icon]; } // Icon (note that this does not match .fancytree-custom-icon, that might // be set by opts.iconClass) span = $span.children("span.fancytree-icon").get(0); if( span ){ if( node.folder ){ icon = node.expanded ? _getIcon(opts, "folderOpen") : _getIcon(opts, "folder"); }else{ icon = node.expanded ? _getIcon(opts, "docOpen") : _getIcon(opts, "doc"); } span.className = "fancytree-icon " + icon; } }, nodeSetStatus: function(ctx, status, message, details) { var span, opts = ctx.options.glyph, node = ctx.node; this._superApply(arguments); if(node.parent){ span = $("span.fancytree-expander", node.span).get(0); }else{ span = $(".fancytree-statusnode-wait, .fancytree-statusnode-error", node[this.nodeContainerAttrName]) .find("span.fancytree-expander").get(0); } if( status === "loading"){ // $("span.fancytree-expander", ctx.node.span).addClass(_getIcon(opts, "loading")); span.className = "fancytree-expander " + _getIcon(opts, "loading"); }else if( status === "error"){ span.className = "fancytree-expander " + _getIcon(opts, "error"); } } }); }(jQuery, window, document)); /*! * jquery.fancytree.gridnav.js * * Support keyboard navigation for trees with embedded input controls. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Private functions and variables */ // Allow these navigation keys even when input controls are focused var KC = $.ui.keyCode, // which keys are *not* handled by embedded control, but passed to tree // navigation handler: NAV_KEYS = { "text": [KC.UP, KC.DOWN], "checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT], "select-one": [KC.LEFT, KC.RIGHT], "select-multiple": [KC.LEFT, KC.RIGHT] }; /* Calculate TD column index (considering colspans).*/ function getColIdx($tr, $td) { var colspan, td = $td.get(0), idx = 0; $tr.children().each(function () { if( this === td ) { return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return idx; } /* Find TD at given column index (considering colspans).*/ function findTdAtColIdx($tr, colIdx) { var colspan, res = null, idx = 0; $tr.children().each(function () { if( idx >= colIdx ) { res = $(this); return false; } colspan = $(this).prop("colspan"); idx += colspan ? colspan : 1; }); return res; } /* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */ function findNeighbourTd($target, keyCode){ var $tr, colIdx, $td = $target.closest("td"), $tdNext = null; switch( keyCode ){ case KC.LEFT: $tdNext = $td.prev(); break; case KC.RIGHT: $tdNext = $td.next(); break; case KC.UP: case KC.DOWN: $tr = $td.parent(); colIdx = getColIdx($tr, $td); while( true ) { $tr = (keyCode === KC.UP) ? $tr.prev() : $tr.next(); if( !$tr.length ) { break; } // Skip hidden rows if( $tr.is(":hidden") ) { continue; } // Find adjacent cell in the same column $tdNext = findTdAtColIdx($tr, colIdx); // Skip cells that don't conatain a focusable element if( $tdNext && $tdNext.find(":input").length ) { break; } } break; } return $tdNext; } /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "gridnav", version: "0.0.1", // Default options for this extension. options: { autofocusInput: false, // Focus first embedded input if node gets activated handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node }, treeInit: function(ctx){ // gridnav requires the table extension to be loaded before itself this._requireExtension("table", true, true); this._superApply(arguments); this.$container.addClass("fancytree-ext-gridnav"); // Activate node if embedded input gets focus (due to a click) this.$container.on("focusin", function(event){ var ctx2, node = $.ui.fancytree.getNode(event.target); if( node && !node.isActive() ){ // Call node.setActive(), but also pass the event ctx2 = ctx.tree._makeHookContext(node, event); ctx.tree._callHook("nodeSetActive", ctx2, true); } }); }, nodeSetActive: function(ctx, flag) { var $outer, opts = ctx.options.gridnav, node = ctx.node, event = ctx.originalEvent || {}, triggeredByInput = $(event.target).is(":input"); flag = (flag !== false); this._superApply(arguments); if( flag ){ if( ctx.options.titlesTabbable ){ if( !triggeredByInput ) { $(node.span).find("span.fancytree-title").focus(); node.setFocus(); } // If one node is tabbable, the container no longer needs to be ctx.tree.$container.attr("tabindex", "-1"); // ctx.tree.$container.removeAttr("tabindex"); } else if( opts.autofocusInput && !triggeredByInput ){ // Set focus to input sub input (if node was clicked, but not // when TAB was pressed ) $outer = $(node.tr || node.span); $outer.find(":input:enabled:first").focus(); } } }, nodeKeydown: function(ctx) { var inputType, handleKeys, $td, opts = ctx.options.gridnav, event = ctx.originalEvent, $target = $(event.target); // jQuery inputType = $target.is(":input:enabled") ? $target.prop("type") : null; // ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType); if( inputType && opts.handleCursorKeys ){ handleKeys = NAV_KEYS[inputType]; if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){ $td = findNeighbourTd($target, event.which); // ctx.node.debug("ignore keydown in input", event.which, handleKeys); if( $td && $td.length ) { $td.find(":input:enabled").focus(); // Prevent Fancytree default navigation return false; } } return true; } // ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType); return this._superApply(arguments); } }); }(jQuery, window, document)); /*! * jquery.fancytree.persist.js * * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @depends: js-cookie or jquery-cookie * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /* global Cookies:false */ /******************************************************************************* * Private functions and variables */ var cookieGetter, cookieRemover, cookieSetter, _assert = $.ui.fancytree.assert, ACTIVE = "active", EXPANDED = "expanded", FOCUS = "focus", SELECTED = "selected"; if( typeof Cookies === "function" ) { // Assume https://github.com/js-cookie/js-cookie cookieSetter = Cookies.set; cookieGetter = Cookies.get; cookieRemover = Cookies.remove; } else { // Fall back to https://github.com/carhartl/jquery-cookie cookieSetter = cookieGetter = $.cookie; cookieRemover = $.removeCookie; } /* Recursively load lazy nodes * @param {string} mode 'load', 'expand', false */ function _loadLazyNodes(tree, local, keyList, mode, dfd) { var i, key, l, node, foundOne = false, deferredList = [], missingKeyList = []; keyList = keyList || []; dfd = dfd || $.Deferred(); for( i=0, l=keyList.length; i<l; i++ ) { key = keyList[i]; node = tree.getNodeByKey(key); if( node ) { if( mode && node.isUndefined() ) { foundOne = true; tree.debug("_loadLazyNodes: " + node + " is lazy: loading..."); if( mode === "expand" ) { deferredList.push(node.setExpanded()); } else { deferredList.push(node.load()); } } else { tree.debug("_loadLazyNodes: " + node + " already loaded."); node.setExpanded(); } } else { missingKeyList.push(key); tree.debug("_loadLazyNodes: " + node + " was not yet found."); } } $.when.apply($, deferredList).always(function(){ // All lazy-expands have finished if( foundOne && missingKeyList.length > 0 ) { // If we read new nodes from server, try to resolve yet-missing keys _loadLazyNodes(tree, local, missingKeyList, mode, dfd); } else { if( missingKeyList.length ) { tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList); for( i=0, l=missingKeyList.length; i<l; i++ ) { key = keyList[i]; local._appendKey(EXPANDED, keyList[i], false); } } dfd.resolve(); } }); return dfd; } /** * [ext-persist] Remove persistence cookies of the given type(s). * Called like * $("#tree").fancytree("getTree").clearCookies("active expanded focus selected"); * * @alias Fancytree#clearCookies * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){ var local = this.ext.persist, prefix = local.cookiePrefix; types = types || "active expanded focus selected"; if(types.indexOf(ACTIVE) >= 0){ local._data(prefix + ACTIVE, null); } if(types.indexOf(EXPANDED) >= 0){ local._data(prefix + EXPANDED, null); } if(types.indexOf(FOCUS) >= 0){ local._data(prefix + FOCUS, null); } if(types.indexOf(SELECTED) >= 0){ local._data(prefix + SELECTED, null); } }; /** * [ext-persist] Return persistence information from cookies * * Called like * $("#tree").fancytree("getTree").getPersistData(); * * @alias Fancytree#getPersistData * @requires jquery.fancytree.persist.js */ $.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){ var local = this.ext.persist, prefix = local.cookiePrefix, delim = local.cookieDelimiter, res = {}; res[ACTIVE] = local._data(prefix + ACTIVE); res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim); res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim); res[FOCUS] = local._data(prefix + FOCUS); return res; }; /* ***************************************************************************** * Extension code */ $.ui.fancytree.registerExtension({ name: "persist", version: "0.3.0", // Default options for this extension. options: { cookieDelimiter: "~", cookiePrefix: undefined, // 'fancytree-<treeId>-' by default cookie: { raw: false, expires: "", path: "", domain: "", secure: false }, expandLazy: false, // true: recursively expand and load lazy nodes overrideSource: true, // true: cookie takes precedence over `source` data attributes. store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore types: "active expanded focus selected" }, /* Generic read/write string data to cookie, sessionStorage or localStorage. */ _data: function(key, value){ var ls = this._local.localStorage; // null, sessionStorage, or localStorage if( value === undefined ) { return ls ? ls.getItem(key) : cookieGetter(key); } else if ( value === null ) { if( ls ) { ls.removeItem(key); } else { cookieRemover(key); } } else { if( ls ) { ls.setItem(key, value); } else { cookieSetter(key, value, this.options.persist.cookie); } } }, /* Append `key` to a cookie. */ _appendKey: function(type, key, flag){ key = "" + key; // #90 var local = this._local, instOpts = this.options.persist, delim = instOpts.cookieDelimiter, cookieName = local.cookiePrefix + type, data = local._data(cookieName), keyList = data ? data.split(delim) : [], idx = $.inArray(key, keyList); // Remove, even if we add a key, so the key is always the last entry if(idx >= 0){ keyList.splice(idx, 1); } // Append key to cookie if(flag){ keyList.push(key); } local._data(cookieName, keyList.join(delim)); }, treeInit: function(ctx){ var tree = ctx.tree, opts = ctx.options, local = this._local, instOpts = this.options.persist; // For 'auto' or 'cookie' mode, the cookie plugin must be available _assert(instOpts.store === "localStore" || cookieGetter, "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js"); local.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-"); local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0; local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0; local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0; local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0; if( instOpts.store === "cookie" || !window.localStorage ) { local.localStorage = null; } else { local.localStorage = (instOpts.store === "local") ? window.localStorage : window.sessionStorage; } // Bind init-handler to apply cookie state tree.$div.bind("fancytreeinit", function(event){ var cookie, dfd, i, keyList, node, prevFocus = local._data(local.cookiePrefix + FOCUS); // record this before node.setActive() overrides it; // tree.debug("document.cookie:", document.cookie); cookie = local._data(local.cookiePrefix + EXPANDED); keyList = cookie && cookie.split(instOpts.cookieDelimiter); if( local.storeExpanded ) { // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load' // Also remove expand-cookies for unmatched nodes dfd = _loadLazyNodes(tree, local, keyList, instOpts.expandLazy ? "expand" : false , null); } else { // nothing to do dfd = new $.Deferred().resolve(); } dfd.done(function(){ if(local.storeSelected){ cookie = local._data(local.cookiePrefix + SELECTED); if(cookie){ keyList = cookie.split(instOpts.cookieDelimiter); for(i=0; i<keyList.length; i++){ node = tree.getNodeByKey(keyList[i]); if(node){ if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){ // node.setSelected(); node.selected = true; node.renderStatus(); } }else{ // node is no longer member of the tree: remove from cookie also local._appendKey(SELECTED, keyList[i], false); } } } // In selectMode 3 we have to fix the child nodes, since we // only stored the selected *top* nodes if( tree.options.selectMode === 3 ){ tree.visit(function(n){ if( n.selected ) { n.fixSelection3AfterClick(); return "skip"; } }); } } if(local.storeActive){ cookie = local._data(local.cookiePrefix + ACTIVE); if(cookie && (opts.persist.overrideSource || !tree.activeNode)){ node = tree.getNodeByKey(cookie); if(node){ node.debug("persist: set active", cookie); // We only want to set the focus if the container // had the keyboard focus before node.setActive(true, {noFocus: true}); } } } if(local.storeFocus && prevFocus){ node = tree.getNodeByKey(prevFocus); if(node){ // node.debug("persist: set focus", cookie); if( tree.options.titlesTabbable ) { $(node.span).find(".fancytree-title").focus(); } else { $(tree.$container).focus(); } // node.setFocus(); } } tree._triggerTreeEvent("restore", null, {}); }); }); // Init the tree return this._superApply(arguments); }, nodeSetActive: function(ctx, flag, opts) { var res, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeActive){ local._data(local.cookiePrefix + ACTIVE, this.activeNode ? this.activeNode.key : null); } return res; }, nodeSetExpanded: function(ctx, flag, opts) { var res, node = ctx.node, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeExpanded){ local._appendKey(EXPANDED, node.key, flag); } return res; }, nodeSetFocus: function(ctx, flag) { var res, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if( local.storeFocus ) { local._data(local.cookiePrefix + FOCUS, this.focusNode ? this.focusNode.key : null); } return res; }, nodeSetSelected: function(ctx, flag) { var res, selNodes, tree = ctx.tree, node = ctx.node, local = this._local; flag = (flag !== false); res = this._superApply(arguments); if(local.storeSelected){ if( tree.options.selectMode === 3 ){ // In selectMode 3 we only store the the selected *top* nodes. // De-selecting a node may also de-select some parents, so we // calculate the current status again selNodes = $.map(tree.getSelectedNodes(true), function(n){ return n.key; }); selNodes = selNodes.join(ctx.options.persist.cookieDelimiter); local._data(local.cookiePrefix + SELECTED, selNodes); } else { local._appendKey(SELECTED, node.key, flag); } } return res; } }); }(jQuery, window, document)); /*! * jquery.fancytree.table.js * * Render tree as table (aka 'treegrid', 'tabletree'). * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /* ***************************************************************************** * Private functions and variables */ function _assert(cond, msg){ msg = msg || ""; if(!cond){ $.error("Assertion failed " + msg); } } function insertSiblingAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } /* Show/hide all rows that are structural descendants of `parent`. */ function setChildRowVisibility(parent, flag) { parent.visit(function(node){ var tr = node.tr; // currentFlag = node.hide ? false : flag; // fix for ext-filter if(tr){ tr.style.display = (node.hide || !flag) ? "none" : ""; } if(!node.expanded){ return "skip"; } }); } /* Find node that is rendered in previous row. */ function findPrevRowNode(node){ var i, last, prev, parent = node.parent, siblings = parent ? parent.children : null; if(siblings && siblings.length > 1 && siblings[0] !== node){ // use the lowest descendant of the preceeding sibling i = $.inArray(node, siblings); prev = siblings[i - 1]; _assert(prev.tr); // descend to lowest child (with a <tr> tag) while(prev.children){ last = prev.children[prev.children.length - 1]; if(!last.tr){ break; } prev = last; } }else{ // if there is no preceding sibling, use the direct parent prev = parent; } return prev; } $.ui.fancytree.registerExtension({ name: "table", version: "0.2.1", // Default options for this extension. options: { checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx) customStatus: false, // true: generate renderColumns events for status nodes indentation: 16, // indent every node level by 16px nodeColumnIdx: 0 // render node expander, icon, and title to this column (default: #0) }, // Overide virtual methods for this extension. // `this` : is this extension object // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree) treeInit: function(ctx){ var i, $row, tdRole, tree = ctx.tree, $table = tree.widget.element; $table.addClass("fancytree-container fancytree-ext-table"); tree.tbody = $table.find("> tbody")[0]; tree.columnCount = $("thead >tr >th", $table).length; $(tree.tbody).empty(); tree.rowFragment = document.createDocumentFragment(); $row = $("<tr />"); tdRole = ""; if(ctx.options.aria){ $row.attr("role", "row"); tdRole = " role='gridcell'"; } for(i=0; i<tree.columnCount; i++) { if(ctx.options.table.nodeColumnIdx === i){ $row.append("<td" + tdRole + "><span class='fancytree-node' /></td>"); }else{ $row.append("<td" + tdRole + " />"); } } tree.rowFragment.appendChild($row.get(0)); // Make sure that status classes are set on the node's <tr> elements tree.statusClassPropName = "tr"; tree.ariaPropName = "tr"; this.nodeContainerAttrName = "tr"; this._superApply(arguments); // standard Fancytree created a root UL $(tree.rootNode.ul).remove(); tree.rootNode.ul = null; tree.$container = $table; // Add container to the TAB chain this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1"); if(this.options.aria){ tree.$container .attr("role", "treegrid") .attr("aria-readonly", true); } }, /* Called by nodeRender to sync node order with tag order.*/ // nodeFixOrder: function(ctx) { // }, nodeRemoveChildMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveChildMarkup()"); node.visit(function(n){ if(n.tr){ $(n.tr).remove(); n.tr = null; } }); }, nodeRemoveMarkup: function(ctx) { var node = ctx.node; // node.debug("nodeRemoveMarkup()"); if(node.tr){ $(node.tr).remove(); node.tr = null; } this.nodeRemoveChildMarkup(ctx); }, /* Override standard render. */ nodeRender: function(ctx, force, deep, collapsed, _recursive) { var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx, tree = ctx.tree, node = ctx.node, opts = ctx.options, isRootNode = !node.parent; if( !_recursive ){ ctx.hasCollapsedParents = node.parent && !node.parent.expanded; } // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr)); if( !isRootNode ){ if(!node.tr){ if( ctx.hasCollapsedParents /*&& !node.parent.tr*/ ) { // #166: we assume that the parent will be (recursively) rendered // later anyway. node.debug("nodeRender ignored due to unrendered parent"); return; } // Create new <tr> after previous row newRow = tree.rowFragment.firstChild.cloneNode(true); prevNode = findPrevRowNode(node); // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key); _assert(prevNode); if(collapsed === true && _recursive){ // hide all child rows, so we can use an animation to show it later newRow.style.display = "none"; }else if(deep && ctx.hasCollapsedParents){ // also hide this row if deep === true but any parent is collapsed newRow.style.display = "none"; // newRow.style.color = "red"; } if(!prevNode.tr){ _assert(!prevNode.parent, "prev. row must have a tr, or is system root"); tree.tbody.appendChild(newRow); }else{ insertSiblingAfter(prevNode.tr, newRow); } node.tr = newRow; if( node.key && opts.generateIds ){ node.tr.id = opts.idPrefix + node.key; } node.tr.ftnode = node; if(opts.aria){ // TODO: why doesn't this work: // node.li.role = "treeitem"; $(node.tr).attr("aria-labelledby", "ftal_" + node.key); } node.span = $("span.fancytree-node", node.tr).get(0); // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // Allow tweaking, binding, after node was created for the first time // tree._triggerNodeEvent("createNode", ctx); if ( opts.createNode ){ opts.createNode.call(tree, {type: "createNode"}, ctx); } } else { if( force ) { // Set icon, link, and title (normally this is only required on initial render) this.nodeRenderTitle(ctx); // triggers renderColumns() } else { // Update element classes according to node state this.nodeRenderStatus(ctx); } } } // Allow tweaking after node state was rendered // tree._triggerNodeEvent("renderNode", ctx); if ( opts.renderNode ){ opts.renderNode.call(tree, {type: "renderNode"}, ctx); } // Visit child nodes // Add child markup children = node.children; if(children && (isRootNode || deep || node.expanded)){ for(i=0, l=children.length; i<l; i++) { subCtx = $.extend({}, ctx, {node: children[i]}); subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded; this.nodeRender(subCtx, force, deep, collapsed, true); } } // Make sure, that <tr> order matches node.children order. if(children && !_recursive){ // we only have to do it once, for the root branch prevTr = node.tr || null; firstTr = tree.tbody.firstChild; // Iterate over all descendants node.visit(function(n){ if(n.tr){ if(!n.parent.expanded && n.tr.style.display !== "none"){ // fix after a node was dropped over a collapsed n.tr.style.display = "none"; setChildRowVisibility(n, false); } if(n.tr.previousSibling !== prevTr){ node.debug("_fixOrder: mismatch at node: " + n); var nextTr = prevTr ? prevTr.nextSibling : firstTr; tree.tbody.insertBefore(n.tr, nextTr); } prevTr = n.tr; } }); } // Update element classes according to node state // if(!isRootNode){ // this.nodeRenderStatus(ctx); // } }, nodeRenderTitle: function(ctx, title) { var $cb, node = ctx.node, opts = ctx.options; this._superApply(arguments); // Move checkbox to custom column if(opts.checkbox && opts.table.checkboxColumnIdx != null ){ $cb = $("span.fancytree-checkbox", node.span).detach(); $(node.tr).find("td").eq(+opts.table.checkboxColumnIdx).html($cb); } // Update element classes according to node state if( ! node.isRoot() ){ this.nodeRenderStatus(ctx); } if( !opts.table.customStatus && node.isStatusNode() ) { // default rendering for status node: leave other cells empty } else if ( opts.renderColumns ) { // Let user code write column content opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx); } }, nodeRenderStatus: function(ctx) { var indent, node = ctx.node, opts = ctx.options; this._superApply(arguments); $(node.tr).removeClass("fancytree-node"); // indent indent = (node.getLevel() - 1) * opts.table.indentation; $(node.span).css({marginLeft: indent + "px"}); }, /* Expand node, return Deferred.promise. */ nodeSetExpanded: function(ctx, flag, opts) { var dfd = new $.Deferred(), subOpts = $.extend({}, opts, {noEvents: true, noAnimation: true}); opts = opts || {}; function _afterExpand(ok) { flag = (flag !== false); setChildRowVisibility(ctx.node, flag); if( ok ) { if( flag && ctx.options.autoScroll && !opts.noAnimation && ctx.node.hasChildren() ) { // Scroll down to last child, but keep current node visible ctx.node.getLastChild().scrollIntoView(true, {topNode: ctx.node}).always(function(){ if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); }); } else { if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.resolveWith(ctx.node); } } else { if( !opts.noEvents ) { ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx); } dfd.rejectWith(ctx.node); } } // Call base-expand with disabled events and animation this._super(ctx, flag, subOpts).done(function () { _afterExpand(true); }).fail(function () { _afterExpand(false); }); return dfd.promise(); }, nodeSetStatus: function(ctx, status, message, details) { if(status === "ok"){ var node = ctx.node, firstChild = ( node.children ? node.children[0] : null ); if ( firstChild && firstChild.isStatusNode() ) { $(firstChild.tr).remove(); } } return this._superApply(arguments); }, treeClear: function(ctx) { this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode)); return this._superApply(arguments); }, treeDestroy: function(ctx) { this.$container.find("tbody").empty(); this.$source && this.$source.removeClass("ui-helper-hidden"); } /*, treeSetFocus: function(ctx, flag) { // alert("treeSetFocus" + ctx.tree.$container); ctx.tree.$container.focus(); $.ui.fancytree.focusTree = ctx.tree; }*/ }); }(jQuery, window, document)); /*! * jquery.fancytree.themeroller.js * * Enable jQuery UI ThemeRoller styles. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * @see http://jqueryui.com/themeroller/ * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "themeroller", version: "0.0.1", // Default options for this extension. options: { activeClass: "ui-state-active", foccusClass: "ui-state-focus", hoverClass: "ui-state-hover", selectedClass: "ui-state-highlight" }, treeInit: function(ctx){ this._superApply(arguments); var $el = ctx.widget.element; if($el[0].nodeName === "TABLE"){ $el.addClass("ui-widget ui-corner-all"); $el.find(">thead tr").addClass("ui-widget-header"); $el.find(">tbody").addClass("ui-widget-conent"); }else{ $el.addClass("ui-widget ui-widget-content ui-corner-all"); } $el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){ var node = $.ui.fancytree.getNode(event.target), flag = (event.type === "mouseenter"); node.debug("hover: " + flag); $(node.tr ? node.tr : node.span).toggleClass("ui-state-hover ui-corner-all", flag); }); }, treeDestroy: function(ctx){ this._superApply(arguments); ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all"); }, nodeRenderStatus: function(ctx){ var node = ctx.node, $el = $(node.tr ? node.tr : node.span); this._superApply(arguments); /* .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons. */ $el.toggleClass("ui-state-active", node.isActive()); $el.toggleClass("ui-state-focus", node.hasFocus()); $el.toggleClass("ui-state-highlight", node.isSelected()); } }); }(jQuery, window, document)); /*! * jquery.fancytree.wide.js * Support for 100% wide selection bars. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/) * * Copyright (c) 2008-2015, Martin Wendt (http://wwWendt.de) * * Released under the MIT license * https://github.com/mar10/fancytree/wiki/LicenseInfo * * @version 2.10.2 * @date 2015-07-02T08:11 */ ;(function($, window, document, undefined) { "use strict"; var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"] /******************************************************************************* * Private functions and variables */ // var _assert = $.ui.fancytree.assert; /* Calculate inner width without scrollbar */ // function realInnerWidth($el) { // // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/ // // inst.contWidth = parseFloat(this.$container.css("width"), 10); // // 'Client width without scrollbar' - 'padding' // return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10)); // } /* Create a global embedded CSS style for the tree. */ function defineHeadStyleElement(id, cssText) { id = "fancytree-style-" + id; var $headStyle = $("#" + id); if( !cssText ) { $headStyle.remove(); return null; } if( !$headStyle.length ) { $headStyle = $("<style />") .attr("id", id) .addClass("fancytree-style") .prop("type", "text/css") .appendTo("head"); } try { $headStyle.html(cssText); } catch ( e ) { // fix for IE 6-8 $headStyle[0].styleSheet.cssText = cssText; } return $headStyle; } /* Calculate the CSS rules that indent title spans. */ function renderLevelCss(containerId, depth, levelOfs, lineOfs, measureUnit) { var i, prefix = "#" + containerId + " span.fancytree-level-", rules = []; for(i = 0; i < depth; i++) { rules.push(prefix + (i + 1) + " span.fancytree-title { padding-left: " + (i * levelOfs + lineOfs) + measureUnit + "; }"); } // Some UI animations wrap the UL inside a DIV and set position:relative on both. // This breaks the left:0 and padding-left:nn settings of the title rules.push("#" + containerId + " div.ui-effects-wrapper ul li span.fancytree-title " + "{ padding-left: 3px; position: static; width: auto; }"); return rules.join("\n"); } // /** // * [ext-wide] Recalculate the width of the selection bar after the tree container // * was resized.<br> // * May be called explicitly on container resize, since there is no resize event // * for DIV tags. // * // * @alias Fancytree#wideUpdate // * @requires jquery.fancytree.wide.js // */ // $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){ // var inst = this.ext.wide, // prevCw = inst.contWidth, // prevLo = inst.lineOfs; // inst.contWidth = realInnerWidth(this.$container); // // Each title is precceeded by 2 or 3 icons (16px + 3 margin) // // + 1px title border and 3px title padding // // TODO: use code from treeInit() below // inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19; // if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) { // this.debug("wideUpdate: " + inst.contWidth); // this.visit(function(node){ // node.tree._callHook("nodeRenderTitle", node); // }); // } // }; /******************************************************************************* * Extension code */ $.ui.fancytree.registerExtension({ name: "wide", version: "0.0.3", // Default options for this extension. options: { iconWidth: null, // Adjust this if @fancy-icon-width != "16px" iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px" levelOfs: null // Adjust this if ul padding != "16px" }, treeCreate: function(ctx){ this._superApply(arguments); this.$container.addClass("fancytree-ext-wide"); var containerId, cssText, iconSpacingUnit, iconWidthUnit, levelOfsUnit, instOpts = ctx.options.wide, // css sniffing $dummyLI = $("<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />") .appendTo(ctx.tree.$container), $dummyIcon = $dummyLI.find(".fancytree-icon"), $dummyUL = $dummyLI.find("ul"), // $dummyTitle = $dummyLI.find(".fancytree-title"), iconSpacing = instOpts.iconSpacing || $dummyIcon.css("margin-left"), iconWidth = instOpts.iconWidth || $dummyIcon.css("width"), levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left"); $dummyLI.remove(); iconSpacingUnit = iconSpacing.match(reNumUnit)[2]; iconSpacing = parseFloat(iconSpacing, 10); iconWidthUnit = iconWidth.match(reNumUnit)[2]; iconWidth = parseFloat(iconWidth, 10); levelOfsUnit = levelOfs.match(reNumUnit)[2]; if( iconSpacingUnit !== iconWidthUnit || levelOfsUnit !== iconWidthUnit ) { $.error("iconWidth, iconSpacing, and levelOfs must have the same css measure unit"); } this._local.measureUnit = iconWidthUnit; this._local.levelOfs = parseFloat(levelOfs); this._local.lineOfs = (ctx.options.checkbox ? 3 : 2) * (iconWidth + iconSpacing) + iconSpacing; this._local.maxDepth = 10; // Get/Set a unique Id on the container (if not already exists) containerId = this.$container.uniqueId().attr("id"); // Generated css rules for some levels (extended on demand) cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); }, treeDestroy: function(ctx){ // Remove generated css rules defineHeadStyleElement(this.$container.attr("id"), null); return this._superApply(arguments); }, nodeRenderStatus: function(ctx) { var containerId, cssText, res, node = ctx.node, level = node.getLevel(); res = this._superApply(arguments); // Generate some more level-n rules if required if( level > this._local.maxDepth ) { containerId = this.$container.attr("id"); this._local.maxDepth *= 2; node.debug("Define global ext-wide css up to level " + this._local.maxDepth); cssText = renderLevelCss(containerId, this._local.maxDepth, this._local.levelOfs, this._local.lineOfs, this._local.measureUnit); defineHeadStyleElement(containerId, cssText); } // Add level-n class to apply indentation padding. // (Setting element style would not work, since it cannot easily be // overriden while animations run) $(node.span).addClass("fancytree-level-" + level); return res; } }); }(jQuery, window, document));
ajax/libs/react/0.4.1/react.min.js
BitsyCode/cdnjs
/** * React v0.4.1 * * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ !function(e){if("function"==typeof bootstrap)bootstrap("react",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeReact=e}else"undefined"!=typeof window?window.React=e():global.React=e()}(function(){return function(e,t,n){function r(n,i){if(!t[n]){if(!e[n]){var a="function"==typeof require&&require;if(!i&&a)return a(n,!0);if(o)return o(n,!0);throw new Error("Cannot find module '"+n+"'")}var s=t[n]={exports:{}};e[n][0].call(s.exports,function(t){var o=e[n][1][t];return r(o?o:t)},s,s.exports)}return t[n].exports}for(var o="function"==typeof require&&require,i=0;i<n.length;i++)r(n[i]);return r}({1:[function(e,t){function n(e){var t=r(e);if(!t)throw new Error(o('Tried to get element with id of "%s" but it is not present on the page.',e));return t}var r=e("./ge"),o=e("./ex");t.exports=n},{"./ex":68,"./ge":71}],2:[function(e,t){"use strict";var n={fillOpacity:!0,fontWeight:!0,opacity:!0,orphans:!0,zIndex:!0,zoom:!0},r={background:{backgroundImage:!0,backgroundPosition:!0,backgroundRepeat:!0,backgroundColor:!0},border:{borderWidth:!0,borderStyle:!0,borderColor:!0},borderBottom:{borderBottomWidth:!0,borderBottomStyle:!0,borderBottomColor:!0},borderLeft:{borderLeftWidth:!0,borderLeftStyle:!0,borderLeftColor:!0},borderRight:{borderRightWidth:!0,borderRightStyle:!0,borderRightColor:!0},borderTop:{borderTopWidth:!0,borderTopStyle:!0,borderTopColor:!0},font:{fontStyle:!0,fontVariant:!0,fontWeight:!0,fontSize:!0,lineHeight:!0,fontFamily:!0}},o={isUnitlessNumber:n,shorthandPropertyExpansions:r};t.exports=o},{}],3:[function(e,t){"use strict";var n=e("./CSSProperty"),r=e("./dangerousStyleValue"),o=e("./escapeTextForBrowser"),i=e("./hyphenate"),a=e("./memoizeStringOnly"),s=a(function(e){return o(i(e))}),u={createMarkupForStyles:function(e){var t="";for(var n in e)if(e.hasOwnProperty(n)){var o=e[n];null!=o&&(t+=s(n)+":",t+=r(n,o)+";")}return t||null},setValueForStyles:function(e,t){var o=e.style;for(var i in t)if(t.hasOwnProperty(i)){var a=r(i,t[i]);if(a)o[i]=a;else{var s=n.shorthandPropertyExpansions[i];if(s)for(var u in s)o[u]="";else o[i]=""}}}};t.exports=u},{"./CSSProperty":2,"./dangerousStyleValue":65,"./escapeTextForBrowser":67,"./hyphenate":76,"./memoizeStringOnly":83}],4:[function(e,t){"use strict";var n={},r={putListener:function(e,t,r){var o=n[t]||(n[t]={});o[e]=r},getListener:function(e,t){var r=n[t];return r&&r[e]},deleteListener:function(e,t){var r=n[t];r&&delete r[e]},deleteAllListeners:function(e){for(var t in n)delete n[t][e]},__purge:function(){n={}}};t.exports=r},{}],5:[function(e,t){!function(){"use strict";function n(e){return"SELECT"===e.nodeName||"INPUT"===e.nodeName&&"file"===e.type}function r(e){var t=M.getPooled(O.change,I,e);C.accumulateTwoPhaseDispatches(t),y.enqueueEvents(t),y.processEventQueue()}function o(e,t){P=e,I=t,P.attachEvent("onchange",r)}function i(){P&&(P.detachEvent("onchange",r),P=null,I=null)}function a(e,t,n){return e===b.topChange?n:void 0}function s(e,t,n){e===b.topFocus?(i(),o(t,n)):e===b.topBlur&&i()}function u(e){return"INPUT"===e.nodeName&&x[e.type]||"TEXTAREA"===e.nodeName}function l(e,t){P=e,I=t,T=e.value,N=Object.getOwnPropertyDescriptor(e.constructor.prototype,"value"),Object.defineProperty(P,"value",A),P.attachEvent("onpropertychange",p)}function c(){P&&(delete P.value,P.detachEvent("onpropertychange",p),P=null,I=null,T=null,N=null)}function p(e){if("value"===e.propertyName){var t=e.srcElement.value;t!==T&&(T=t,r(e))}}function d(e,t,n){return e===b.topInput?n:void 0}function h(e,t,n){e===b.topFocus?(c(),l(t,n)):e===b.topBlur&&c()}function f(e){return e!==b.topSelectionChange&&e!==b.topKeyUp&&e!==b.topKeyDown||!P||P.value===T?void 0:(T=P.value,I)}function v(e){return"INPUT"===e.nodeName&&("checkbox"===e.type||"radio"===e.type)}function m(e,t,n){return e===b.topClick?n:void 0}var g=e("./EventConstants"),y=e("./EventPluginHub"),C=e("./EventPropagators"),E=e("./ExecutionEnvironment"),M=e("./SyntheticEvent"),D=e("./isEventSupported"),R=e("./keyOf"),b=g.topLevelTypes,O={change:{phasedRegistrationNames:{bubbled:R({onChange:null}),captured:R({onChangeCapture:null})}}},P=null,I=null,T=null,N=null,S=!1;E.canUseDOM&&(S=D("change")&&(!("documentMode"in document)||document.documentMode>8));var _=!1;E.canUseDOM&&(_=D("input")&&(!("documentMode"in document)||document.documentMode>9));var x={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},A={get:function(){return N.get.call(this)},set:function(e){T=""+e,N.set.call(this,e)}},w={eventTypes:O,extractEvents:function(e,t,r,o){var i,l;if(n(t)?S?i=a:l=s:u(t)?_?i=d:(i=f,l=h):v(t)&&(i=m),i){var c=i(e,t,r);if(c){var p=M.getPooled(O.change,c,o);return C.accumulateTwoPhaseDispatches(p),p}}l&&l(e,t,r)}};t.exports=w}()},{"./EventConstants":13,"./EventPluginHub":15,"./EventPropagators":18,"./ExecutionEnvironment":19,"./SyntheticEvent":51,"./isEventSupported":79,"./keyOf":82}],6:[function(e,t){!function(){"use strict";var n=e("./Danger"),r=e("./insertNodeAt"),o=e("./keyOf");e("./throwIf");var i=o({moveFrom:null}),a=o({insertMarkup:null}),s=o({removeAt:null}),u=function(e,t){for(var n,r,o,a=0;a<t.length;a++)r=t[a],i in r?(n=n||[],o=r.moveFrom,n[o]=e.childNodes[o]):s in r&&(n=n||[],o=r.removeAt,n[o]=e.childNodes[o]);return n},l=function(e,t){for(var n=0;n<t.length;n++){var r=t[n];r&&e.removeChild(t[n])}},c=function(e,t,o){for(var u,l,c,p=0;p<t.length;p++)if(c=t[p],i in c)u=o[c.moveFrom],l=c.finalIndex,r(e,u,l);else if(s in c);else if(a in c){l=c.finalIndex;var d=c.insertMarkup;n.dangerouslyInsertMarkupAt(e,d,l)}},p=function(e,t){var n=u(e,t);n&&l(e,n),c(e,t,n)},d={dangerouslyReplaceNodeWithMarkup:n.dangerouslyReplaceNodeWithMarkup,manageChildren:p};t.exports=d}()},{"./Danger":9,"./insertNodeAt":77,"./keyOf":82,"./throwIf":89}],7:[function(e,t){"use strict";var n=e("./invariant"),r={MUST_USE_ATTRIBUTE:1,MUST_USE_PROPERTY:2,HAS_BOOLEAN_VALUE:4,HAS_SIDE_EFFECTS:8,injectDOMPropertyConfig:function(e){var t=e.Properties||{},o=e.DOMAttributeNames||{},a=e.DOMPropertyNames||{},s=e.DOMMutationMethods||{};e.isCustomAttribute&&i._isCustomAttributeFunctions.push(e.isCustomAttribute);for(var u in t){n(!i.isStandardName[u]),i.isStandardName[u]=!0,i.getAttributeName[u]=o[u]||u.toLowerCase(),i.getPropertyName[u]=a[u]||u;var l=s[u];l&&(i.getMutationMethod[u]=l);var c=t[u];i.mustUseAttribute[u]=c&r.MUST_USE_ATTRIBUTE,i.mustUseProperty[u]=c&r.MUST_USE_PROPERTY,i.hasBooleanValue[u]=c&r.HAS_BOOLEAN_VALUE,i.hasSideEffects[u]=c&r.HAS_SIDE_EFFECTS,n(!i.mustUseAttribute[u]||!i.mustUseProperty[u]),n(i.mustUseProperty[u]||!i.hasSideEffects[u])}}},o={},i={isStandardName:{},getAttributeName:{},getPropertyName:{},getMutationMethod:{},mustUseAttribute:{},mustUseProperty:{},hasBooleanValue:{},hasSideEffects:{},_isCustomAttributeFunctions:[],isCustomAttribute:function(e){return i._isCustomAttributeFunctions.some(function(t){return t.call(null,e)})},getDefaultValueForProperty:function(e,t){var n,r=o[e];return r||(o[e]=r={}),t in r||(n=document.createElement(e),r[t]=n[t]),r[t]},injection:r};t.exports=i},{"./invariant":78}],8:[function(e,t){"use strict";var n=e("./DOMProperty"),r=e("./escapeTextForBrowser"),o=e("./memoizeStringOnly"),i=o(function(e){return r(e)+'="'}),a={createMarkupForProperty:function(e,t){if(n.isStandardName[e]){if(null==t||n.hasBooleanValue[e]&&!t)return"";var o=n.getAttributeName[e];return i(o)+r(t)+'"'}return n.isCustomAttribute(e)?null==t?"":i(e)+r(t)+'"':null},setValueForProperty:function(e,t,r){if(n.isStandardName[t]){var o=n.getMutationMethod[t];if(o)o(e,r);else if(n.mustUseAttribute[t])n.hasBooleanValue[t]&&!r?e.removeAttribute(n.getAttributeName[t]):e.setAttribute(n.getAttributeName[t],r);else{var i=n.getPropertyName[t];n.hasSideEffects[t]&&e[i]===r||(e[i]=r)}}else n.isCustomAttribute(t)&&e.setAttribute(t,r)},deleteValueForProperty:function(e,t){if(n.isStandardName[t]){var r=n.getMutationMethod[t];if(r)r(e,void 0);else if(n.mustUseAttribute[t])e.removeAttribute(n.getAttributeName[t]);else{var o=n.getPropertyName[t];e[o]=n.getDefaultValueForProperty(e.nodeName,t)}}else n.isCustomAttribute(t)&&e.removeAttribute(t)}};t.exports=a},{"./DOMProperty":7,"./escapeTextForBrowser":67,"./memoizeStringOnly":83}],9:[function(e,t){"use strict";function n(e){var t=u,n=e.substring(1,e.indexOf(" ")),r=l[n.toLowerCase()]||c;if(r){t.innerHTML=r[1]+e+r[2];for(var o=r[0];o--;)t=t.lastChild}else t.innerHTML=e;return t.childNodes}function r(e,t,n){return n?n.nextSibling?e.insertBefore(t,n.nextSibling):e.appendChild(t):e.insertBefore(t,e.firstChild)}function o(e,t,n){for(var o,i=t.length,a=0;i>a;a++)o=r(e,t[0],o||n)}function i(e,t,r){var i=n(t),a=r?e.childNodes[r-1]:null;o(e,i,a)}function a(e,t){var r=e.parentNode,o=n(t);r.replaceChild(o[0],e)}var s=e("./ExecutionEnvironment");e("./throwIf");var u=s.canUseDOM?document.createElement("div"):null,l={option:[1,'<select multiple="true">',"</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>"]};l.optgroup=l.option,l.tbody=l.thead,l.tfoot=l.thead,l.colgroup=l.thead,l.caption=l.thead,l.th=l.td;var c=[1,"?<div>","</div>"];if(u){for(var p in l)l.hasOwnProperty(p)&&(u.innerHTML="<"+p+"></"+p+">",u.firstChild&&(l[p]=null));u.innerHTML="<link />",u.firstChild&&(c=null)}var d={dangerouslyInsertMarkupAt:i,dangerouslyReplaceNodeWithMarkup:a};t.exports=d},{"./ExecutionEnvironment":19,"./throwIf":89}],10:[function(e,t){"use strict";var n=e("./DOMProperty"),r=n.injection.MUST_USE_ATTRIBUTE,o=n.injection.MUST_USE_PROPERTY,i=n.injection.HAS_BOOLEAN_VALUE,a=n.injection.HAS_SIDE_EFFECTS,s={isCustomAttribute:RegExp.prototype.test.bind(/^(data|aria)-[a-z_][a-z\d_.\-]*$/),Properties:{accessKey:null,accept:null,action:null,ajaxify:r,allowFullScreen:r|i,allowTransparency:r,alt:null,autoComplete:null,autoFocus:i,autoPlay:i,cellPadding:null,cellSpacing:null,checked:o|i,className:o,colSpan:null,contentEditable:null,contextMenu:r,controls:o|i,data:null,dateTime:r,dir:null,disabled:o|i,draggable:null,encType:null,frameBorder:r,height:r,hidden:r|i,href:null,htmlFor:null,icon:null,id:o,label:null,lang:null,list:null,max:null,maxLength:r,method:null,min:null,multiple:o|i,name:null,pattern:null,poster:null,preload:null,placeholder:null,radioGroup:null,rel:null,readOnly:o|i,required:i,role:r,scrollLeft:o,scrollTop:o,selected:o|i,size:null,spellCheck:null,src:null,step:null,style:null,tabIndex:null,target:null,title:null,type:null,value:o|a,width:r,wmode:r,cx:o,cy:o,d:o,fill:o,fx:o,fy:o,points:o,r:o,stroke:o,strokeLinecap:o,strokeWidth:o,transform:o,x:o,x1:o,x2:o,version:o,viewBox:o,y:o,y1:o,y2:o,spreadMethod:o,offset:o,stopColor:o,stopOpacity:o,gradientUnits:o,gradientTransform:o},DOMAttributeNames:{className:"class",htmlFor:"for",strokeLinecap:"stroke-linecap",strokeWidth:"stroke-width",stopColor:"stop-color",stopOpacity:"stop-opacity"},DOMPropertyNames:{autoComplete:"autocomplete",autoFocus:"autofocus",autoPlay:"autoplay",encType:"enctype",radioGroup:"radiogroup",spellCheck:"spellcheck"},DOMMutationMethods:{className:function(e,t){e.className=t||""}}};t.exports=s},{"./DOMProperty":7}],11:[function(e,t){"use strict";var n=e("./keyOf"),r=[n({ResponderEventPlugin:null}),n({SimpleEventPlugin:null}),n({TapEventPlugin:null}),n({EnterLeaveEventPlugin:null}),n({ChangeEventPlugin:null}),n({AnalyticsEventPlugin:null}),n({MobileSafariClickEventPlugin:null})];t.exports=r},{"./keyOf":82}],12:[function(e,t){!function(){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),o=e("./ExecutionEnvironment"),i=e("./SyntheticMouseEvent"),a=e("./ReactMount"),s=e("./keyOf"),u=n.topLevelTypes,l=a.getFirstReactDOM,c={mouseEnter:{registrationName:s({onMouseEnter:null})},mouseLeave:{registrationName:s({onMouseLeave:null})}},p={eventTypes:c,extractEvents:function(e,t,n,s){if(e===u.topMouseOver&&(s.relatedTarget||s.fromElement))return null;if(e!==u.topMouseOut&&e!==u.topMouseOver)return null;var p,d;if(e===u.topMouseOut?(p=t,d=l(s.relatedTarget||s.toElement)||o.global):(p=o.global,d=t),p===d)return null;var h=p?a.getID(p):"",f=d?a.getID(d):"",v=i.getPooled(c.mouseLeave,h,s),m=i.getPooled(c.mouseEnter,f,s);return r.accumulateEnterLeaveDispatches(v,m,h,f),[v,m]}};t.exports=p}()},{"./EventConstants":13,"./EventPropagators":18,"./ExecutionEnvironment":19,"./ReactMount":39,"./SyntheticMouseEvent":54,"./keyOf":82}],13:[function(e,t){"use strict";var n=e("./keyMirror"),r=n({bubbled:null,captured:null}),o=n({topBlur:null,topChange:null,topClick:null,topDOMCharacterDataModified:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),i={topLevelTypes:o,PropagationPhases:r};t.exports=i},{"./keyMirror":81}],14:[function(e,t){var n={listen:function(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent&&e.attachEvent("on"+t,n)},capture:function(e,t,n){e.addEventListener&&e.addEventListener(t,n,!0)}};t.exports=n},{}],15:[function(e,t){"use strict";var n=e("./CallbackRegistry"),r=e("./EventPluginRegistry"),o=e("./EventPluginUtils"),i=e("./EventPropagators"),a=e("./ExecutionEnvironment"),s=e("./accumulate"),u=e("./forEachAccumulated"),l=e("./invariant"),c=null,p=function(e){if(e){var t=o.executeDispatch,n=r.getPluginModuleForEvent(e);n&&n.executeDispatch&&(t=n.executeDispatch),o.executeDispatchesInOrder(e,t),e.isPersistent()||e.constructor.release(e)}},d={injection:{injectInstanceHandle:i.injection.injectInstanceHandle,injectEventPluginOrder:r.injectEventPluginOrder,injectEventPluginsByName:r.injectEventPluginsByName},registrationNames:r.registrationNames,putListener:n.putListener,getListener:n.getListener,deleteListener:n.deleteListener,deleteAllListeners:n.deleteAllListeners,extractEvents:function(e,t,n,o){for(var i,a=r.plugins,u=0,l=a.length;l>u;u++){var c=a[u];if(c){var p=c.extractEvents(e,t,n,o);p&&(i=s(i,p))}}return i},enqueueEvents:function(e){e&&(c=s(c,e))},processEventQueue:function(){var e=c;c=null,u(e,p),l(!c)}};a.canUseDOM&&(window.EventPluginHub=d),t.exports=d},{"./CallbackRegistry":4,"./EventPluginRegistry":16,"./EventPluginUtils":17,"./EventPropagators":18,"./ExecutionEnvironment":19,"./accumulate":61,"./forEachAccumulated":70,"./invariant":78}],16:[function(e,t){"use strict";function n(){if(a)for(var e in s){var t=s[e],n=a.indexOf(e);if(i(n>-1),!u.plugins[n]){i(t.extractEvents),u.plugins[n]=t;var o=t.eventTypes;for(var l in o)i(r(o[l],t))}}}function r(e,t){var n=e.phasedRegistrationNames;if(n){for(var r in n)if(n.hasOwnProperty(r)){var i=n[r];o(i,t)}return!0}return e.registrationName?(o(e.registrationName,t),!0):!1}function o(e,t){i(!u.registrationNames[e]),u.registrationNames[e]=t,u.registrationNamesKeys.push(e)}var i=e("./invariant"),a=null,s={},u={plugins:[],registrationNames:{},registrationNamesKeys:[],injectEventPluginOrder:function(e){i(!a),a=Array.prototype.slice.call(e),n()},injectEventPluginsByName:function(e){var t=!1;for(var r in e)if(e.hasOwnProperty(r)){var o=e[r];s[r]!==o&&(i(!s[r]),s[r]=o,t=!0)}t&&n()},getPluginModuleForEvent:function(e){var t=e.dispatchConfig;if(t.registrationName)return u.registrationNames[t.registrationName]||null;for(var n in t.phasedRegistrationNames)if(t.phasedRegistrationNames.hasOwnProperty(n)){var r=u.registrationNames[t.phasedRegistrationNames[n]];if(r)return r}return null},_resetEventPlugins:function(){a=null;for(var e in s)s.hasOwnProperty(e)&&delete s[e];u.plugins.length=0;var t=u.registrationNames;for(var n in t)t.hasOwnProperty(n)&&delete t[n];u.registrationNamesKeys.length=0}};t.exports=u},{"./invariant":78}],17:[function(e,t){"use strict";function n(e){return e===h.topMouseUp||e===h.topTouchEnd||e===h.topTouchCancel}function r(e){return e===h.topMouseMove||e===h.topTouchMove}function o(e){return e===h.topMouseDown||e===h.topTouchStart}function i(e,t){var n=e._dispatchListeners,r=e._dispatchIDs;if(Array.isArray(n))for(var o=0;o<n.length&&!e.isPropagationStopped();o++)t(e,n[o],r[o]);else n&&t(e,n,r)}function a(e,t,n){t(e,n)}function s(e,t){i(e,t),e._dispatchListeners=null,e._dispatchIDs=null}function u(e){var t=e._dispatchListeners,n=e._dispatchIDs;if(Array.isArray(t)){for(var r=0;r<t.length&&!e.isPropagationStopped();r++)if(t[r](e,n[r]))return n[r]}else if(t&&t(e,n))return n;return null}function l(e){var t=e._dispatchListeners,n=e._dispatchIDs;d(!Array.isArray(t));var r=t?t(e,n):null;return e._dispatchListeners=null,e._dispatchIDs=null,r}function c(e){return!!e._dispatchListeners}var p=e("./EventConstants"),d=e("./invariant"),h=p.topLevelTypes,f={isEndish:n,isMoveish:r,isStartish:o,executeDispatchesInOrder:s,executeDispatchesInOrderStopAtTrue:u,executeDirectDispatch:l,hasDispatches:c,executeDispatch:a};t.exports=f},{"./EventConstants":13,"./invariant":78}],18:[function(e,t){"use strict";function n(e,t,n){var r=t.dispatchConfig.phasedRegistrationNames[n];return f(e,r)}function r(e,t,r){var o=t?v.bubbled:v.captured,i=n(e,r,o);i&&(r._dispatchListeners=d(r._dispatchListeners,i),r._dispatchIDs=d(r._dispatchIDs,e))}function o(e){e&&e.dispatchConfig.phasedRegistrationNames&&m.InstanceHandle.traverseTwoPhase(e.dispatchMarker,r,e)}function i(e,t,n){if(n&&n.dispatchConfig.registrationName){var r=n.dispatchConfig.registrationName,o=f(e,r);o&&(n._dispatchListeners=d(n._dispatchListeners,o),n._dispatchIDs=d(n._dispatchIDs,e))}}function a(e){e&&e.dispatchConfig.registrationName&&i(e.dispatchMarker,null,e)}function s(e){h(e,o)}function u(e,t,n,r){m.InstanceHandle.traverseEnterLeave(n,r,i,e,t)}function l(e){h(e,a)}var c=e("./CallbackRegistry"),p=e("./EventConstants"),d=e("./accumulate"),h=e("./forEachAccumulated"),f=c.getListener,v=p.PropagationPhases,m={InstanceHandle:null,injectInstanceHandle:function(e){m.InstanceHandle=e},validate:function(){var e=!m.InstanceHandle||!m.InstanceHandle.traverseTwoPhase||!m.InstanceHandle.traverseEnterLeave;if(e)throw new Error("InstanceHandle not injected before use!")}},g={accumulateTwoPhaseDispatches:s,accumulateDirectDispatches:l,accumulateEnterLeaveDispatches:u,injection:m};t.exports=g},{"./CallbackRegistry":4,"./EventConstants":13,"./accumulate":61,"./forEachAccumulated":70}],19:[function(e,t){!function(){"use strict";var e="undefined"!=typeof window,n={canUseDOM:e,canUseWorkers:"undefined"!=typeof Worker,isInWorker:!e,global:new Function("return this;")()};t.exports=n}()},{}],20:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./emptyFunction"),o=n.topLevelTypes,i={eventTypes:null,extractEvents:function(e,t,n,i){if(e===o.topTouchStart){var a=i.target;a&&!a.onclick&&(a.onclick=r)}}};t.exports=i},{"./EventConstants":13,"./emptyFunction":66}],21:[function(e,t){"use strict";var n=function(e){var t=this;if(t.instancePool.length){var n=t.instancePool.pop();return t.call(n,e),n}return new t(e)},r=function(e,t){var n=this;if(n.instancePool.length){var r=n.instancePool.pop();return n.call(r,e,t),r}return new n(e,t)},o=function(e,t,n){var r=this;if(r.instancePool.length){var o=r.instancePool.pop();return r.call(o,e,t,n),o}return new r(e,t,n)},i=function(e,t,n,r,o){var i=this;if(i.instancePool.length){var a=i.instancePool.pop();return i.call(a,e,t,n,r,o),a}return new i(e,t,n,r,o)},a=function(e){var t=this;e.destructor&&e.destructor(),t.instancePool.length<t.poolSize&&t.instancePool.push(e)},s=10,u=n,l=function(e,t){var n=e;return n.instancePool=[],n.getPooled=t||u,n.poolSize||(n.poolSize=s),n.release=a,n},c={addPoolingTo:l,oneArgumentPooler:n,twoArgumentPooler:r,threeArgumentPooler:o,fiveArgumentPooler:i};t.exports=c},{}],22:[function(e,t){"use strict";var n=e("./ReactCompositeComponent"),r=e("./ReactComponent"),o=e("./ReactDOM"),i=e("./ReactMount"),a=e("./ReactPropTypes"),s=e("./ReactServerRendering"),u=e("./ReactDefaultInjection");u.inject();var l={DOM:o,PropTypes:a,initializeTouchEvents:function(e){i.useTouchEvents=e},autoBind:n.autoBind,createClass:n.createClass,constructAndRenderComponent:i.constructAndRenderComponent,constructAndRenderComponentByID:i.constructAndRenderComponentByID,renderComponent:i.renderComponent,renderComponentToString:s.renderComponentToString,unmountAndReleaseReactRootNode:i.unmountAndReleaseReactRootNode,isValidComponent:r.isValidComponent};t.exports=l},{"./ReactComponent":23,"./ReactCompositeComponent":24,"./ReactDOM":26,"./ReactDefaultInjection":33,"./ReactMount":39,"./ReactPropTypes":45,"./ReactServerRendering":47}],23:[function(e,t){"use strict";var n=e("./getReactRootElementInContainer"),r=e("./ReactCurrentOwner"),o=e("./ReactDOMIDOperations"),i=e("./ReactMarkupChecksum"),a=e("./ReactMount"),s=e("./ReactOwner"),u=e("./ReactReconcileTransaction"),l=e("./ReactUpdates"),c=e("./invariant"),p=e("./keyMirror"),d=e("./merge"),h="{owner}",f=p({MOUNTED:null,UNMOUNTED:null}),v={isValidComponent:function(e){return!(!e||"function"!=typeof e.mountComponentIntoNode||"function"!=typeof e.receiveProps)},getKey:function(e,t){return e&&e.props&&null!=e.props.key?""+e.props.key:""+t},LifeCycle:f,DOMIDOperations:o,ReactReconcileTransaction:u,setDOMOperations:function(e){v.DOMIDOperations=e},setReactReconcileTransaction:function(e){v.ReactReconcileTransaction=e},Mixin:{isMounted:function(){return this._lifeCycleState===f.MOUNTED},getDOMNode:function(){return c(this.isMounted()),a.getNode(this._rootNodeID)},setProps:function(e,t){this.replaceProps(d(this._pendingProps||this.props,e),t)},replaceProps:function(e,t){c(!this.props[h]),this._pendingProps=e,l.enqueueUpdate(this,t)},construct:function(e,t){this.props=e||{},this.props[h]=r.current,this._lifeCycleState=f.UNMOUNTED,this._pendingProps=null,this._pendingCallbacks=null;var n=arguments.length-1;if(1===n)this.props.children=t;else if(n>1){for(var o=Array(n),i=0;n>i;i++)o[i]=arguments[i+1];this.props.children=o}},mountComponent:function(e){c(!this.isMounted());var t=this.props;null!=t.ref&&s.addComponentAsRefTo(this,t.ref,t[h]),this._rootNodeID=e,this._lifeCycleState=f.MOUNTED},unmountComponent:function(){c(this.isMounted());var e=this.props;null!=e.ref&&s.removeComponentAsRefFrom(this,e.ref,e[h]),a.purgeID(this._rootNodeID),this._rootNodeID=null,this._lifeCycleState=f.UNMOUNTED},receiveProps:function(e,t){c(this.isMounted()),this._pendingProps=e,this._performUpdateIfNecessary(t)},performUpdateIfNecessary:function(){var e=v.ReactReconcileTransaction.getPooled();e.perform(this._performUpdateIfNecessary,this,e),v.ReactReconcileTransaction.release(e)},_performUpdateIfNecessary:function(e){if(null!=this._pendingProps){var t=this.props;this.props=this._pendingProps,this._pendingProps=null,this.updateComponent(e,t)}},updateComponent:function(e,t){var n=this.props;(n[h]!==t[h]||n.ref!==t.ref)&&(null!=t.ref&&s.removeComponentAsRefFrom(this,t.ref,t[h]),null!=n.ref&&s.addComponentAsRefTo(this,n.ref,n[h]))},mountComponentIntoNode:function(e,t,n){var r=v.ReactReconcileTransaction.getPooled();r.perform(this._mountComponentIntoNode,this,e,t,r,n),v.ReactReconcileTransaction.release(r)},_mountComponentIntoNode:function(e,t,r,o){c(t&&1===t.nodeType);var a=this.mountComponent(e,r);if(!o||!i.canReuseMarkup(a,n(t))){var s=t.parentNode;if(s){var u=t.nextSibling;s.removeChild(t),t.innerHTML=a,u?s.insertBefore(t,u):s.appendChild(t)}else t.innerHTML=a}},unmountComponentFromNode:function(e){for(this.unmountComponent();e.lastChild;)e.removeChild(e.lastChild)},isOwnedBy:function(e){return this.props[h]===e},getSiblingByRef:function(e){var t=this.props[h];return t&&t.refs?t.refs[e]:null}}};t.exports=v},{"./ReactCurrentOwner":25,"./ReactDOMIDOperations":28,"./ReactMarkupChecksum":38,"./ReactMount":39,"./ReactOwner":43,"./ReactReconcileTransaction":46,"./ReactUpdates":49,"./getReactRootElementInContainer":73,"./invariant":78,"./keyMirror":81,"./merge":84}],24:[function(e,t){!function(){"use strict";function n(e,t){var n=m[t];C.hasOwnProperty(t)&&p(n===v.OVERRIDE_BASE),e.hasOwnProperty(t)&&p(n===v.DEFINE_MANY)}function r(e){var t=e._compositeLifeCycleState;p(e.isMounted()||t===y.MOUNTING),p(t!==y.RECEIVING_STATE&&t!==y.UNMOUNTING)}function o(e,t){var r=e.prototype;for(var o in t){var a=t[o];if(t.hasOwnProperty(o)&&a)if(n(r,o),g.hasOwnProperty(o))g[o](e,a);else{var s=o in m,u=o in r,l=a.__reactDontBind,c="function"==typeof a,p=c&&!s&&!u&&!l;p?(r.__reactAutoBindMap||(r.__reactAutoBindMap={}),r.__reactAutoBindMap[o]=a,r[o]=a):r[o]=u?i(r[o],a):a}}}function i(e,t){return function(){e.apply(this,arguments),t.apply(this,arguments)}}var a=e("./ReactComponent"),s=e("./ReactCurrentOwner"),u=e("./ReactOwner"),l=e("./ReactPropTransferer"),c=e("./ReactUpdates"),p=e("./invariant"),d=e("./keyMirror"),h=e("./merge"),f=e("./mixInto"),v=d({DEFINE_ONCE:null,DEFINE_MANY:null,OVERRIDE_BASE:null}),m={mixins:v.DEFINE_MANY,propTypes:v.DEFINE_ONCE,getDefaultProps:v.DEFINE_ONCE,getInitialState:v.DEFINE_ONCE,render:v.DEFINE_ONCE,componentWillMount:v.DEFINE_MANY,componentDidMount:v.DEFINE_MANY,componentWillReceiveProps:v.DEFINE_MANY,shouldComponentUpdate:v.DEFINE_ONCE,componentWillUpdate:v.DEFINE_MANY,componentDidUpdate:v.DEFINE_MANY,componentWillUnmount:v.DEFINE_MANY,updateComponent:v.OVERRIDE_BASE},g={displayName:function(e,t){e.displayName=t},mixins:function(e,t){if(t)for(var n=0;n<t.length;n++)o(e,t[n])},propTypes:function(e,t){e.propTypes=t}},y=d({MOUNTING:null,UNMOUNTING:null,RECEIVING_PROPS:null,RECEIVING_STATE:null}),C={construct:function(){a.Mixin.construct.apply(this,arguments),this.state=null,this._pendingState=null,this._compositeLifeCycleState=null},isMounted:function(){return a.Mixin.isMounted.call(this)&&this._compositeLifeCycleState!==y.MOUNTING},mountComponent:function(e,t){a.Mixin.mountComponent.call(this,e,t),this._compositeLifeCycleState=y.MOUNTING,this._defaultProps=this.getDefaultProps?this.getDefaultProps():null,this._processProps(this.props),this.__reactAutoBindMap&&this._bindAutoBindMethods(),this.state=this.getInitialState?this.getInitialState():null,this._pendingState=null,this._pendingForceUpdate=!1,this.componentWillMount&&(this.componentWillMount(),this._pendingState&&(this.state=this._pendingState,this._pendingState=null)),this._renderedComponent=this._renderValidatedComponent(),this._compositeLifeCycleState=null;var n=this._renderedComponent.mountComponent(e,t);return this.componentDidMount&&t.getReactOnDOMReady().enqueue(this,this.componentDidMount),n},unmountComponent:function(){this._compositeLifeCycleState=y.UNMOUNTING,this.componentWillUnmount&&this.componentWillUnmount(),this._compositeLifeCycleState=null,this._defaultProps=null,a.Mixin.unmountComponent.call(this),this._renderedComponent.unmountComponent(),this._renderedComponent=null,this.refs&&(this.refs=null)},setState:function(e,t){this.replaceState(h(this._pendingState||this.state,e),t)},replaceState:function(e,t){r(this),this._pendingState=e,c.enqueueUpdate(this,t)},_processProps:function(e){var t,n=this._defaultProps;for(t in n)t in e||(e[t]=n[t]);var r=this.constructor.propTypes;if(r){var o=this.constructor.displayName;for(t in r){var i=r[t];i&&i(e,t,o)}}},performUpdateIfNecessary:function(){var e=this._compositeLifeCycleState;e!==y.MOUNTING&&e!==y.RECEIVING_PROPS&&a.Mixin.performUpdateIfNecessary.call(this)},_performUpdateIfNecessary:function(e){if(null!=this._pendingProps||null!=this._pendingState||this._pendingForceUpdate){var t=this.props;null!=this._pendingProps&&(t=this._pendingProps,this._processProps(t),this._pendingProps=null,this._compositeLifeCycleState=y.RECEIVING_PROPS,this.componentWillReceiveProps&&this.componentWillReceiveProps(t,e)),this._compositeLifeCycleState=y.RECEIVING_STATE;var n=this._pendingState||this.state;this._pendingState=null,this._pendingForceUpdate||!this.shouldComponentUpdate||this.shouldComponentUpdate(t,n)?(this._pendingForceUpdate=!1,this._performComponentUpdate(t,n,e)):(this.props=t,this.state=n),this._compositeLifeCycleState=null}},_performComponentUpdate:function(e,t,n){var r=this.props,o=this.state;this.componentWillUpdate&&this.componentWillUpdate(e,t,n),this.props=e,this.state=t,this.updateComponent(n,r,o),this.componentDidUpdate&&n.getReactOnDOMReady().enqueue(this,this.componentDidUpdate.bind(this,r,o))},updateComponent:function(e,t){a.Mixin.updateComponent.call(this,e,t);var n=this._renderedComponent,r=this._renderValidatedComponent();if(n.constructor===r.constructor)n.receiveProps(r.props,e);else{var o=this._rootNodeID,i=n._rootNodeID;n.unmountComponent();var s=r.mountComponent(o,e);a.DOMIDOperations.dangerouslyReplaceNodeWithMarkupByID(i,s),this._renderedComponent=r}},forceUpdate:function(e){var t=this._compositeLifeCycleState;p(this.isMounted()||t===y.MOUNTING),p(t!==y.RECEIVING_STATE&&t!==y.UNMOUNTING),this._pendingForceUpdate=!0,c.enqueueUpdate(this,e)},_renderValidatedComponent:function(){var e;s.current=this;try{e=this.render()}catch(t){throw t}finally{s.current=null}return p(a.isValidComponent(e)),e},_bindAutoBindMethods:function(){for(var e in this.__reactAutoBindMap)if(this.__reactAutoBindMap.hasOwnProperty(e)){var t=this.__reactAutoBindMap[e];this[e]=this._bindAutoBindMethod(t)}},_bindAutoBindMethod:function(e){var t=this,n=function(){return e.apply(t,arguments)};return n}},E=function(){};f(E,a.Mixin),f(E,u.Mixin),f(E,l.Mixin),f(E,C);var M={LifeCycle:y,Base:E,createClass:function(e){var t=function(){};t.prototype=new E,t.prototype.constructor=t,o(t,e),p(t.prototype.render);for(var n in m)t.prototype[n]||(t.prototype[n]=null);var r=function(){var e=new t;return e.construct.apply(e,arguments),e};return r.componentConstructor=t,r.originalSpec=e,r},autoBind:function(e){return e}};t.exports=M}()},{"./ReactComponent":23,"./ReactCurrentOwner":25,"./ReactOwner":43,"./ReactPropTransferer":44,"./ReactUpdates":49,"./invariant":78,"./keyMirror":81,"./merge":84,"./mixInto":87}],25:[function(e,t){"use strict";var n={current:null};t.exports=n},{}],26:[function(e,t){"use strict";function n(e,t){var n=function(){};n.prototype=new r(e,t),n.prototype.constructor=n;var o=function(){var e=new n;return e.construct.apply(e,arguments),e};return o.componentConstructor=n,o}var r=e("./ReactNativeComponent"),o=e("./mergeInto"),i=e("./objMapKeyVal"),a=i({a:!1,abbr:!1,address:!1,area:!1,article:!1,aside:!1,audio:!1,b:!1,base:!1,bdi:!1,bdo:!1,big:!1,blockquote:!1,body:!1,br:!0,button:!1,canvas:!1,caption:!1,cite:!1,code:!1,col:!0,colgroup:!1,data:!1,datalist:!1,dd:!1,del:!1,details:!1,dfn:!1,div:!1,dl:!1,dt:!1,em:!1,embed:!0,fieldset:!1,figcaption:!1,figure:!1,footer:!1,form:!1,h1:!1,h2:!1,h3:!1,h4:!1,h5:!1,h6:!1,head:!1,header:!1,hr:!0,html:!1,i:!1,iframe:!1,img:!0,input:!0,ins:!1,kbd:!1,keygen:!0,label:!1,legend:!1,li:!1,link:!1,main:!1,map:!1,mark:!1,menu:!1,menuitem:!1,meta:!0,meter:!1,nav:!1,noscript:!1,object:!1,ol:!1,optgroup:!1,option:!1,output:!1,p:!1,param:!0,pre:!1,progress:!1,q:!1,rp:!1,rt:!1,ruby:!1,s:!1,samp:!1,script:!1,section:!1,select:!1,small:!1,source:!1,span:!1,strong:!1,style:!1,sub:!1,summary:!1,sup:!1,table:!1,tbody:!1,td:!1,textarea:!1,tfoot:!1,th:!1,thead:!1,time:!1,title:!1,tr:!1,track:!0,u:!1,ul:!1,"var":!1,video:!1,wbr:!1,circle:!1,g:!1,line:!1,path:!1,polyline:!1,rect:!1,svg:!1,text:!1},n),s={injectComponentClasses:function(e){o(a,e)}};a.injection=s,t.exports=a},{"./ReactNativeComponent":41,"./mergeInto":86,"./objMapKeyVal":88}],27:[function(e,t){"use strict";var n=e("./ReactCompositeComponent"),r=e("./ReactDOM"),o=e("./ReactEventEmitter"),i=e("./EventConstants"),a=r.form,s=n.createClass({render:function(){return this.transferPropsTo(a(null,this.props.children))},componentDidMount:function(e){o.trapBubbledEvent(i.topLevelTypes.topSubmit,"submit",e)}});t.exports=s},{"./EventConstants":13,"./ReactCompositeComponent":24,"./ReactDOM":26,"./ReactEventEmitter":34}],28:[function(e,t){!function(){"use strict"; var n=e("./CSSPropertyOperations"),r=e("./DOMChildrenOperations"),o=e("./DOMPropertyOperations"),i=e("./ReactMount"),a=e("./getTextContentAccessor"),s=e("./invariant"),u={dangerouslySetInnerHTML:"`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.",style:"`style` must be set using `updateStylesByID()`."},l=a()||"NA",c={updatePropertyByID:function(e,t,n){var r=i.getNode(e);s(!u.hasOwnProperty(t)),null!=n?o.setValueForProperty(r,t,n):o.deleteValueForProperty(r,t)},deletePropertyByID:function(e,t,n){var r=i.getNode(e);s(!u.hasOwnProperty(t)),o.deleteValueForProperty(r,t,n)},updatePropertiesByID:function(e,t){for(var n in t)t.hasOwnProperty(n)&&c.updatePropertiesByID(e,n,t[n])},updateStylesByID:function(e,t){var r=i.getNode(e);n.setValueForStyles(r,t)},updateInnerHTMLByID:function(e,t){var n=i.getNode(e);n.innerHTML=(t&&t.__html||"").replace(/^ /g,"&nbsp;")},updateTextContentByID:function(e,t){var n=i.getNode(e);n[l]=t},dangerouslyReplaceNodeWithMarkupByID:function(e,t){var n=i.getNode(e);r.dangerouslyReplaceNodeWithMarkup(n,t)},manageChildrenByParentID:function(e,t){var n=i.getNode(e);r.manageChildren(n,t)}};t.exports=c}()},{"./CSSPropertyOperations":3,"./DOMChildrenOperations":6,"./DOMPropertyOperations":8,"./ReactMount":39,"./getTextContentAccessor":74,"./invariant":78}],29:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactCompositeComponent"),o=e("./ReactDOM"),i=e("./merge"),a=o.input,s=r.createClass({getInitialState:function(){return{checked:this.props.defaultChecked||!1,value:this.props.defaultValue||""}},shouldComponentUpdate:function(){return!this._isChanging},getChecked:function(){return null!=this.props.checked?this.props.checked:this.state.checked},getValue:function(){return null!=this.props.value?""+this.props.value:this.state.value},render:function(){var e=i(this.props);return e.checked=this.getChecked(),e.value=this.getValue(),e.onChange=this.handleChange,a(e,this.props.children)},componentDidUpdate:function(e,t,r){null!=this.props.checked&&n.setValueForProperty(r,"checked",this.props.checked||!1),null!=this.props.value&&n.setValueForProperty(r,"value",""+this.props.value||"")},handleChange:function(e){var t;return this.props.onChange&&(this._isChanging=!0,t=this.props.onChange(e),this._isChanging=!1),this.setState({checked:e.target.checked,value:e.target.value}),t}});t.exports=s},{"./DOMPropertyOperations":8,"./ReactCompositeComponent":24,"./ReactDOM":26,"./merge":84}],30:[function(e,t){"use strict";var n=e("./ReactCompositeComponent"),r=e("./ReactDOM"),o=r.option,i=n.createClass({componentWillMount:function(){null!=this.props.selected},render:function(){return o(this.props,this.props.children)}});t.exports=i},{"./ReactCompositeComponent":24,"./ReactDOM":26}],31:[function(e,t){"use strict";function n(e,t){null!=e[t]&&(e.multiple?a(Array.isArray(e[t])):a(!Array.isArray(e[t])))}function r(){if(null!=this.props.value)for(var e=this.getDOMNode().options,t=""+this.props.value,n=0,r=e.length;r>n;n++){var o=this.props.multiple?t.indexOf(e[n].value)>=0:o=e[n].value===t;o!==e[n].selected&&(e[n].selected=o)}}var o=e("./ReactCompositeComponent"),i=e("./ReactDOM"),a=e("./invariant"),s=e("./merge"),u=i.select,l=o.createClass({propTypes:{defaultValue:n,value:n},getInitialState:function(){return{value:this.props.defaultValue||(this.props.multiple?[]:"")}},componentWillReceiveProps:function(e){!this.props.multiple&&e.multiple?this.setState({value:[this.state.value]}):this.props.multiple&&!e.multiple&&this.setState({value:this.state.value[0]})},shouldComponentUpdate:function(){return!this._isChanging},render:function(){var e=s(this.props);return e.onChange=this.handleChange,e.value=null,u(e,this.props.children)},componentDidMount:r,componentDidUpdate:r,handleChange:function(e){var t;this.props.onChange&&(this._isChanging=!0,t=this.props.onChange(e),this._isChanging=!1);var n;if(this.props.multiple){n=[];for(var r=e.target.options,o=0,i=r.length;i>o;o++)r[o].selected&&n.push(r[o].value)}else n=e.target.value;return this.setState({value:n}),t}});t.exports=l},{"./ReactCompositeComponent":24,"./ReactDOM":26,"./invariant":78,"./merge":84}],32:[function(e,t){"use strict";var n=e("./DOMPropertyOperations"),r=e("./ReactCompositeComponent"),o=e("./ReactDOM"),i=e("./invariant"),a=e("./merge"),s=o.textarea,u={string:!0,number:!0},l=r.createClass({getInitialState:function(){var e=this.props.defaultValue,t=this.props.children;return null!=t&&(i(null==e),Array.isArray(t)&&(i(t.length<=1),t=t[0]),i(u[typeof t]),e=""+t),e=e||"",{initialValue:null!=this.props.value?this.props.value:e,value:e}},shouldComponentUpdate:function(){return!this._isChanging},getValue:function(){return null!=this.props.value?this.props.value:this.state.value},render:function(){var e=a(this.props);return i(null==e.dangerouslySetInnerHTML),e.value=this.getValue(),e.onChange=this.handleChange,s(e,this.state.initialValue)},componentDidUpdate:function(e,t,r){null!=this.props.value&&n.setValueForProperty(r,"value",this.props.value||"")},handleChange:function(e){var t;return this.props.onChange&&(this._isChanging=!0,t=this.props.onChange(e),this._isChanging=!1),this.setState({value:e.target.value}),t}});t.exports=l},{"./DOMPropertyOperations":8,"./ReactCompositeComponent":24,"./ReactDOM":26,"./invariant":78,"./merge":84}],33:[function(e,t){"use strict";function n(){l.TopLevelCallbackCreator=c,m.injection.injectEventPluginOrder(h),m.injection.injectInstanceHandle(g),m.injection.injectEventPluginsByName({SimpleEventPlugin:y,EnterLeaveEventPlugin:f,ChangeEventPlugin:v,MobileSafariClickEventPlugin:C}),r.injection.injectComponentClasses({form:o,input:i,option:a,select:s,textarea:u}),d.injection.injectDOMPropertyConfig(p)}var r=e("./ReactDOM"),o=e("./ReactDOMForm"),i=e("./ReactDOMInput"),a=e("./ReactDOMOption"),s=e("./ReactDOMSelect"),u=e("./ReactDOMTextarea"),l=e("./ReactEventEmitter"),c=e("./ReactEventTopLevelCallback"),p=e("./DefaultDOMPropertyConfig"),d=e("./DOMProperty"),h=e("./DefaultEventPluginOrder"),f=e("./EnterLeaveEventPlugin"),v=e("./ChangeEventPlugin"),m=e("./EventPluginHub"),g=e("./ReactInstanceHandles"),y=e("./SimpleEventPlugin"),C=e("./MobileSafariClickEventPlugin");t.exports={inject:n}},{"./ChangeEventPlugin":5,"./DOMProperty":7,"./DefaultDOMPropertyConfig":10,"./DefaultEventPluginOrder":11,"./EnterLeaveEventPlugin":12,"./EventPluginHub":15,"./MobileSafariClickEventPlugin":20,"./ReactDOM":26,"./ReactDOMForm":27,"./ReactDOMInput":29,"./ReactDOMOption":30,"./ReactDOMSelect":31,"./ReactDOMTextarea":32,"./ReactEventEmitter":34,"./ReactEventTopLevelCallback":35,"./ReactInstanceHandles":37,"./SimpleEventPlugin":50}],34:[function(e,t){!function(){"use strict";function n(e,t,n){s.listen(n,t,v.TopLevelCallbackCreator.createTopLevelCallback(e))}function r(e,t,n){s.capture(n,t,v.TopLevelCallbackCreator.createTopLevelCallback(e))}function o(){var e=p.refreshScrollValues;s.listen(window,"scroll",e),s.listen(window,"resize",e)}function i(e){d(!f);var t=a.topLevelTypes,i=document;o(),n(t.topMouseOver,"mouseover",i),n(t.topMouseDown,"mousedown",i),n(t.topMouseUp,"mouseup",i),n(t.topMouseMove,"mousemove",i),n(t.topMouseOut,"mouseout",i),n(t.topClick,"click",i),n(t.topDoubleClick,"dblclick",i),e&&(n(t.topTouchStart,"touchstart",i),n(t.topTouchEnd,"touchend",i),n(t.topTouchMove,"touchmove",i),n(t.topTouchCancel,"touchcancel",i)),n(t.topKeyUp,"keyup",i),n(t.topKeyPress,"keypress",i),n(t.topKeyDown,"keydown",i),n(t.topInput,"input",i),n(t.topChange,"change",i),n(t.topSelectionChange,"selectionchange",i),n(t.topDOMCharacterDataModified,"DOMCharacterDataModified",i),h("drag")&&(n(t.topDrag,"drag",i),n(t.topDragEnd,"dragend",i),n(t.topDragEnter,"dragenter",i),n(t.topDragExit,"dragexit",i),n(t.topDragLeave,"dragleave",i),n(t.topDragOver,"dragover",i),n(t.topDragStart,"dragstart",i),n(t.topDrop,"drop",i)),h("wheel")?n(t.topWheel,"wheel",i):h("mousewheel")?n(t.topWheel,"mousewheel",i):n(t.topWheel,"DOMMouseScroll",i),h("scroll",!0)?r(t.topScroll,"scroll",i):n(t.topScroll,"scroll",window),h("focus",!0)?(r(t.topFocus,"focus",i),r(t.topBlur,"blur",i)):h("focusin")&&(n(t.topFocus,"focusin",i),n(t.topBlur,"focusout",i))}var a=e("./EventConstants"),s=e("./EventListener"),u=e("./EventPluginHub"),l=e("./ExecutionEnvironment"),c=e("./ReactUpdates"),p=e("./ViewportMetrics"),d=e("./invariant"),h=e("./isEventSupported"),f=!1,v={TopLevelCallbackCreator:null,ensureListening:function(e){d(l.canUseDOM),d(v.TopLevelCallbackCreator),f||(i(e),f=!0)},setEnabled:function(e){d(l.canUseDOM),v.TopLevelCallbackCreator&&v.TopLevelCallbackCreator.setEnabled(e)},isEnabled:function(){return!(!v.TopLevelCallbackCreator||!v.TopLevelCallbackCreator.isEnabled())},handleTopLevel:function(e,t,n,r){var o=u.extractEvents(e,t,n,r);c.batchedUpdates(function(){u.enqueueEvents(o),u.processEventQueue()})},registrationNames:u.registrationNames,putListener:u.putListener,getListener:u.getListener,deleteListener:u.deleteListener,deleteAllListeners:u.deleteAllListeners,trapBubbledEvent:n,trapCapturedEvent:r};t.exports=v}()},{"./EventConstants":13,"./EventListener":14,"./EventPluginHub":15,"./ExecutionEnvironment":19,"./ReactUpdates":49,"./ViewportMetrics":60,"./invariant":78,"./isEventSupported":79}],35:[function(e,t){!function(){"use strict";var n=e("./ExecutionEnvironment"),r=e("./ReactEventEmitter"),o=e("./ReactMount"),i=e("./getEventTarget"),a=!0,s={setEnabled:function(e){a=!!e},isEnabled:function(){return a},createTopLevelCallback:function(e){return function(t){if(a){t.srcElement&&t.srcElement!==t.target&&(t.target=t.srcElement);var s=o.getFirstReactDOM(i(t))||n.global,u=o.getID(s)||"";r.handleTopLevel(e,s,u,t)}}}};t.exports=s}()},{"./ExecutionEnvironment":19,"./ReactEventEmitter":34,"./ReactMount":39,"./getEventTarget":72}],36:[function(e,t){"use strict";function n(){try{return document.activeElement}catch(e){}}function r(e){return document.documentElement.contains(e)}var o={hasSelectionCapabilities:function(e){return e&&("INPUT"===e.nodeName&&"text"===e.type||"TEXTAREA"===e.nodeName||"true"===e.contentEditable)},getSelectionInformation:function(){var e=n();return{focusedElem:e,selectionRange:o.hasSelectionCapabilities(e)?o.getSelection(e):null}},restoreSelection:function(e){var t=n(),i=e.focusedElem,a=e.selectionRange;t!==i&&r(i)&&(o.hasSelectionCapabilities(i)&&o.setSelection(i,a),i.focus())},getSelection:function(e){var t;if("true"===e.contentEditable&&window.getSelection){t=window.getSelection().getRangeAt(0);var n=t.commonAncestorContainer;return n&&3===n.nodeType&&(n=n.parentNode),n!==e?{start:0,end:0}:{start:t.startOffset,end:t.endOffset}}if(!document.selection)return{start:e.selectionStart,end:e.selectionEnd};if(t=document.selection.createRange(),t.parentElement()!==e)return{start:0,end:0};var r=e.value.length;if("INPUT"===e.nodeName)return{start:-t.moveStart("character",-r),end:-t.moveEnd("character",-r)};var o=t.duplicate();o.moveToElementText(e),o.setEndPoint("StartToEnd",t);var i=r-o.text.length;return o.setEndPoint("StartToStart",t),{start:r-o.text.length,end:i}},setSelection:function(e,t){var n,r=t.start,o=t.end;if("undefined"==typeof o&&(o=r),document.selection){if("TEXTAREA"===e.tagName){var i=(e.value.slice(0,r).match(/\r/g)||[]).length,a=(e.value.slice(r,o).match(/\r/g)||[]).length;r-=i,o-=i+a}n=e.createTextRange(),n.collapse(!0),n.moveStart("character",r),n.moveEnd("character",o-r),n.select()}else if("true"===e.contentEditable){if(1===e.childNodes.length){n=document.createRange(),n.setStart(e.childNodes[0],r),n.setEnd(e.childNodes[0],o);var s=window.getSelection();s.removeAllRanges(),s.addRange(n)}}else e.selectionStart=r,e.selectionEnd=Math.min(o,e.value.length),e.focus()}};t.exports=o},{}],37:[function(e,t){"use strict";function n(e){return p+"r["+e.toString(36)+"]"}function r(e,t){return e.charAt(t)===p||t===e.length}function o(e){return""===e||e.charAt(0)===p&&e.charAt(e.length-1)!==p}function i(e,t){return 0===t.indexOf(e)&&r(t,e.length)}function a(e){return e?e.substr(0,e.lastIndexOf(p)):""}function s(e,t){if(c(o(e)&&o(t)),c(i(e,t)),e===t)return e;for(var n=e.length+d,a=n;a<t.length&&!r(t,a);a++);return t.substr(0,a)}function u(e,t){var n=Math.min(e.length,t.length);if(0===n)return"";for(var i=0,a=0;n>=a;a++)if(r(e,a)&&r(t,a))i=a;else if(e.charAt(a)!==t.charAt(a))break;var s=e.substr(0,i);return c(o(s)),s}function l(e,t,n,r,o,u){e=e||"",t=t||"",c(e!==t);var l=i(t,e);c(l||i(e,t));for(var p=0,d=l?a:s,f=e;o&&f===e||u&&f===t||n(f,l,r),f!==t;f=d(f,t))c(p++<h)}var c=e("./invariant"),p=".",d=p.length,h=100,f=9999999,v={separator:p,createReactRootID:function(){return n(Math.ceil(Math.random()*f))},getReactRootIDFromNodeID:function(e){var t=/\.r\[[^\]]+\]/.exec(e);return t&&t[0]},traverseEnterLeave:function(e,t,n,r,o){var i=u(e,t);i!==e&&l(e,i,n,r,!1,!0),i!==t&&l(i,t,n,o,!0,!1)},traverseTwoPhase:function(e,t,n){e&&(l("",e,t,n,!0,!1),l(e,"",t,n,!1,!0))},_getFirstCommonAncestorID:u,_getNextDescendantID:s,isAncestorIDOf:i,SEPARATOR:p};t.exports=v},{"./invariant":78}],38:[function(e,t){"use strict";var n=e("./adler32"),r={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(e){var t=n(e);return e.replace(">"," "+r.CHECKSUM_ATTR_NAME+'="'+t+'">')},canReuseMarkup:function(e,t){var o=t.getAttribute(r.CHECKSUM_ATTR_NAME);o=o&&parseInt(o,10);var i=n(e);return i===o}};t.exports=r},{"./adler32":62}],39:[function(e,t){!function(){"use strict";function n(e){var t=p(e);return t&&E.getID(t)}function r(e){var t=o(e);if(t)if(m.hasOwnProperty(t)){var n=m[t];n!==e&&(c(!s(n,t)),m[t]=e)}else m[t]=e;return t}function o(e){return e&&e.getAttribute&&e.getAttribute(v)||""}function i(e,t){var n=o(e);n!==t&&delete m[n],e.setAttribute(v,t),m[t]=e}function a(e){return m.hasOwnProperty(e)&&s(m[e],e)||(m[e]=E.findReactNodeByID(e)),m[e]}function s(e,t){if(e){c(o(e)===t);var n=E.findReactContainerForID(t);if(n&&u(n,e))return!0}return!1}function u(e,t){if(e.contains)return e.contains(t);if(t===e)return!0;for(3===t.nodeType&&(t=t.parentNode);t&&1===t.nodeType;){if(t===e)return!0;t=t.parentNode}return!1}function l(e){delete m[e]}var c=e("./invariant"),p=e("./getReactRootElementInContainer"),d=e("./ReactEventEmitter"),h=e("./ReactInstanceHandles"),f=h.SEPARATOR,v="data-reactid",m={},g=e("./$"),y={},C={},E={totalInstantiationTime:0,totalInjectionTime:0,useTouchEvents:!1,scrollMonitor:function(e,t){t()},prepareTopLevelEvents:function(){d.ensureListening(E.useTouchEvents)},_updateRootComponent:function(e,t,n,r){var o=t.props;return E.scrollMonitor(n,function(){e.replaceProps(o,r)}),e},_registerComponent:function(e,t){E.prepareTopLevelEvents();var n=E.registerContainer(t);return y[n]=e,n},_renderNewRootComponent:function(e,t,n){var r=E._registerComponent(e,t);return e.mountComponentIntoNode(r,t,n),e},renderComponent:function(e,t,r){var o=y[n(t)];if(o){if(o.constructor===e.constructor)return E._updateRootComponent(o,e,t,r);E.unmountAndReleaseReactRootNode(t)}var i=p(t),a=i&&E.isRenderedByReact(i),s=a&&!o,u=E._renderNewRootComponent(e,t,s);return r&&r(),u},constructAndRenderComponent:function(e,t,n){return E.renderComponent(e(t),n)},constructAndRenderComponentByID:function(e,t,n){return E.constructAndRenderComponent(e,t,g(n))},registerContainer:function(e){var t=n(e);return t&&(t=h.getReactRootIDFromNodeID(t)),t||(t=h.createReactRootID()),C[t]=e,t},unmountAndReleaseReactRootNode:function(e){var t=n(e),r=y[t];return r?(r.unmountComponentFromNode(e),delete y[t],delete C[t],!0):!1},findReactContainerForID:function(e){var t=h.getReactRootIDFromNodeID(e),n=C[t];return n},findReactNodeByID:function(e){var t=E.findReactContainerForID(e);return E.findComponentRoot(t,e)},isRenderedByReact:function(e){if(1!==e.nodeType)return!1;var t=E.getID(e);return t?t.charAt(0)===f:!1},getFirstReactDOM:function(e){for(var t=e;t&&t.parentNode!==t;){if(E.isRenderedByReact(t))return t;t=t.parentNode}return null},findComponentRoot:function(e,t){for(var n=[e.firstChild],r=0;r<n.length;)for(var o=n[r++];o;){var i=E.getID(o);if(i){if(t===i)return o;if(h.isAncestorIDOf(i,t)){n.length=r=0,n.push(o.firstChild);break}n.push(o.firstChild)}else n.push(o.firstChild);o=o.nextSibling}c(!1)},ATTR_NAME:v,getID:r,setID:i,getNode:a,purgeID:l,injection:{}};t.exports=E}()},{"./$":1,"./ReactEventEmitter":34,"./ReactInstanceHandles":37,"./getReactRootElementInContainer":73,"./invariant":78}],40:[function(e,t){!function(){"use strict";function n(e,t){return e&&t&&e.constructor===t.constructor}var r=e("./ReactComponent"),o={enqueueMarkupAt:function(e,t){this.domOperations=this.domOperations||[],this.domOperations.push({insertMarkup:e,finalIndex:t})},enqueueMove:function(e,t){this.domOperations=this.domOperations||[],this.domOperations.push({moveFrom:e,finalIndex:t})},enqueueUnmountChildByName:function(e,t){r.isValidComponent(t)&&(this.domOperations=this.domOperations||[],this.domOperations.push({removeAt:t._domIndex}),t.unmountComponent&&t.unmountComponent(),delete this._renderedChildren[e])},processChildDOMOperationsQueue:function(){this.domOperations&&(r.DOMIDOperations.manageChildrenByParentID(this._rootNodeID,this.domOperations),this.domOperations=null)},unmountMultiChild:function(){var e=this._renderedChildren;for(var t in e)if(e.hasOwnProperty(t)&&e[t]){var n=e[t];n.unmountComponent&&n.unmountComponent()}this._renderedChildren=null},mountMultiChild:function(e,t){var n="",r=0;for(var o in e){var i=e[o];e.hasOwnProperty(o)&&i&&(n+=i.mountComponent(this._rootNodeID+"."+o,t),i._domIndex=r,r++)}return this._renderedChildren=e,this.domOperations=null,n},updateMultiChild:function(e,t){if(e||this._renderedChildren){e&&!this._renderedChildren?this._renderedChildren={}:!e&&this._renderedChildren&&(e={});var r=this._rootNodeID+".",o=null,i=0,a=0,s=0;for(var u in e)if(e.hasOwnProperty(u)){var l=this._renderedChildren[u],c=e[u];if(n(l,c))o&&(this.enqueueMarkupAt(o,a-i),o=null),i=0,l._domIndex<s&&this.enqueueMove(l._domIndex,a),s=Math.max(l._domIndex,s),l.receiveProps(c.props,t),l._domIndex=a;else if(l&&(this.enqueueUnmountChildByName(u,l),s=Math.max(l._domIndex,s)),c){this._renderedChildren[u]=c;var p=c.mountComponent(r+u,t);o=o?o+p:p,i++,c._domIndex=a}a=c?a+1:a}o&&this.enqueueMarkupAt(o,a-i);for(var d in this._renderedChildren)if(this._renderedChildren.hasOwnProperty(d)){var h=this._renderedChildren[d];h&&!e[d]&&this.enqueueUnmountChildByName(d,h)}this.processChildDOMOperationsQueue()}}},i={Mixin:o};t.exports=i}()},{"./ReactComponent":23}],41:[function(e,t){"use strict";function n(e){e&&(h(null==e.children||null==e.dangerouslySetInnerHTML),h(null==e.style||"object"==typeof e.style))}function r(e,t){this._tagOpen="<"+e,this._tagClose=t?"":"</"+e+">",this.tagName=e.toUpperCase()}var o=e("./CSSPropertyOperations"),i=e("./DOMProperty"),a=e("./DOMPropertyOperations"),s=e("./ReactComponent"),u=e("./ReactEventEmitter"),l=e("./ReactMultiChild"),c=e("./ReactMount"),p=e("./escapeTextForBrowser"),d=e("./flattenChildren"),h=e("./invariant"),f=e("./keyOf"),v=e("./merge"),m=e("./mixInto"),g=u.putListener,y=u.deleteListener,C=u.registrationNames,E={string:!0,number:!0},M=f({dangerouslySetInnerHTML:null}),D=f({style:null});r.Mixin={mountComponent:function(e,t){return s.Mixin.mountComponent.call(this,e,t),n(this.props),this._createOpenTagMarkup()+this._createContentMarkup(t)+this._tagClose},_createOpenTagMarkup:function(){var e=this.props,t=this._tagOpen;for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];if(null!=r)if(C[n])g(this._rootNodeID,n,r);else{n===D&&(r&&(r=e.style=v(e.style)),r=o.createMarkupForStyles(r));var i=a.createMarkupForProperty(n,r);i&&(t+=" "+i)}}var s=p(this._rootNodeID);return t+" "+c.ATTR_NAME+'="'+s+'">'},_createContentMarkup:function(e){var t=this.props.dangerouslySetInnerHTML;if(null!=t){if(null!=t.__html)return t.__html}else{var n=E[typeof this.props.children]?this.props.children:null,r=null!=n?null:this.props.children;if(null!=n)return p(n);if(null!=r)return this.mountMultiChild(d(r),e)}return""},receiveProps:function(e,t){n(e),s.Mixin.receiveProps.call(this,e,t)},updateComponent:function(e,t){s.Mixin.updateComponent.call(this,e,t),this._updateDOMProperties(t),this._updateDOMChildren(t,e)},_updateDOMProperties:function(e){var t,n,r,o=this.props;for(t in e)if(!o.hasOwnProperty(t)&&e.hasOwnProperty(t))if(t===D){var a=e[t];for(n in a)a.hasOwnProperty(n)&&(r=r||{},r[n]="")}else t===M?s.DOMIDOperations.updateTextContentByID(this._rootNodeID,""):C[t]?y(this._rootNodeID,t):s.DOMIDOperations.deletePropertyByID(this._rootNodeID,t);for(t in o){var u=o[t],l=e[t];if(o.hasOwnProperty(t)&&u!==l)if(t===D)if(u&&(u=o.style=v(u)),l){for(n in l)l.hasOwnProperty(n)&&!u.hasOwnProperty(n)&&(r=r||{},r[n]="");for(n in u)u.hasOwnProperty(n)&&l[n]!==u[n]&&(r=r||{},r[n]=u[n])}else r=u;else if(t===M){var c=l&&l.__html,p=u&&u.__html;c!==p&&s.DOMIDOperations.updateInnerHTMLByID(this._rootNodeID,u)}else C[t]?g(this._rootNodeID,t,u):(i.isStandardName[t]||i.isCustomAttribute(t))&&s.DOMIDOperations.updatePropertyByID(this._rootNodeID,t,u)}r&&s.DOMIDOperations.updateStylesByID(this._rootNodeID,r)},_updateDOMChildren:function(e,t){var n=this.props,r=E[typeof e.children]?e.children:null,o=E[typeof n.children]?n.children:null,i=null!=r?null:e.children,a=null!=o?null:n.children;if(null!=o){var u=null!=i&&null==a;u&&this.updateMultiChild(null,t),r!==o&&s.DOMIDOperations.updateTextContentByID(this._rootNodeID,""+o)}else{var l=null!=r&&null==o;l&&s.DOMIDOperations.updateTextContentByID(this._rootNodeID,""),this.updateMultiChild(d(n.children),t)}},unmountComponent:function(){u.deleteAllListeners(this._rootNodeID),s.Mixin.unmountComponent.call(this),this.unmountMultiChild()}},m(r,s.Mixin),m(r,r.Mixin),m(r,l.Mixin),t.exports=r},{"./CSSPropertyOperations":3,"./DOMProperty":7,"./DOMPropertyOperations":8,"./ReactComponent":23,"./ReactEventEmitter":34,"./ReactMount":39,"./ReactMultiChild":40,"./escapeTextForBrowser":67,"./flattenChildren":69,"./invariant":78,"./keyOf":82,"./merge":84,"./mixInto":87}],42:[function(e,t){"use strict";function n(e){this._queue=e||null}var r=e("./PooledClass"),o=e("./mixInto");o(n,{enqueue:function(e,t){this._queue=this._queue||[],this._queue.push({component:e,callback:t})},notifyAll:function(){var e=this._queue;if(e){this._queue=null;for(var t=0,n=e.length;n>t;t++){var r=e[t].component,o=e[t].callback;o.call(r,r.getDOMNode())}e.length=0}},reset:function(){this._queue=null},destructor:function(){this.reset()}}),r.addPoolingTo(n),t.exports=n},{"./PooledClass":21,"./mixInto":87}],43:[function(e,t){"use strict";var n=e("./invariant"),r={isValidOwner:function(e){return!(!e||"function"!=typeof e.attachRef||"function"!=typeof e.detachRef)},addComponentAsRefTo:function(e,t,o){n(r.isValidOwner(o)),o.attachRef(t,e)},removeComponentAsRefFrom:function(e,t,o){n(r.isValidOwner(o)),o.refs[t]===e&&o.detachRef(t)},Mixin:{attachRef:function(e,t){n(t.isOwnedBy(this));var r=this.refs||(this.refs={});r[e]=t},detachRef:function(e){delete this.refs[e]}}};t.exports=r},{"./invariant":78}],44:[function(e,t){"use strict";function n(e){return function(t,n,r){t[n]=t.hasOwnProperty(n)?e(t[n],r):r}}var r=e("./emptyFunction"),o=e("./joinClasses"),i=e("./merge"),a={children:r,className:n(o),ref:r,style:n(i)},s={TransferStrategies:a,Mixin:{transferPropsTo:function(e){var t={};for(var n in e.props)e.props.hasOwnProperty(n)&&(t[n]=e.props[n]);for(var r in this.props)if(this.props.hasOwnProperty(r)){var o=a[r];o?o(t,r,this.props[r]):t.hasOwnProperty(r)||(t[r]=this.props[r])}return e.props=t,e}}};t.exports=s},{"./emptyFunction":66,"./joinClasses":80,"./merge":84}],45:[function(e,t){"use strict";function n(e){function t(t){var n=typeof t;"object"===n&&Array.isArray(t)&&(n="array"),s(n===e)}return i(t)}function r(e){function t(e){s(n[e])}var n=a(e);return i(t)}function o(e){function t(t){s(t instanceof e)}return i(t)}function i(e){function t(n){function r(t,r,o){var i=t[r];null!=i?e(i,r,o||l):s(!n)}return n||(r.isRequired=t(!0)),r}return t(!1)}var a=e("./createObjectFrom"),s=e("./invariant"),u={array:n("array"),bool:n("boolean"),func:n("function"),number:n("number"),object:n("object"),string:n("string"),oneOf:r,instanceOf:o},l="<<anonymous>>";t.exports=u},{"./createObjectFrom":64,"./invariant":78}],46:[function(e,t){"use strict";function n(){this.reinitializeTransaction(),this.reactOnDOMReady=s.getPooled(null)}var r=e("./ExecutionEnvironment"),o=e("./PooledClass"),i=e("./ReactEventEmitter"),a=e("./ReactInputSelection"),s=e("./ReactOnDOMReady"),u=e("./Transaction"),l=e("./mixInto"),c={initialize:a.getSelectionInformation,close:a.restoreSelection},p={initialize:function(){var e=i.isEnabled();return i.setEnabled(!1),e},close:function(e){i.setEnabled(e)}},d={initialize:function(){this.reactOnDOMReady.reset()},close:function(){this.reactOnDOMReady.notifyAll()}},h=[c,p,d],f={getTransactionWrappers:function(){return r.canUseDOM?h:[]},getReactOnDOMReady:function(){return this.reactOnDOMReady},destructor:function(){s.release(this.reactOnDOMReady),this.reactOnDOMReady=null}};l(n,u.Mixin),l(n,f),o.addPoolingTo(n),t.exports=n},{"./ExecutionEnvironment":19,"./PooledClass":21,"./ReactEventEmitter":34,"./ReactInputSelection":36,"./ReactOnDOMReady":42,"./Transaction":59,"./mixInto":87}],47:[function(e,t){"use strict";function n(e,t){var n=i.createReactRootID(),a=o.getPooled();a.reinitializeTransaction();try{a.perform(function(){var o=e.mountComponent(n,a);o=r.addChecksumToMarkup(o),t(o)},null)}finally{o.release(a)}}var r=e("./ReactMarkupChecksum"),o=e("./ReactReconcileTransaction"),i=e("./ReactInstanceHandles");t.exports={renderComponentToString:n}},{"./ReactInstanceHandles":37,"./ReactMarkupChecksum":38,"./ReactReconcileTransaction":46}],48:[function(e,t){"use strict";var n=e("./ReactComponent"),r=e("./ReactMount"),o=e("./escapeTextForBrowser"),i=e("./mixInto"),a=function(e){this.construct({text:e})};i(a,n.Mixin),i(a,{mountComponent:function(e){return n.Mixin.mountComponent.call(this,e),"<span "+r.ATTR_NAME+'="'+e+'">'+o(this.props.text)+"</span>"},receiveProps:function(e){e.text!==this.props.text&&(this.props.text=e.text,n.DOMIDOperations.updateTextContentByID(this._rootNodeID,e.text))}}),t.exports=a},{"./ReactComponent":23,"./ReactMount":39,"./escapeTextForBrowser":67,"./mixInto":87}],49:[function(e,t){"use strict";function n(e){if(i)return e(),void 0;i=!0;try{e();for(var t=0;t<a.length;t++){var n=a[t];if(n.isMounted()){var r=n._pendingCallbacks;if(n._pendingCallbacks=null,n.performUpdateIfNecessary(),r)for(var o=0;o<r.length;o++)r[o].call(n)}}}catch(s){throw s}finally{a.length=0,i=!1}}function r(e,t){return o(!t||"function"==typeof t),i?(a.push(e),t&&(e._pendingCallbacks?e._pendingCallbacks.push(t):e._pendingCallbacks=[t]),void 0):(e.performUpdateIfNecessary(),t&&t(),void 0)}var o=e("./invariant"),i=!1,a=[],s={batchedUpdates:n,enqueueUpdate:r};t.exports=s},{"./invariant":78}],50:[function(e,t){"use strict";var n=e("./EventConstants"),r=e("./EventPropagators"),o=e("./SyntheticEvent"),i=e("./SyntheticFocusEvent"),a=e("./SyntheticKeyboardEvent"),s=e("./SyntheticMouseEvent"),u=e("./SyntheticMutationEvent"),l=e("./SyntheticTouchEvent"),c=e("./SyntheticUIEvent"),p=e("./SyntheticWheelEvent"),d=e("./invariant"),h=e("./keyOf"),f=n.topLevelTypes,v={blur:{phasedRegistrationNames:{bubbled:h({onBlur:!0}),captured:h({onBlurCapture:!0})}},click:{phasedRegistrationNames:{bubbled:h({onClick:!0}),captured:h({onClickCapture:!0})}},doubleClick:{phasedRegistrationNames:{bubbled:h({onDoubleClick:!0}),captured:h({onDoubleClickCapture:!0})}},drag:{phasedRegistrationNames:{bubbled:h({onDrag:!0}),captured:h({onDragCapture:!0})}},dragEnd:{phasedRegistrationNames:{bubbled:h({onDragEnd:!0}),captured:h({onDragEndCapture:!0})}},dragEnter:{phasedRegistrationNames:{bubbled:h({onDragEnter:!0}),captured:h({onDragEnterCapture:!0})}},dragExit:{phasedRegistrationNames:{bubbled:h({onDragExit:!0}),captured:h({onDragExitCapture:!0})}},dragLeave:{phasedRegistrationNames:{bubbled:h({onDragLeave:!0}),captured:h({onDragLeaveCapture:!0})}},dragOver:{phasedRegistrationNames:{bubbled:h({onDragOver:!0}),captured:h({onDragOverCapture:!0})}},dragStart:{phasedRegistrationNames:{bubbled:h({onDragStart:!0}),captured:h({onDragStartCapture:!0})}},drop:{phasedRegistrationNames:{bubbled:h({onDrop:!0}),captured:h({onDropCapture:!0})}},DOMCharacterDataModified:{phasedRegistrationNames:{bubbled:h({onDOMCharacterDataModified:!0}),captured:h({onDOMCharacterDataModifiedCapture:!0})}},focus:{phasedRegistrationNames:{bubbled:h({onFocus:!0}),captured:h({onFocusCapture:!0})}},input:{phasedRegistrationNames:{bubbled:h({onInput:!0}),captured:h({onInputCapture:!0})}},keyDown:{phasedRegistrationNames:{bubbled:h({onKeyDown:!0}),captured:h({onKeyDownCapture:!0})}},keyPress:{phasedRegistrationNames:{bubbled:h({onKeyPress:!0}),captured:h({onKeyPressCapture:!0})}},keyUp:{phasedRegistrationNames:{bubbled:h({onKeyUp:!0}),captured:h({onKeyUpCapture:!0})}},mouseDown:{phasedRegistrationNames:{bubbled:h({onMouseDown:!0}),captured:h({onMouseDownCapture:!0})}},mouseMove:{phasedRegistrationNames:{bubbled:h({onMouseMove:!0}),captured:h({onMouseMoveCapture:!0})}},mouseUp:{phasedRegistrationNames:{bubbled:h({onMouseUp:!0}),captured:h({onMouseUpCapture:!0})}},scroll:{phasedRegistrationNames:{bubbled:h({onScroll:!0}),captured:h({onScrollCapture:!0})}},submit:{phasedRegistrationNames:{bubbled:h({onSubmit:!0}),captured:h({onSubmitCapture:!0})}},touchCancel:{phasedRegistrationNames:{bubbled:h({onTouchCancel:!0}),captured:h({onTouchCancelCapture:!0})}},touchEnd:{phasedRegistrationNames:{bubbled:h({onTouchEnd:!0}),captured:h({onTouchEndCapture:!0})}},touchMove:{phasedRegistrationNames:{bubbled:h({onTouchMove:!0}),captured:h({onTouchMoveCapture:!0})}},touchStart:{phasedRegistrationNames:{bubbled:h({onTouchStart:!0}),captured:h({onTouchStartCapture:!0})}},wheel:{phasedRegistrationNames:{bubbled:h({onWheel:!0}),captured:h({onWheelCapture:!0})}}},m={topBlur:v.blur,topClick:v.click,topDoubleClick:v.doubleClick,topDOMCharacterDataModified:v.DOMCharacterDataModified,topDrag:v.drag,topDragEnd:v.dragEnd,topDragEnter:v.dragEnter,topDragExit:v.dragExit,topDragLeave:v.dragLeave,topDragOver:v.dragOver,topDragStart:v.dragStart,topDrop:v.drop,topFocus:v.focus,topInput:v.input,topKeyDown:v.keyDown,topKeyPress:v.keyPress,topKeyUp:v.keyUp,topMouseDown:v.mouseDown,topMouseMove:v.mouseMove,topMouseUp:v.mouseUp,topScroll:v.scroll,topSubmit:v.submit,topTouchCancel:v.touchCancel,topTouchEnd:v.touchEnd,topTouchMove:v.touchMove,topTouchStart:v.touchStart,topWheel:v.wheel},g={eventTypes:v,executeDispatch:function(e,t,n){var r=t(e,n);r===!1&&(e.stopPropagation(),e.preventDefault())},extractEvents:function(e,t,n,h){var v=m[e];if(!v)return null;var g;switch(e){case f.topInput:case f.topSubmit:g=o;break;case f.topKeyDown:case f.topKeyPress:case f.topKeyUp:g=a;break;case f.topBlur:case f.topFocus:g=i;break;case f.topClick:case f.topDoubleClick:case f.topDrag:case f.topDragEnd:case f.topDragEnter:case f.topDragExit:case f.topDragLeave:case f.topDragOver:case f.topDragStart:case f.topDrop:case f.topMouseDown:case f.topMouseMove:case f.topMouseUp:g=s;break;case f.topDOMCharacterDataModified:g=u;break;case f.topTouchCancel:case f.topTouchEnd:case f.topTouchMove:case f.topTouchStart:g=l;break;case f.topScroll:g=c;break;case f.topWheel:g=p}d(g);var y=g.getPooled(v,n,h);return r.accumulateTwoPhaseDispatches(y),y}};t.exports=g},{"./EventConstants":13,"./EventPropagators":18,"./SyntheticEvent":51,"./SyntheticFocusEvent":52,"./SyntheticKeyboardEvent":53,"./SyntheticMouseEvent":54,"./SyntheticMutationEvent":55,"./SyntheticTouchEvent":56,"./SyntheticUIEvent":57,"./SyntheticWheelEvent":58,"./invariant":78,"./keyOf":82}],51:[function(e,t){"use strict";function n(e,t,n){this.dispatchConfig=e,this.dispatchMarker=t,this.nativeEvent=n;var r=this.constructor.Interface;for(var i in r)if(r.hasOwnProperty(i)){var a=r[i];this[i]=a?a(n):n[i]}this.isDefaultPrevented=n.defaultPrevented||n.returnValue===!1?o.thatReturnsTrue:o.thatReturnsFalse,this.isPropagationStopped=o.thatReturnsFalse}var r=e("./PooledClass"),o=e("./emptyFunction"),i=e("./getEventTarget"),a=e("./merge"),s=e("./mergeInto"),u={type:null,target:i,currentTarget:null,eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now() },defaultPrevented:null,isTrusted:null};s(n.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e.preventDefault?e.preventDefault():e.returnValue=!1,this.isDefaultPrevented=o.thatReturnsTrue},stopPropagation:function(){var e=this.nativeEvent;e.stopPropagation?e.stopPropagation():e.cancelBubble=!0,this.isPropagationStopped=o.thatReturnsTrue},persist:function(){this.isPersistent=o.thatReturnsTrue},isPersistent:o.thatReturnsFalse,destructor:function(){var e=this.constructor.Interface;for(var t in e)this[t]=null;this.dispatchConfig=null,this.dispatchMarker=null,this.nativeEvent=null}}),n.Interface=u,n.augmentClass=function(e,t){var n=this,o=Object.create(n.prototype);s(o,e.prototype),e.prototype=o,e.prototype.constructor=e,e.Interface=a(n.Interface,t),e.augmentClass=n.augmentClass,r.addPoolingTo(e,r.threeArgumentPooler)},r.addPoolingTo(n,r.threeArgumentPooler),t.exports=n},{"./PooledClass":21,"./emptyFunction":66,"./getEventTarget":72,"./merge":84,"./mergeInto":86}],52:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={relatedTarget:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":57}],53:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={"char":null,key:null,location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,charCode:null,keyCode:null,which:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":57}],54:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o=e("./ViewportMetrics"),i={screenX:null,screenY:null,clientX:null,clientY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,button:function(e){var t=e.button;return"which"in e?t:2===t?2:4===t?1:0},buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},pageX:function(e){return"pageX"in e?e.pageX:e.clientX+o.currentScrollLeft},pageY:function(e){return"pageY"in e?e.pageY:e.clientY+o.currentScrollTop}};r.augmentClass(n,i),t.exports=n},{"./SyntheticUIEvent":57,"./ViewportMetrics":60}],55:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={relatedNode:null,prevValue:null,newValue:null,attrName:null,attrChange:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":51}],56:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticUIEvent"),o={touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticUIEvent":57}],57:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticEvent"),o={view:null,detail:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticEvent":51}],58:[function(e,t){"use strict";function n(e,t,n){r.call(this,e,t,n)}var r=e("./SyntheticMouseEvent"),o={deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?-e.deltaY:"wheelDeltaY"in e?e.wheelDeltaY:"wheelDelta"in e?e.wheelData:0},deltaZ:null,deltaMode:null};r.augmentClass(n,o),t.exports=n},{"./SyntheticMouseEvent":54}],59:[function(e,t){!function(){"use strict";var n=e("./invariant"),r={reinitializeTransaction:function(){this.transactionWrappers=this.getTransactionWrappers(),this.wrapperInitData?this.wrapperInitData.length=0:this.wrapperInitData=[],this.timingMetrics||(this.timingMetrics={}),this.timingMetrics.methodInvocationTime=0,this.timingMetrics.wrapperInitTimes?this.timingMetrics.wrapperInitTimes.length=0:this.timingMetrics.wrapperInitTimes=[],this.timingMetrics.wrapperCloseTimes?this.timingMetrics.wrapperCloseTimes.length=0:this.timingMetrics.wrapperCloseTimes=[],this._isInTransaction=!1},_isInTransaction:!1,getTransactionWrappers:null,isInTransaction:function(){return!!this._isInTransaction},perform:function(e,t,r,o,i,a,s,u){n(!this.isInTransaction());var l,c=Date.now(),p=null;try{this.initializeAll(),l=e.call(t,r,o,i,a,s,u)}catch(d){p=d}finally{var h=Date.now();this.methodInvocationTime+=h-c;try{this.closeAll()}catch(f){p=p||f}}if(p)throw p;return l},initializeAll:function(){this._isInTransaction=!0;for(var e=this.transactionWrappers,t=this.timingMetrics.wrapperInitTimes,n=null,r=0;r<e.length;r++){var i=Date.now(),a=e[r];try{this.wrapperInitData[r]=a.initialize?a.initialize.call(this):null}catch(s){n=n||s,this.wrapperInitData[r]=o.OBSERVED_ERROR}finally{var u=t[r],l=Date.now();t[r]=(u||0)+(l-i)}}if(n)throw n},closeAll:function(){n(this.isInTransaction());for(var e=this.transactionWrappers,t=this.timingMetrics.wrapperCloseTimes,r=null,i=0;i<e.length;i++){var a=e[i],s=Date.now(),u=this.wrapperInitData[i];try{u!==o.OBSERVED_ERROR&&a.close&&a.close.call(this,u)}catch(l){r=r||l}finally{var c=Date.now(),p=t[i];t[i]=(p||0)+(c-s)}}if(this.wrapperInitData.length=0,this._isInTransaction=!1,r)throw r}},o={Mixin:r,OBSERVED_ERROR:{}};t.exports=o}()},{"./invariant":78}],60:[function(e,t){"use strict";var n={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){n.currentScrollLeft=document.body.scrollLeft+document.documentElement.scrollLeft,n.currentScrollTop=document.body.scrollTop+document.documentElement.scrollTop}};t.exports=n},{}],61:[function(e,t){"use strict";function n(e,t){if(r(null!=t),null==e)return t;var n=Array.isArray(e),o=Array.isArray(t);return n?e.concat(t):o?[e].concat(t):[e,t]}var r=e("./invariant");t.exports=n},{"./invariant":78}],62:[function(e,t){"use strict";function n(e){for(var t=1,n=0,o=0;o<e.length;o++)t=(t+e.charCodeAt(o))%r,n=(n+t)%r;return t|n<<16}var r=65521;t.exports=n},{}],63:[function(e,t){function n(e,t,n,r,o,i){e=e||{};for(var a,s=[t,n,r,o,i],u=0;s[u];){a=s[u++];for(var l in a)e[l]=a[l];a.hasOwnProperty&&a.hasOwnProperty("toString")&&"undefined"!=typeof a.toString&&e.toString!==a.toString&&(e.toString=a.toString)}return e}t.exports=n},{}],64:[function(e,t){function n(e,t){var n={},o=r(t);"undefined"==typeof t&&(t=!0);for(var i=e.length;i--;)n[e[i]]=o?t[i]:t;return n}var r=e("./hasArrayNature");t.exports=n},{"./hasArrayNature":75}],65:[function(e,t){"use strict";function n(e,t){var n=null==t||"boolean"==typeof t||""===t;if(n)return"";var o=isNaN(t);return o||0===t||r.isUnitlessNumber[e]?""+t:t+"px"}var r=e("./CSSProperty");t.exports=n},{"./CSSProperty":2}],66:[function(e,t){function n(e){return function(){return e}}function r(){}var o=e("./copyProperties");o(r,{thatReturns:n,thatReturnsFalse:n(!1),thatReturnsTrue:n(!0),thatReturnsNull:n(null),thatReturnsThis:function(){return this},thatReturnsArgument:function(e){return e}}),t.exports=r},{"./copyProperties":63}],67:[function(e,t){"use strict";function n(e){return i[e]}function r(e){var t=typeof e;return o("object"!==t),""===e?"":"string"===t?e.replace(/[&><"'\/]/g,n):(""+e).replace(/[&><"'\/]/g,n)}var o=e("./invariant"),i={"&":"&amp;",">":"&gt;","<":"&lt;",'"':"&quot;","'":"&#x27;","/":"&#x2f;"};t.exports=r},{"./invariant":78}],68:[function(e,t){var n=function(e){var t=Array.prototype.slice.call(arguments).map(function(e){return String(e)}),r=e.split("%s").length-1;return r!==t.length-1?n("ex args number mismatch: %s",JSON.stringify(t)):n._prefix+JSON.stringify(t)+n._suffix};n._prefix="<![EX[",n._suffix="]]>",t.exports=n},{}],69:[function(e,t){"use strict";function n(e,t,n){var r=e;o(!r.hasOwnProperty(n)),r[n]=t}function r(e){if(null==e)return e;var t={};return i(e,n,t),t}var o=e("./invariant"),i=e("./traverseAllChildren");t.exports=r},{"./invariant":78,"./traverseAllChildren":90}],70:[function(e,t){"use strict";var n=function(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)};t.exports=n},{}],71:[function(e,t){function n(e,t,n){return"string"!=typeof e?e:t?r(e,t,n):document.getElementById(e)}function r(e,t,n){var i,a,s;if(o(t)==e)return t;if(t.getElementsByTagName){for(a=t.getElementsByTagName(n||"*"),s=0;s<a.length;s++)if(o(a[s])==e)return a[s]}else for(a=t.childNodes,s=0;s<a.length;s++)if(i=r(e,a[s]))return i;return null}function o(e){var t=e.getAttributeNode&&e.getAttributeNode("id");return t?t.value:null}t.exports=n},{}],72:[function(e,t){!function(){"use strict";function n(e){var t=e.target||e.srcElement||r.global;return 3===t.nodeType?t.parentNode:t}var r=e("./ExecutionEnvironment");t.exports=n}()},{"./ExecutionEnvironment":19}],73:[function(e,t){"use strict";function n(e){return e&&e.firstChild}t.exports=n},{}],74:[function(e,t){"use strict";function n(){return!o&&r.canUseDOM&&(o="innerText"in document.createElement("div")?"innerText":"textContent"),o}var r=e("./ExecutionEnvironment"),o=null;t.exports=n},{"./ExecutionEnvironment":19}],75:[function(e,t){function n(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"length"in e&&!("setInterval"in e)&&"number"!=typeof e.nodeType&&(Array.isArray(e)||"callee"in e||"item"in e)}t.exports=n},{}],76:[function(e,t){function n(e){return e.replace(r,"-$1").toLowerCase()}var r=/([A-Z])/g;t.exports=n},{}],77:[function(e,t){"use strict";function n(e,t,n){var r=e.childNodes,o=e.childNodes[n];return o===t?t:(t.parentNode&&t.parentNode.removeChild(t),n>=r.length?e.appendChild(t):e.insertBefore(t,r[n]),t)}t.exports=n},{}],78:[function(e,t){function n(e){if(!e)throw new Error("Invariant Violation")}t.exports=n},{}],79:[function(e,t){"use strict";function n(e,t){if(!r||t&&!r.addEventListener)return!1;var n=document.createElement("div"),i="on"+e,a=i in n;return a||(n.setAttribute(i,""),a="function"==typeof n[i],"undefined"!=typeof n[i]&&(n[i]=void 0),n.removeAttribute(i)),!a&&o&&"wheel"===e&&(a=document.implementation.hasFeature("Events.wheel","3.0")),n=null,a}var r,o,i=e("./ExecutionEnvironment");i.canUseDOM&&(r=document.createElement("div"),o=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),t.exports=n},{"./ExecutionEnvironment":19}],80:[function(e,t){"use strict";function n(e){e||(e="");var t,n=arguments.length;if(n>1)for(var r=1;n>r;r++)t=arguments[r],t&&(e+=" "+t);return e}t.exports=n},{}],81:[function(e,t){"use strict";var n=e("./invariant"),r=function(e){var t,r={};n(e instanceof Object&&!Array.isArray(e));for(t in e)e.hasOwnProperty(t)&&(r[t]=t);return r};t.exports=r},{"./invariant":78}],82:[function(e,t){var n=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};t.exports=n},{}],83:[function(e,t){"use strict";function n(e){var t={};return function(n){return t.hasOwnProperty(n)?t[n]:t[n]=e.call(this,n)}}t.exports=n},{}],84:[function(e,t){"use strict";var n=e("./mergeInto"),r=function(e,t){var r={};return n(r,e),n(r,t),r};t.exports=r},{"./mergeInto":86}],85:[function(e,t){"use strict";var n=e("./invariant"),r=e("./keyMirror"),o=36,i=function(e){return"object"!=typeof e||null===e},a={MAX_MERGE_DEPTH:o,isTerminal:i,normalizeMergeArg:function(e){return void 0===e||null===e?{}:e},checkMergeArrayArgs:function(e,t){n(Array.isArray(e)&&Array.isArray(t))},checkMergeObjectArgs:function(e,t){a.checkMergeObjectArg(e),a.checkMergeObjectArg(t)},checkMergeObjectArg:function(e){n(!i(e)&&!Array.isArray(e))},checkMergeLevel:function(e){n(o>e)},checkArrayStrategy:function(e){n(void 0===e||e in a.ArrayStrategies)},ArrayStrategies:r({Clobber:!0,IndexByIndex:!0})};t.exports=a},{"./invariant":78,"./keyMirror":81}],86:[function(e,t){"use strict";function n(e,t){if(o(e),null!=t){o(t);for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])}}var r=e("./mergeHelpers"),o=r.checkMergeObjectArg;t.exports=n},{"./mergeHelpers":85}],87:[function(e,t){"use strict";var n=function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e.prototype[n]=t[n])};t.exports=n},{}],88:[function(e,t){"use strict";function n(e,t,n){if(!e)return null;var r=0,o={};for(var i in e)e.hasOwnProperty(i)&&(o[i]=t.call(n,i,e[i],r++));return o}t.exports=n},{}],89:[function(e,t){"use strict";var n=function(e,t){if(e)throw new Error(t)};t.exports=n},{}],90:[function(e,t){!function(){"use strict";function n(e,t,n){null!==e&&void 0!==e&&a(e,"",0,t,n)}var r=e("./ReactComponent"),o=e("./ReactTextComponent"),i=e("./invariant"),a=function(e,t,n,s,u){var l=0;if(Array.isArray(e))for(var c=0;c<e.length;c++){var p=e[c],d=t+"["+r.getKey(p,c)+"]",h=n+l;l+=a(p,d,h,s,u)}else{var f=typeof e,v=""===t,m=v?"["+r.getKey(e,0)+"]":t;if(null===e||void 0===e||"boolean"===f)s(u,null,m,n),l=1;else if(e.mountComponentIntoNode)s(u,e,m,n),l=1;else if("object"===f){i(e||1!==e.nodeType);for(var g in e)e.hasOwnProperty(g)&&(l+=a(e[g],t+"{"+g+"}",n+l,s,u))}else if("string"===f){var y=new o(e);s(u,y,m,n),l+=1}else if("number"===f){var C=new o(""+e);s(u,C,m,n),l+=1}}return l};t.exports=n}()},{"./ReactComponent":23,"./ReactTextComponent":48,"./invariant":78}]},{},[22])(22)});
ajax/libs/backbone-react-component/0.7.0/backbone-react-component-min.js
wenliang-developer/cdnjs
"use strict";!function(a,b){if("function"==typeof define&&define.amd)define(["react","backbone","underscore"],b);else if("undefined"!=typeof module&&module.exports){var c=require("react"),d=require("backbone"),e=require("underscore");module.exports=b(c,d,e)}else b(a.React,a.Backbone,a._)}(this,function(a,b,c){function d(a,b){b=b||{};var d=b.model,e=b.collection;"undefined"!=typeof d&&(d.attributes||"object"==typeof d&&c.values(d)[0].attributes)&&(delete b.model,this.model=d,this.setPropsBackbone(d,void 0,b)),"undefined"!=typeof e&&(e.models||"object"==typeof e&&c.values(e)[0].models)&&(delete b.collection,this.collection=e,this.setPropsBackbone(e,void 0,b)),this.component=a,a._owner||"undefined"==typeof document||(this.startModelListeners(),this.startCollectionListeners())}!b.React&&(b.React={}),!b.React.Component&&(b.React.Component={});b.React.Component.mixin={componentDidMount:function(){this.setElement(this.getDOMNode())},componentDidUpdate:function(){this.setElement(this.getDOMNode())},componentWillMount:function(){this.wrapper||(this.wrapper=new d(this,this.props))},componentWillUnmount:function(){this.wrapper&&(this.wrapper.stopListening(),delete this.wrapper)},componentWillReceiveProps:function(a){var b=a.model;if(this.wrapper.model&&b)if(delete a.model,this.wrapper.model.attributes)this.wrapper.setProps(b,void 0,a);else for(var c in b)this.wrapper.setProps(b[c],c,a)},$:function(){return this.$el&&this.$el.find.apply(this.$el,arguments)},getCollection:function(){for(var a=this,b=a.wrapper;!b.collection;){if(a=a._owner,!a)throw new Error("Collection not found");b=a.wrapper}return b.collection},getModel:function(){for(var a=this,b=a.wrapper;!b.model;){if(a=a._owner,!a)throw new Error("Model not found");b=a.wrapper}return b.model},getOwner:function(){for(var a=this;a._owner;)a=a._owner;return a},setElement:function(a){if(a&&b.$&&a instanceof b.$){if(a.length>1)throw new Error("You can only assign one element to a component");this.el=a[0],this.$el=a}else a&&(this.el=a,b.$&&(this.$el=b.$(a)));return this}};return c.extend(d.prototype,b.Events,{onError:function(a,b,c){c.silent||this.setProps({isRequesting:!1,hasError:!0,error:b})},onRequest:function(a,b,c){c.silent||this.setProps({isRequesting:!0,hasError:!1})},onSync:function(a,b,c){c.silent||this.setProps({isRequesting:!1})},setPropsBackbone:function(a,b,c){if(a.models||a.attributes)this.setProps.apply(this,arguments);else for(b in a)this.setPropsBackbone(a[b],b,c)},setProps:function(a,d,e){var f={},g=a.toJSON?a.toJSON():a;d?f[d]=g:a instanceof b.Collection?f.collection=g:f=g,e?c.extend(e,f):(this.nextProps=c.extend(this.nextProps||{},f),c.defer(c.bind(function(){this.nextProps&&(this.component&&this.component.setProps(this.nextProps),delete this.nextProps)},this)))},startCollectionListeners:function(a,b){if(a||(a=this.collection),a)if(a.models)this.listenTo(a,"add remove change sort reset",c.partial(this.setPropsBackbone,a,b,void 0)).listenTo(a,"error",this.onError).listenTo(a,"request",this.onRequest).listenTo(a,"sync",this.onSync);else if("object"==typeof a)for(b in a)a.hasOwnProperty(b)&&this.startCollectionListeners(a[b],b)},startModelListeners:function(a,b){if(a||(a=this.model),a)if(a.attributes)this.listenTo(a,"change",c.partial(this.setPropsBackbone,a,b,void 0)).listenTo(a,"error",this.onError).listenTo(a,"request",this.onRequest).listenTo(a,"sync",this.onSync);else if("object"==typeof a)for(b in a)this.startModelListeners(a[b],b)}}),b.React.Component.mixin});
example/pages/input/index.js
woshisbb43/coinMessageWechat
import React from 'react'; import { ButtonArea, Button, CellsTitle, CellsTips, Cell, CellHeader, CellBody, CellFooter, Form, FormCell, Icon, Input, Label, TextArea, Switch, Radio, Checkbox, Select, VCode, Agreement, Toptips } from '../../../build/packages'; import Page from '../../component/page'; import iconSrc from './images/icon.png'; import vcodeSrc from './images/vcode.jpg'; import avatarSrc from './images/avatar.jpg'; export default class inputDemo extends React.Component { constructor(props){ super(props); this.state = { showToptips: false } } render(){ return ( <Page className="input" title="Input" subTitle="表单输入"> <CellsTitle>Radio</CellsTitle> <Form radio> <FormCell radio> <CellBody>Option 1</CellBody> <CellFooter> <Radio name="radio1" value="1" defaultChecked/> </CellFooter> </FormCell> <FormCell radio> <CellBody>Option 2</CellBody> <CellFooter> <Radio name="radio1" value="2"/> </CellFooter> </FormCell> <Cell link> <CellBody>More</CellBody> </Cell> </Form> <CellsTitle>Checkbox</CellsTitle> <Form checkbox> <FormCell checkbox> <CellHeader> <Checkbox name="checkbox1" value="1"/> </CellHeader> <CellBody>Option 1</CellBody> </FormCell> <FormCell checkbox> <CellHeader> <Checkbox name="checkbox2" value="2" defaultChecked/> </CellHeader> <CellBody>Option 2</CellBody> </FormCell> <Cell link> <CellBody>More</CellBody> </Cell> </Form> <CellsTitle>Switch</CellsTitle> <Form> <FormCell switch> <CellBody>Switch Label</CellBody> <CellFooter> <Switch/> </CellFooter> </FormCell> </Form> <CellsTitle>Forms</CellsTitle> <Form> <FormCell> <CellHeader> <Label>QQ</Label> </CellHeader> <CellBody> <Input type="tel" placeholder="Enter your qq#"/> </CellBody> </FormCell> <FormCell vcode> <CellHeader> <Label>Phone</Label> </CellHeader> <CellBody> <Input type="tel" placeholder="Enter your cellphone #"/> </CellBody> <CellFooter> <Button type="vcode">Send</Button> </CellFooter> </FormCell> <FormCell> <CellHeader> <Label>Date</Label> </CellHeader> <CellBody> <Input type="date" defaultValue="" onChange={ e=> console.log(e.target.value)}/> </CellBody> </FormCell> <FormCell> <CellHeader> <Label>Datetime</Label> </CellHeader> <CellBody> <Input type="datetime-local" defaultValue="" placeholder=""/> </CellBody> </FormCell> <FormCell vcode> <CellHeader> <Label>VCode</Label> </CellHeader> <CellBody> <Input type="number" placeholder="Enter the code"/> </CellBody> <CellFooter> <VCode src={vcodeSrc} /> </CellFooter> </FormCell> </Form> <CellsTips>Form Footer Tips</CellsTips> <CellsTitle>Warnings</CellsTitle> <Form> <FormCell warn> <CellHeader> <Label>QQ</Label> </CellHeader> <CellBody> <Input type="text" defaultValue="Oops..."/> </CellBody> <CellFooter> <Icon value="warn" /> </CellFooter> </FormCell> </Form> <CellsTitle>Textarea</CellsTitle> <Form> <FormCell> <CellBody> <TextArea placeholder="Enter your comments" rows="3" maxlength="200"></TextArea> </CellBody> </FormCell> </Form> <CellsTitle>选择</CellsTitle> <Form> <FormCell select selectPos="before"> <CellHeader> <Select> <option value="1">+86</option> <option value="2">+80</option> <option value="3">+84</option> <option value="4">+87</option> </Select> </CellHeader> <CellBody> <Input type="tel" placeholder="Enter Phone"/> </CellBody> </FormCell> </Form> <CellsTitle>Selects</CellsTitle> <Form> <FormCell select> <CellBody> <Select defaultValue="2"> <option value="1">WeChat</option> <option value="2">QQ</option> <option value="3">Email</option> </Select> </CellBody> </FormCell> <FormCell select selectPos="after"> <CellHeader> <Label>Country</Label> </CellHeader> <CellBody> <Select data={[ { value: 1, label: 'China' }, { value: 2, label: 'United States' }, { value: 3, label: 'Germany' } ]} /> </CellBody> </FormCell> </Form> <Agreement> &nbsp;&nbsp;I agree to the <a href="javascript:;">WeUI Terms and Privacy</a> </Agreement> <ButtonArea> <Button //button to display toptips onClick={ e=> { if(this.state.showToptips) return; this.setState({showToptips: !this.state.showToptips}) window.setTimeout(e=> this.setState({showToptips: !this.state.showToptips}), 2000) } }> OK </Button> </ButtonArea> <Toptips type="warn" show={this.state.showToptips} > Oops, something is wrong! </Toptips> </Page> ) } }
examples/universal/webpack.config.js
edge/redux
var path = require('path') var webpack = require('webpack') module.exports = { devtool: 'inline-source-map', entry: [ 'webpack-hot-middleware/client', './client/index.js' ], output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', publicPath: '/static/' }, plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], module: { loaders: [ { test: /\.js$/, loader: 'babel', exclude: /node_modules/, include: __dirname, query: { presets: [ 'react-hmre' ] } } ] } } // When inside Redux repo, prefer src to compiled version. // You can safely delete these lines in your project. var reduxSrc = path.join(__dirname, '..', '..', 'src') var reduxNodeModules = path.join(__dirname, '..', '..', 'node_modules') var fs = require('fs') if (fs.existsSync(reduxSrc) && fs.existsSync(reduxNodeModules)) { // Resolve Redux to source module.exports.resolve = { alias: { 'redux': reduxSrc } } // Compile Redux from source module.exports.module.loaders.push({ test: /\.js$/, loaders: [ 'babel' ], include: reduxSrc, }) }
modules/ScrollManagementMixin.js
apoco/react-router
import React from 'react'; import { canUseDOM, setWindowScrollPosition } from './DOMUtils'; import NavigationTypes from './NavigationTypes'; var { func } = React.PropTypes; function getCommonAncestors(branch, otherBranch) { return branch.filter(route => otherBranch.indexOf(route) !== -1); } function shouldUpdateScrollPosition(state, prevState) { var { location, branch } = state; var { location: prevLocation, branch: prevBranch } = prevState; // When an onEnter hook uses transition.to to redirect // on the initial load prevLocation is null, so assume // we don't want to update the scroll position. if (prevLocation === null) return false; // Don't update scroll position if only the query has changed. if (location.pathname === prevLocation.pathname) return false; // Don't update scroll position if any of the ancestors // has `ignoreScrollPosition` set to `true` on the route. var sharedAncestors = getCommonAncestors(branch, prevBranch); if (sharedAncestors.some(route => route.ignoreScrollBehavior)) return false; return true; } function updateWindowScrollPosition(navigationType, scrollX, scrollY) { if (canUseDOM) { if (navigationType === NavigationTypes.POP) { setWindowScrollPosition(scrollX, scrollY); } else { setWindowScrollPosition(0, 0); } } } var ScrollManagementMixin = { propTypes: { shouldUpdateScrollPosition: func.isRequired, updateScrollPosition: func.isRequired }, getDefaultProps() { return { shouldUpdateScrollPosition, updateScrollPosition: updateWindowScrollPosition }; }, componentDidUpdate(prevProps, prevState) { var { location } = this.state; var locationState = location && location.state; if (locationState && this.props.shouldUpdateScrollPosition(this.state, prevState)) { var { scrollX, scrollY } = locationState; this.props.updateScrollPosition(location.navigationType, scrollX || 0, scrollY || 0); } } }; export default ScrollManagementMixin;
ajax/libs/forerunnerdb/1.3.335/fdb-core+views.js
cdnjs/cdnjs
(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){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":29,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":28}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { var sortKey; this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; for (sortKey in orderBy) { if (orderBy.hasOwnProperty(sortKey)) { this._keyArr.push({ key: sortKey, dir: orderBy[sortKey] }); } } }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof obj[sortType.key]; if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.dir === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.dir === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += obj[sortType.key]; } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Shared":27}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (!(index instanceof Array)) { // Convert the index object to an array of key val objects index = this.keys(index); } } return this.$super.call(this, index); }); BinaryTree.prototype.keys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return true; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._index.length; i++) { indexData = this._index[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return result; } } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._index.length; i++) { indexData = this._index[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._index[0].key]; }; BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (!this._data) { // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === -1) { // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === 1) { // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'key': resultArr.push(this._data); break; default: resultArr.push({ key: this._key, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Shared":27}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this._onChange(); this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value return new Path(query.substr(3, query.length - 3)).value(item)[0]; } return new Path(query).value(item)[0]; } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":8,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":27}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":27}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } callback(); }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":13,"./Overload":24,"./Shared":27}],8:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":13,"./Overload":24,"./Shared":27}],10:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":25,"./Shared":27}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":25,"./Shared":27}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":27}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":23,"./Shared":27}],14:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],15:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],16:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":24}],17:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],18:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":24}],19:[function(_dereq_,module,exports){ "use strict"; var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) { return true; } else if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; } return -1; } }; module.exports = Matching; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":24}],22:[function(_dereq_,module,exports){ "use strict"; var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":25,"./Shared":27}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":27}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactoreOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":27}],27:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.335', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],28:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],29:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._transformPrimaryKey(source.primaryKey()); this._transformSetData(collData); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, //tempData, //dataIsArray, updates, //finalUpdates, primaryKey, tQuery, item, currentIndex, i; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); // Modify transform data this._transformSetData(collData); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; // Modify transform data this._transformInsert(chainPacket.data, insertIndex); this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } if (this._transformEnabled && this._transformIn) { primaryKey = this._publicData.primaryKey(); for (i = 0; i < updates.length; i++) { tQuery = {}; item = updates[i]; tQuery[primaryKey] = item[primaryKey]; this._transformUpdate(tQuery, item); } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } // Modify transform data this._transformRemove(chainPacket.data.query, chainPacket.options); this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._privateData.distinct.apply(this._privateData, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._privateData.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function () { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } else { return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } // Update the transformed data object this._transformPrimaryKey(this.privateData().primaryKey()); this._transformSetData(this.privateData().find()); return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; /** * Updates the public data object to match data from the private data object * by running private data through the dataIn method provided in * the transform() call. * @private */ View.prototype._transformSetData = function (data) { if (this._transformEnabled) { // Clear existing data this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); this._publicData.setData(data); } }; View.prototype._transformInsert = function (data, index) { if (this._transformEnabled && this._publicData) { this._publicData.insert(data, index); } }; View.prototype._transformUpdate = function (query, update, options) { if (this._transformEnabled && this._publicData) { this._publicData.update(query, update, options); } }; View.prototype._transformRemove = function (query, options) { if (this._transformEnabled && this._publicData) { this._publicData.remove(query, options); } }; View.prototype._transformPrimaryKey = function (key) { if (this._transformEnabled && this._publicData) { this._publicData.primaryKey(key); } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (!this._view[viewName]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":26,"./Shared":27}]},{},[1]);
src/sagas/storage.js
connectordb/connectordb-android
/* This file handles the storage of all relevant values. All credentials and app settings are stored asynchronously here. */ import { AsyncStorage } from 'react-native'; import { put, takeEvery, select, call } from 'redux-saga/effects' const CREDENTIALS = '@CDB:credentials'; const INPUTS = '@CDB:inputs'; const DOWNLINKS = '@CDB:downlinks'; // Loads all of the data that is stored in storage. This function initializes the app from a cold-boot. function* loadStorage() { // First, load the credentials if such exist try { let cred = yield call(AsyncStorage.getItem, CREDENTIALS); // Set up the credentials if (cred != null) { cred = JSON.parse(cred); yield put({ type: "SET_CREDENTIALS", value: cred, storage: false }); if (cred.apikey !== undefined && cred.apikey != "") { // There is an API key. Try loading the inputs and downlinks let inputs = yield call(AsyncStorage.getItem, INPUTS); if (inputs != null) yield put({ type: "UPDATE_INPUTS", value: JSON.parse(inputs), storage: false }); let downlinks = yield call(AsyncStorage.getItem, DOWNLINKS); if (downlinks != null) yield put({ type: "UPDATE_DOWNLINKS", value: JSON.parse(downlinks), storage: false }); } } } catch (error) { // If there is an error, we don't do anything. It means that the app is simply uninitialized } // The app is finished with initial loading, so hide the loading screen yield put({ type: "LOAD_FINISHED" }); } // Clear the keys when logging out function* logOut() { yield call(AsyncStorage.multiRemove, [CREDENTIALS, INPUTS, DOWNLINKS]); } function* updater(action, key) { if (action.storage !== undefined && !action.storage) { return; // We don't want to store things that were called from storage code. } yield call(AsyncStorage.setItem, key, JSON.stringify(action.value)); } // Every time new credentials are stored, we also update the storage. This tries to merge the data first. function* setCredentials(action) { if (action.storage !== undefined && !action.storage) { return; // We don't want to store things that were called from storage code. } try { yield call(AsyncStorage.mergeItem, CREDENTIALS, JSON.stringify(action.value)); } catch (error) { yield call(AsyncStorage.setItem, CREDENTIALS, JSON.stringify(action.value)); } } // Same for inputs and downlinks function* updateInputs(action) { yield* updater(action, INPUTS); } function* updateDownlinks(action) { yield* updater(action, DOWNLINKS); } // Our watcher Saga: spawn a new incrementAsync task on each INCREMENT_ASYNC export default function* storageSaga() { yield takeEvery('LOAD_STORAGE', loadStorage); yield takeEvery('LOGOUT', logOut); yield takeEvery('SET_CREDENTIALS', setCredentials); yield takeEvery('UPDATE_INPUTS', updateInputs); yield takeEvery('UPDATE_DOWNLINKS', updateDownlinks); }
src/js/components/place.js
mdrobny/hack-place
import React from 'react'; import placesStore from '../utils/places'; var PlaceView = React.createClass({ displayName: 'PlaceView', propTypes: { params: React.PropTypes.object }, getInitialState() { return { place: null }; }, componentDidMount() { this.fetchData(); }, fetchData() { var id = this.props.params.id; placesStore.fetchOne(id, () => { var place = placesStore.getOne(); console.log(place); this.setState({place: place}); }); }, render() { var viewData; if (this.state.place) { var imgSrc = 'http://pdziok.vgnett.no/enably.ng-api/upload/' + this.state.place.image.filename; viewData = (<div className="pure-g"> <div className="pure-u-1-5 col"></div> <div className="pure-u-2-5 col"> <div className="place-view"> <div className="place-img"> <img src = {imgSrc} /> </div> <div className="place-description"> <p>{this.state.place.name}</p> <br /> <p>{this.state.place.description}</p> </div> </div> </div> <div className="pure-u-1-5 col map"> <div className="place-likes"> <div className="ratings"> <div className="rating pluses"> <img src="images/happy.png"/> <span className="rating-value">{this.state.place.rating.pluses}</span> </div> <div className="rating minuses"> <img src="images/sad.png"/> <span className="rating-value">{this.state.place.rating.minuses}</span> </div> </div> </div> </div> <div className="pure-u-1-5 col"></div> </div>); } else { viewData = <div></div>; } return viewData; } }); export default PlaceView;
ajax/libs/material-ui/4.9.13/es/internal/svg-icons/MoreHoriz.min.js
cdnjs/cdnjs
import*as React from"react";import createSvgIcon from"../../utils/createSvgIcon";export default createSvgIcon(React.createElement("path",{d:"M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"}),"MoreHoriz");
Console/app/node_modules/antd/es/input-number/index.js
RisenEsports/RisenEsports.github.io
import _extends from 'babel-runtime/helpers/extends'; import _defineProperty from 'babel-runtime/helpers/defineProperty'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _createClass from 'babel-runtime/helpers/createClass'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; var __rest = this && this.__rest || function (s, e) { var t = {}; for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; }if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; }return t; }; import React from 'react'; import classNames from 'classnames'; import RcInputNumber from 'rc-input-number'; var InputNumber = function (_React$Component) { _inherits(InputNumber, _React$Component); function InputNumber() { _classCallCheck(this, InputNumber); return _possibleConstructorReturn(this, (InputNumber.__proto__ || Object.getPrototypeOf(InputNumber)).apply(this, arguments)); } _createClass(InputNumber, [{ key: 'render', value: function render() { var _classNames; var _a = this.props, className = _a.className, size = _a.size, others = __rest(_a, ["className", "size"]); var inputNumberClass = classNames((_classNames = {}, _defineProperty(_classNames, this.props.prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, this.props.prefixCls + '-sm', size === 'small'), _classNames), className); return React.createElement(RcInputNumber, _extends({ className: inputNumberClass }, others)); } }]); return InputNumber; }(React.Component); export default InputNumber; InputNumber.defaultProps = { prefixCls: 'ant-input-number', step: 1 };
docs/src/pages/components/transitions/SimpleSlide.js
lgollut/material-ui
import React from 'react'; import Switch from '@material-ui/core/Switch'; import Paper from '@material-ui/core/Paper'; import Slide from '@material-ui/core/Slide'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ root: { height: 180, }, wrapper: { width: 100 + theme.spacing(2), }, paper: { zIndex: 1, position: 'relative', margin: theme.spacing(1), }, svg: { width: 100, height: 100, }, polygon: { fill: theme.palette.common.white, stroke: theme.palette.divider, strokeWidth: 1, }, })); export default function SimpleSlide() { const classes = useStyles(); const [checked, setChecked] = React.useState(false); const handleChange = () => { setChecked((prev) => !prev); }; return ( <div className={classes.root}> <div className={classes.wrapper}> <FormControlLabel control={<Switch checked={checked} onChange={handleChange} />} label="Show" /> <Slide direction="up" in={checked} mountOnEnter unmountOnExit> <Paper elevation={4} className={classes.paper}> <svg className={classes.svg}> <polygon points="0,100 50,00, 100,100" className={classes.polygon} /> </svg> </Paper> </Slide> </div> </div> ); }
tests/Rules-isLength-spec.js
sdemjanenko/formsy-react
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import Formsy from './..'; import { InputFactory } from './utils/TestInput'; const TestInput = InputFactory({ render() { return <input value={this.getValue()} readOnly/>; } }); const TestForm = React.createClass({ render() { return ( <Formsy.Form> <TestInput name="foo" validations={this.props.rule} value={this.props.inputValue}/> </Formsy.Form> ); } }); export default { 'isLength:3': { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a string too small': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue="hi"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should fail with a string too long': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue="hi ho happ"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with matching length': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue="foo"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:3" inputValue={123}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); } }, 'isLength:0': { 'should pass with a default value': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a string too small': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue="hi"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should fail with a string too long': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue="hi ho happ"/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); }, 'should pass with matching length': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with undefined': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue={undefined}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with null': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue={null}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should pass with empty string': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue=""/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), true); test.done(); }, 'should fail with a number': function (test) { const form = TestUtils.renderIntoDocument(<TestForm rule="isLength:0" inputValue={123}/>); const inputComponent = TestUtils.findRenderedComponentWithType(form, TestInput); test.equal(inputComponent.isValid(), false); test.done(); } } };
src/svg-icons/action/lock.js
ruifortes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLock = (props) => ( <SvgIcon {...props}> <path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/> </SvgIcon> ); ActionLock = pure(ActionLock); ActionLock.displayName = 'ActionLock'; ActionLock.muiName = 'SvgIcon'; export default ActionLock;
src/components/util/Alert.js
mailvelope/mailvelope
/** * Copyright (C) 2017 Mailvelope GmbH * Licensed under the GNU Affero General Public License version 3 */ import React from 'react'; import PropTypes from 'prop-types'; /** * Alert */ export default function Alert({className, id, header, children: message, type}) { return ( <div id={id} className={`alert alert-${type} fade show ${className || ''}`} role="alert"> {header && <strong>{`${header} `}</strong>} {message} </div> ); } Alert.propTypes = { className: PropTypes.string, id: PropTypes.string, header: PropTypes.string, children: PropTypes.node.isRequired, type: PropTypes.oneOf(['success', 'info', 'warning', 'danger']), }; Alert.defaultProps = { type: 'info' };
packages/bonde-admin-canary/src/scenes/Auth/scenes/ResetPassword/index.js
ourcities/rebu-client
import React from 'react' import { I18n } from 'react-i18next' import { Query } from 'react-apollo' import { AuthAPI } from 'services/auth' import { notify } from 'components/Notification' import tokenVerify from './tokenVerify.graphql' import CheckingToken from './CheckingToken' import InvalidToken from './InvalidToken' import ResetPasswordForm from './ResetPasswordForm' export default ({ match }) => ( <I18n ns='auth'> {t => { const token = match.params.token return ( <Query query={tokenVerify} variables={{ token }}> {({ data, loading, error }) => { if (loading) return <CheckingToken t={t} /> if (error) return <InvalidToken t={t} /> return ( <ResetPasswordForm t={t} token={token} handleSuccess={({ data }) => { const { changePasswordField } = data.resetPasswordChangePassword const user = { name: changePasswordField.userFirstName } AuthAPI.login({ jwtToken: changePasswordField.token }) .then(() => { notify(t('resetPassword.success', { user })) // should redirect with window to rehydrate session window.location.href = '/' }) }} /> ) }} </Query> ) }} </I18n> )
test/server/ModalSpec.js
snadn/react-bootstrap
import React from 'react'; import {assert} from 'chai'; import Modal from '../../src/Modal.js'; describe('Modal', () => { it('Should be rendered on the server side', function () { let noOp = () => {}; assert.doesNotThrow(function renderOnServerSide() { return React.renderToString( <Modal onHide={noOp}> <strong>Message</strong> </Modal> ); }); }); });